diff options
| author | Pjotr <wrk@bosa.lan> | 2026-11-10 13:34:29 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-11-10 13:34:29 +0000 |
| commit | 9ea2fa0f0d5336814a0c62020b20f55f4394874f (patch) | |
| tree | 7f81ca483528417c5e96324834faf81c842b91db /src | |
| parent | d5164d9f94aee148fe76d91b1956cf5ef97b3e69 (diff) | |
| download | genenetwork4-9ea2fa0f0d5336814a0c62020b20f55f4394874f.tar.gz | |
genotypes: a trait summarised per genotype class at one marker
The question that follows "why do GEMMA and R/qtl2 peak at different
markers": what does the trait look like within each genotype class at one
marker. The frequencies endpoints report the distribution of calls, not
the values behind them, and the answer must not be "serve the matrix" --
this API never does.
GET /groups/{group}/genotypes/{version}/markers/{marker}/classes?trait=<id>
-> {"A": {"n", "mean", "sd", "min", "max"}, "H": {...}, "B": {...}}
The calls are joined to the trait's per-strain values inside the server
(the same lookup, authorization and 404s as /groups/{g}/traits/{id}/values)
and reduced to those five numbers per class. Nothing in the payload names
an animal. A class with fewer than ten animals is called out in notes,
because a peak resting on two is a different claim from one resting on a
hundred.
It settles the DOL trait 10003 question. At GEMMA's top marker
JAX00418132 (chr16 36.35 Mb) the classes are A n=2 mean 1.8, H n=20 mean
2.53, B n=171 mean 3.95 -- the A class is two animals and they are the
trait's two lowest values. R/qtl2 drops H on a riself panel (R/qtl's
convert2riself), so it keeps 173 animals there but only 2 of one class:
nearly monomorphic, which is why its scan peaks elsewhere. GEMMA keeps
the 20 hets at dosage 0.5, and that is where its sharper p-value comes
from. GEMMA's next two hits are the same pattern in opposite directions
(one A among 171, then two B among 171), so the chr16 block is a haplotype
carried by a handful of extreme animals, not a population effect.
Also fixes the reading of GEMMA's `af`: it is mean(dosage)/2 under the
BIMBAM coding this deployment ships (B=1, H=0.5, A=0), so 0.469 for
JAX00418132 is half the B-allele frequency 0.935, not the A-allele
frequency 0.065. The bimbam file and DOL.geno agree at that marker.
tests/frequencies.rs gains a route test: the class fields, A < B, the
small-class note, the "not served" note, no individual names anywhere in
the payload, and a 404 for a trait the group does not have.
Diffstat (limited to 'src')
| -rw-r--r-- | src/frequencies.rs | 91 | ||||
| -rw-r--r-- | src/lib.rs | 1 | ||||
| -rw-r--r-- | src/routes/frequencies.rs | 252 | ||||
| -rw-r--r-- | src/routes/groups.rs | 6 | ||||
| -rw-r--r-- | src/routes/probesets.rs | 2 |
5 files changed, 348 insertions, 4 deletions
diff --git a/src/frequencies.rs b/src/frequencies.rs index 971451f..31ac403 100644 --- a/src/frequencies.rs +++ b/src/frequencies.rs @@ -437,3 +437,94 @@ mod tests { ); } } + +/// One marker's genotype calls, in the file's individual order: `(name, +/// Some(call))` where a call is present, `(name, None)` where it is missing. +/// +/// This is the per-animal row the tally deliberately does not return -- it +/// stays inside the server, joined to a trait's values and reduced to a +/// per-class summary (see `GET .../markers/{marker}/classes`). It is never +/// serialised: the endpoint above it answers with statistics, not calls. +pub struct MarkerCalls { + pub chr: Option<String>, + pub cm: Option<f64>, + pub mb: Option<f64>, + pub calls: Vec<(String, Option<String>)>, +} + +/// Read one marker's calls. The header defines the individuals; a row may be +/// shorter than the header (a truncated file), and those individuals are +/// missing rather than absent. +pub fn marker_calls(geno: &Path, marker: &str) -> Result<MarkerCalls, FreqError> { + let metadata = std::fs::metadata(geno) + .map_err(|error| FreqError::NotFound(format!("{}: {error}", geno.display())))?; + if metadata.len() > MAX_SCAN_BYTES { + return Err(FreqError::TooLarge(format!( + "{} is {} MB, past the {} MB a per-marker read scans; pick a smaller version", + geno.display(), + metadata.len() / (1024 * 1024), + MAX_SCAN_BYTES / (1024 * 1024) + ))); + } + let file = std::fs::File::open(geno) + .map_err(|error| FreqError::Io(format!("{}: {error}", geno.display())))?; + let mut individuals: Vec<String> = Vec::new(); + let mut start = 3usize; + let mut found: Option<MarkerCalls> = None; + for line in BufReader::with_capacity(1 << 20, file).lines() { + let line = line.map_err(|error| FreqError::Io(format!("{}: {error}", geno.display())))?; + let line = line.trim_end_matches('\r'); + if line.trim().is_empty() || line.starts_with('#') || line.starts_with('@') { + continue; + } + let columns: Vec<&str> = line.split('\t').collect(); + if individuals.is_empty() { + start = if columns.len() > 3 && columns[3] == "Mb" { + 4 + } else { + 3 + }; + individuals = columns[start.min(columns.len())..] + .iter() + .map(|name| name.trim().to_string()) + .collect(); + if individuals.is_empty() { + return Err(FreqError::NotFound(format!( + "{}: the header names no individuals", + geno.display() + ))); + } + continue; + } + if columns.get(1).map(|name| name.trim()) != Some(marker) { + continue; + } + let number = |index: usize| -> Option<f64> { + columns + .get(index) + .and_then(|value| value.trim().parse().ok()) + }; + let calls = individuals + .iter() + .enumerate() + .map(|(index, name)| { + let call = columns.get(start + index).map(|cell| cell.trim()); + let call = call.filter(|cell| !is_missing(cell)); + (name.clone(), call.map(str::to_string)) + }) + .collect(); + found = Some(MarkerCalls { + chr: columns.first().map(|chr| chr.trim().to_string()), + cm: number(2), + mb: number(3).or_else(|| number(2)), + calls, + }); + break; + } + found.ok_or_else(|| { + FreqError::NotFound(format!( + "{}: no marker '{marker}'", + geno.display() + )) + }) +} diff --git a/src/lib.rs b/src/lib.rs index caefdbf..62317eb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -131,6 +131,7 @@ pub fn app() -> Router { .routes(routes!(routes::frequencies::group_marker_frequencies)) .routes(routes!(routes::frequencies::unlisted_frequencies)) .routes(routes!(routes::frequencies::unlisted_marker_frequencies)) + .routes(routes!(routes::frequencies::marker_classes)) .routes(routes!(routes::genotypes::group_genotypes)) .routes(routes!(routes::genotypes::group_genotype_version)) .routes(routes!(routes::genotypes::group_genotype_markers)) diff --git a/src/routes/frequencies.rs b/src/routes/frequencies.rs index 2d45337..e9bc73f 100644 --- a/src/routes/frequencies.rs +++ b/src/routes/frequencies.rs @@ -382,3 +382,255 @@ fn map_genotype_error(error: genotypes::GenotypeError, rid: RequestInfo) -> ApiE .with_request_id(rid), } } + +// --------------------------------------------------------------------------- +// `GET /groups/{group}/genotypes/{version}/markers/{marker}/classes` +// +// The question that follows "why do GEMMA and R/qtl2 peak at different +// markers": what the trait looks like within each genotype class at one +// marker. It cannot be answered from the endpoints above -- they report the +// distribution of calls, not the values behind them -- and it must not be +// answered by serving genotypes, which this API never does. +// +// So the calls stay inside the server: they are joined to a trait's per-strain +// values (with that trait's own authorization) and reduced to n/mean/sd/min/max +// per class. A caller learns "the two A animals are 5.9 and 6.0" as +// `{"n": 2, "mean": 5.95, ...}` and never learns which animal carried which +// allele. +// --------------------------------------------------------------------------- + +#[derive(Deserialize, utoipa::IntoParams)] +pub struct ClassParams { + /// The trait whose values are summarised, as `/groups/{group}/traits` + /// reports its id (a PublishXRef.Id). `trait` is a Rust keyword, hence + /// the serde rename. + #[serde(rename = "trait")] + pub trait_id: u32, +} + +#[utoipa::path(get, path = "/groups/{group}/genotypes/{version}/markers/{marker}/classes", + summary = "A trait's values summarised per genotype class at one marker", + description = "n, mean, sd, min and max of a published trait within each genotype class \ +(A, H, B, or whatever codes the file uses) at one marker. This is how a caller checks whether a \ +peak rests on a handful of animals -- or whether the class a scan cannot use, like a nearly \ +monomorphic biallelic marker, is where another scan's signal lives. The calls are joined to the \ +trait's values inside the server and only the summary is returned; individual genotypes are \ +never served, and the trait's own authorization applies.", + params( + ("group" = String, Path, description = "InbredSet name, e.g. DOL"), + ("version" = String, Path, description = "Version from /groups/{group}/genotypes"), + ("marker" = String, Path, description = "Marker name as the genotype file spells it"), + ClassParams + ), + responses( + (status = 200, description = "class -> {n, mean, sd, min, max}", body = Envelope<serde_json::Value>), + Unauthorized, + (status = 403, description = "The trait is not public and you are not authorized", body = ApiError), + (status = 404, description = "No such group, version, marker or trait", body = ApiError) + ) +)] +#[gnauth(secured)] +pub async fn marker_classes( + ctx: Ctx, + Path((group, version, marker)): Path<(String, String, String)>, + Query(params): Query<ClassParams>, + token: AuthToken, +) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { + let rid = ctx.request_info(); + let config = Config::load(); + let root = config.genotype_files_dir.clone(); + let auth_server_url = config.auth_server_url.clone(); + let trait_id = params.trait_id; + + // The genotype side: which individual carries which call at this marker. + let (wanted_group, wanted_version, wanted_marker) = + (group.clone(), version.clone(), marker.clone()); + let calls = tokio::task::spawn_blocking(move || { + let resolved = genotypes::resolve( + std::path::Path::new(&root), + &wanted_group, + Some(&wanted_version), + ) + .map_err(|error| FreqError::NotFound(error.to_string()))?; + frequencies::marker_calls(&resolved.geno, &wanted_marker) + }) + .await + .map_err(|error| internal(error.to_string(), rid.clone()))? + .map_err(|error| map_error(error, rid.clone()))?; + + // The trait side: the same lookup, authorization and 404s as + // /groups/{group}/traits/{id}/values. + let (wanted_group, wanted_version) = (group.clone(), version.clone()); + let values = tokio::task::spawn_blocking(move || { + crate::routes::groups::get_group_trait_values_result( + &wanted_group, + trait_id, + &auth_server_url, + &token, + ) + }) + .await + .map_err(|error| internal(error.to_string(), rid.clone()))?; + let values = match values { + Ok(crate::routes::groups::GroupTraitLookup::Found(authorized, values)) => { + let _: crate::auth::Authorized = authorized; + values + } + Ok(crate::routes::groups::GroupTraitLookup::Forbidden) => { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "forbidden", + "Not authorized", + format!("trait {trait_id} is not public, and you are not authorized to view it."), + "marker_classes", + ) + .with_request_id(rid)); + } + Ok(crate::routes::groups::GroupTraitLookup::GroupNotFound) => { + return Err(ApiError::new( + StatusCode::NOT_FOUND, + "group_not_found", + "Group not found", + format!("No group matching '{group}'."), + "marker_classes", + ) + .with_request_id(rid)); + } + Ok(crate::routes::groups::GroupTraitLookup::TraitNotFound) => { + return Err(ApiError::new( + StatusCode::NOT_FOUND, + "trait_not_found", + "Trait not found", + format!("No trait {trait_id} in group '{group}'."), + "marker_classes", + ) + .with_request_id(rid)); + } + Err(crate::routes::groups::GroupAuthError::Db(error)) => { + return Err(ApiError::from_db(error, "marker_classes").with_request_id(rid)); + } + Err(crate::routes::groups::GroupAuthError::Auth(detail)) => { + return Err(ApiError::new( + StatusCode::BAD_GATEWAY, + "auth_server_error", + "Could not check authorization", + detail, + "marker_classes", + ) + .with_request_id(rid)); + } + }; + + // Join by individual name, then summarise per class. + let by_name: std::collections::HashMap<&str, Option<f64>> = values + .iter() + .map(|value| (value.name.as_str(), value.value)) + .collect(); + let mut classes: std::collections::BTreeMap<String, Vec<f64>> = + std::collections::BTreeMap::new(); + let mut without_call = 0usize; + let mut without_value = 0usize; + for (name, call) in &calls.calls { + match (call, by_name.get(name.as_str()).copied().flatten()) { + (Some(call), Some(value)) => classes.entry(call.clone()).or_default().push(value), + (None, Some(_)) => without_call += 1, + (Some(_), None) => without_value += 1, + (None, None) => {} + } + } + let panel: std::collections::HashSet<&str> = + calls.calls.iter().map(|(name, _)| name.as_str()).collect(); + let outside_panel = values + .iter() + .filter(|value| !panel.contains(value.name.as_str())) + .count(); + + let mut data = serde_json::Map::new(); + for (class, mut numbers) in classes { + let n = numbers.len(); + numbers.sort_by(|left, right| left.partial_cmp(right).unwrap_or(std::cmp::Ordering::Equal)); + let mean = numbers.iter().sum::<f64>() / n as f64; + let sd = if n > 1 { + let variance = numbers + .iter() + .map(|value| (value - mean).powi(2)) + .sum::<f64>() + / (n - 1) as f64; + variance.sqrt() + } else { + 0.0 + }; + data.insert( + class, + serde_json::json!({ + "n": n, + "mean": crate::routes::probesets::round(Some(mean), 4.0), + "sd": crate::routes::probesets::round(Some(sd), 4.0), + "min": crate::routes::probesets::round(numbers.first().copied(), 4.0), + "max": crate::routes::probesets::round(numbers.last().copied(), 4.0), + }), + ); + } + let marker_label = format!( + "{marker}{} in {group} {version}", + match (calls.chr.as_deref(), calls.mb) { + (Some(chr), Some(mb)) => format!(" (chr{chr}, {mb:.2} Mb)"), + (Some(chr), None) => format!(" (chr{chr})"), + _ => String::new(), + } + ); + let mut envelope = ctx + .envelope(serde_json::Value::Object(data)) + .with_note(&format!( + "{marker_label}: trait {trait_id}'s values summarised per genotype class. Counting \ + only animals that have both a call and a value; {without_call} have a value but no \ + call (missing at this marker) and {without_value} have a call but no value." + )) + .with_note( + "Individual genotypes are not served: the calls are joined to the values here and \ + reduced to these statistics. sd is the sample standard deviation.", + ); + if calls.calls.len() == 0 { + envelope = envelope.with_note("This marker has no individuals in the file."); + } else if let Some((class, smallest)) = envelope + .data + .as_object() + .and_then(|classes| { + classes + .iter() + .filter_map(|(class, stats)| Some((class.clone(), stats.get("n")?.as_u64()?))) + .min_by_key(|(_, n)| *n) + }) + { + if smallest < 10 { + let warn = envelope.with_note(&format!( + "The smallest class is '{class}' with {smallest} animal(s): a peak resting on that \ + many is sensitive to one extreme value." + )); + envelope = warn; + } + } + if outside_panel > 0 { + envelope = envelope.with_note(&format!( + "{outside_panel} animal(s) with a value for this trait are not in this genotype file \ + and were left out." + )); + } + envelope = envelope.with_next( + &format!( + "/groups/{}/genotypes/{}/markers/{}/frequencies", + crate::response::path_segment(&group), + crate::response::path_segment(&version), + crate::response::path_segment(&marker) + ), + "This marker's calls across the panel, as frequencies", + ); + let links = suggest::genotype_version_links(&group, &version); + let current = format!( + "/groups/{}/genotypes/{}/markers/{}/classes", + crate::response::path_segment(&group), + crate::response::path_segment(&version), + crate::response::path_segment(&marker) + ); + Ok(Json(envelope.with_links_except(links, ¤t))) +} diff --git a/src/routes/groups.rs b/src/routes/groups.rs index 9d7a4bc..304eb33 100644 --- a/src/routes/groups.rs +++ b/src/routes/groups.rs @@ -239,7 +239,7 @@ pub async fn group_strains( /// published (phenotype) data is reachable there via /// /traits/{dataset}/... with a gn-auth check, so it needs one here /// too (this was a known gap -- see docs/gn-auth.md). -enum GroupTraitLookup<T> { +pub(crate) enum GroupTraitLookup<T> { GroupNotFound, TraitNotFound, Forbidden, @@ -248,7 +248,7 @@ enum GroupTraitLookup<T> { /// Either a database error, or a failure to reach/parse gn-auth's /// answer while checking authorization for a non-public group. -enum GroupAuthError { +pub(crate) enum GroupAuthError { Db(db::DbError), Auth(String), } @@ -287,7 +287,7 @@ fn check_group_trait_authorized( .map_err(GroupAuthError::Auth) } -fn get_group_trait_values_result( +pub(crate) fn get_group_trait_values_result( group: &str, trait_id: u32, auth_server_url: &str, diff --git a/src/routes/probesets.rs b/src/routes/probesets.rs index ce573b8..e6e4154 100644 --- a/src/routes/probesets.rs +++ b/src/routes/probesets.rs @@ -296,7 +296,7 @@ struct Page { /// Rounded for reading: the database's floats carry more digits than a reply /// needs, and 6.63333333333333 is noise where 6.633 is the number. -fn round(value: Option<f64>, places: f64) -> Option<f64> { +pub(crate) fn round(value: Option<f64>, places: f64) -> Option<f64> { let factor = 10f64.powf(places); value.map(|value| (value * factor).round() / factor) } |
