diff options
| author | Pjotr <wrk@bosa.lan> | 2026-11-14 03:33:25 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-11-14 03:33:25 +0000 |
| commit | 5c6f36f6d0155d73e3fb8d24aee1a6827a77ae97 (patch) | |
| tree | 1b9080c563b05d0fb4db550b37263e0f748cea47 /src | |
| parent | a0d7a37d65e98fc874617d5b08983fe66c5f2655 (diff) | |
| download | genenetwork4-5c6f36f6d0155d73e3fb8d24aee1a6827a77ae97.tar.gz | |
groups: an endpoint for a family's parental design
GET /groups/{group}/parents-and-f1s answers the question the mapping notes only
implied. It reports the F1 strains, the maternal and paternal strain (from the
deployment's parents_and_f1s.json, ported from GN2's ParInfo -- all 24 groups),
the @type of the group's genotype file, the individuals each role names where
the metadata names them (BXD-Longevity does, most do not), and -- the part a
caller needs -- which members of the current panel the default rule drops and
which the `F1` name heuristic catches.
Two things that came out of building it and comparison with GN2:
* the JSON's paternal/maternal labels were INVERTED against GN2's reading.
GN2 unpacks ParInfo as `f1, f12, maternal, paternal`, so BXD's maternal
strain is C57BL/6J; our file said paternal. No mapping was affected
(non_strains takes both regardless of role) but the metadata was wrong, and
anything using "maternal" later -- reciprocal F1 direction, the @mat/@pat
note -- would have been backwards. The file is rewritten from ParInfo itself
(ast-parsed, not retyped), 23 groups' roles filled in and the 24th
(BXD-Longevity, which GN2 does not have) left as it was.
* an RI set has two kinds of F1 name: the design's (B6D2F1) and the panel's
own intercross individuals (C57BL/6JxBXD037F1). The endpoint reports
excluded_from_panel and excluded_by_name separately and says which is doing
the work, because "0 declared, 37 by name" is otherwise confusing. Empty F1
names (C57BL-6JxC57BL-6NJF2 has two) are dropped rather than becoming
exclusion entries that match nothing.
genotypes::non_strains is rebuilt on the same typed parser (DesignRole /
ParentalDesign), so the rule and the endpoint cannot disagree. tests: a unit
test for the roles, empty-name handling and the unlisted-group source, and an
integration test asserting BXD's maternal/paternal orientation and the note.
Diffstat (limited to 'src')
| -rw-r--r-- | src/genotypes.rs | 203 | ||||
| -rw-r--r-- | src/lib.rs | 1 | ||||
| -rw-r--r-- | src/routes/groups.rs | 112 |
3 files changed, 295 insertions, 21 deletions
diff --git a/src/genotypes.rs b/src/genotypes.rs index f9864c1..0d6c1c2 100644 --- a/src/genotypes.rs +++ b/src/genotypes.rs @@ -479,29 +479,157 @@ pub fn select_panel( /// GN2 keeps the lists in `parents_and_f1s.json`; the F1 columns in the /// BXD file are additionally named `<strain>x<strain>F1`, which is what /// catches them when the JSON has no entry for the group. -pub fn non_strains(dir: &Path, group: &str, panel: &[String]) -> BTreeSet<String> { - let mut excluded = BTreeSet::new(); +/// One role in a parental design: a strain, and the individuals of it that a +/// group's metadata names (BXD-Longevity lists them; most groups do not). +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +pub struct DesignRole { + pub strain: String, + /// Individuals the metadata attributes to this role, when it says. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub individuals: Vec<String>, +} + +/// A family's parental design: who the parents are, which F1s were made, and +/// what a mapping does with them. +/// +/// This is metadata (`parents_and_f1s.json`, ported from GN2's `ParInfo`), not +/// policy: a caller can *see* it instead of inferring why an individual was +/// dropped, and can name one back with `individuals.include`. +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +pub struct ParentalDesign { + pub group: String, + pub f1s: Vec<DesignRole>, + pub maternal: Option<DesignRole>, + pub paternal: Option<DesignRole>, + /// Where the roles came from: "metadata" when the group is listed, "name + /// heuristic" when only the `F1` substring rule applies (an unlisted group + /// has parents nobody declared, and its mapping may include strains that + /// are not RI lines). + pub source: &'static str, + /// The `@type` of the group's genotype file, e.g. `riset` or `f2`. + pub design: Option<String>, + /// Individuals of the current panel the default rule would drop. + pub excluded_from_panel: Vec<String>, + /// Panel members the `F1` name heuristic catches -- reported separately, + /// because it is a heuristic and an unlisted group's parents are invisible + /// to it. + pub excluded_by_name: Vec<String>, +} + +/// The roles a group's metadata declares, or `None` when the group is unlisted. +fn design_roles(dir: &Path, group: &str) -> Option<(Vec<DesignRole>, Option<DesignRole>, Option<DesignRole>)> { let path = dir.join("parents_and_f1s.json"); - if let Ok(text) = std::fs::read_to_string(&path) { - if let Ok(document) = serde_json::from_str::<serde_json::Value>(&text) { - if let Some(entry) = document.get(group) { - for key in ["paternal", "maternal"] { - if let Some(strain) = entry - .get(key) - .and_then(|v| v.get("strain")) - .and_then(|v| v.as_str()) - { - excluded.insert(strain.to_string()); - } - } - if let Some(f1s) = entry.get("f1s").and_then(|v| v.as_array()) { - for f1 in f1s { - if let Some(strain) = f1.get("strain").and_then(|v| v.as_str()) { - excluded.insert(strain.to_string()); - } - } - } + let text = std::fs::read_to_string(&path).ok()?; + let document: serde_json::Value = serde_json::from_str(&text).ok()?; + let entry = document.get(group)?; + let role = |key: &str| { + entry.get(key).and_then(|value| { + let strain = value.get("strain").and_then(|s| s.as_str())?.trim(); + if strain.is_empty() { + return None; } + Some(DesignRole { + strain: strain.to_string(), + individuals: value + .get("individuals") + .and_then(|list| list.as_array()) + .map(|list| { + list.iter() + .filter_map(|name| name.as_str()) + .map(str::to_string) + .collect() + }) + .unwrap_or_default(), + }) + }) + }; + let f1s: Vec<DesignRole> = entry + .get("f1s") + .and_then(|list| list.as_array()) + .map(|list| { + list.iter() + .filter_map(|value| { + let strain = value.get("strain").and_then(|s| s.as_str())?.trim(); + if strain.is_empty() { + return None; + } + Some(DesignRole { + strain: strain.to_string(), + individuals: value + .get("individuals") + .and_then(|list| list.as_array()) + .map(|list| { + list.iter() + .filter_map(|name| name.as_str()) + .map(str::to_string) + .collect() + }) + .unwrap_or_default(), + }) + }) + .collect() + }) + .unwrap_or_default(); + Some((f1s, role("maternal"), role("paternal"))) +} + +/// The parental design of one group, as `/groups/{group}/parents-and-f1s` +/// reports it. +/// +/// `panel` is the group's individual list; it is what turns the metadata into +/// "these members would be dropped", which is the fact a caller needs. An +/// unlisted group still gets an answer: `source` says the roles are unknown and +/// only the name heuristic applied. +pub fn parental_design(dir: &Path, group: &str, panel: Option<&[String]>, design: Option<String>) -> ParentalDesign { + let roles = design_roles(dir, group); + let (f1s, maternal, paternal) = roles.clone().unwrap_or_default(); + let empty: &[String] = &[]; + let panel = panel.unwrap_or(empty); + let declared: Vec<&str> = f1s + .iter() + .map(|role| role.strain.as_str()) + .chain(maternal.iter().map(|role| role.strain.as_str())) + .chain(paternal.iter().map(|role| role.strain.as_str())) + .collect(); + let excluded_from_panel: Vec<String> = panel + .iter() + .filter(|name| declared.contains(&name.as_str())) + .cloned() + .collect(); + let excluded_by_name: Vec<String> = panel + .iter() + .filter(|name| name.contains("F1")) + .cloned() + .collect(); + ParentalDesign { + group: group.to_string(), + f1s, + maternal, + paternal, + source: if roles.is_some() { "metadata" } else { "name heuristic" }, + design, + excluded_from_panel, + excluded_by_name, + } +} + +/// The individuals a mapping excludes by default: parents and F1s. +/// +/// The roles come from `parents_and_f1s.json` (GN2's `ParInfo`, roles named +/// rather than positional -- GN2 unpacks it as `f1, f12, maternal, paternal`, +/// and the file once had those two swapped). The `F1` substring rule is a +/// fallback for groups the metadata does not list, and an unlisted group's +/// parents are invisible to it: that is why `parental_design` reports which +/// source answered. +pub fn non_strains(dir: &Path, group: &str, panel: &[String]) -> BTreeSet<String> { + let mut excluded = BTreeSet::new(); + if let Some((f1s, maternal, paternal)) = design_roles(dir, group) { + for role in f1s + .iter() + .chain(maternal.iter()) + .chain(paternal.iter()) + { + excluded.insert(role.strain.clone()); } } for name in panel { @@ -909,6 +1037,39 @@ mod tests { names.iter().map(|name| (*name).to_string()).collect() } + + #[test] + fn the_design_names_the_roles_the_way_gn2_does() { + let dir = scratch("design"); + std::fs::write( + dir.join("parents_and_f1s.json"), + // GN2 unpacks ParInfo as f1, f12, maternal, paternal. + r#"{"BXD": {"f1s": [{"strain": "B6D2F1"}, {"strain": "D2B6F1"}], + "maternal": {"strain": "C57BL/6J"}, + "paternal": {"strain": "DBA/2J"}}, + "EMPTY": {"f1s": [{"strain": ""}, {"strain": ""}], + "maternal": {"strain": "A"}, "paternal": {"strain": "B"}}}"#, + ) + .unwrap(); + let design = parental_design(&dir, "BXD", Some(&["BXD1".to_string(), "B6D2F1".to_string()]), Some("riset".into())); + assert_eq!(design.source, "metadata"); + assert_eq!(design.design.as_deref(), Some("riset")); + assert_eq!(design.f1s.len(), 2); + assert_eq!(design.maternal.as_ref().unwrap().strain, "C57BL/6J"); + assert_eq!(design.paternal.as_ref().unwrap().strain, "DBA/2J"); + assert_eq!(design.excluded_from_panel, vec!["B6D2F1"]); + assert_eq!(design.excluded_by_name, vec!["B6D2F1"]); + + // An empty F1 name is not an exclusion entry. + let design = parental_design(&dir, "EMPTY", None, None); + assert!(design.f1s.is_empty(), "empty names are dropped: {:?}", design.f1s); + + // An unlisted group says so. + let design = parental_design(&dir, "NOT-LISTED", None, None); + assert_eq!(design.source, "name heuristic"); + assert!(design.maternal.is_none() && design.paternal.is_none()); + } + #[test] fn the_parent_f1_rule_still_drops_and_counts() { let p = panel(&["BXD1", "B6D2F1", "C57BL/6J"]); diff --git a/src/lib.rs b/src/lib.rs index a47f3ca..e6aa328 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -158,6 +158,7 @@ pub fn app() -> Router { .routes(routes!(routes::frequencies::unlisted_frequencies)) .routes(routes!(routes::frequencies::unlisted_marker_frequencies)) .routes(routes!(routes::frequencies::marker_classes)) + .routes(routes!(routes::groups::group_parental_design)) .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/groups.rs b/src/routes/groups.rs index 287aa66..e2ac7c7 100644 --- a/src/routes/groups.rs +++ b/src/routes/groups.rs @@ -14,6 +14,7 @@ use crate::config::Config; use crate::db; use crate::normalize; use crate::error::{ApiError, Unauthorized}; +use crate::genotypes; use crate::response::{Ctx, Envelope, path_segment}; use crate::suggest; @@ -167,6 +168,117 @@ pub struct GroupStrainsParams { used_for_mapping: Option<bool>, } +#[utoipa::path(get, path = "/groups/{group}/parents-and-f1s", + summary = "A family's parental design: its parents, its F1s, and what a mapping drops", + description = "The parental design of a family, from the deployment's \ +`parents_and_f1s.json` (ported from GeneNetwork2's `ParInfo`): the F1 strains, \ +the maternal and paternal strain, and -- when the metadata names them -- the \ +individuals belonging to each role. It also says what the default mapping rule \ +would drop from the group's current panel and which panel members the `F1` \ +name heuristic catches, because an unlisted group's parents are invisible to \ +that heuristic. `include_parents_f1` and `individuals` then decide what \ +actually enters a mapping.", + responses( + (status = 200, description = "The design", body = Envelope<genotypes::ParentalDesign>), + crate::error::Unauthorized, + (status = 404, description = "No genotype file for that group", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn group_parental_design( + ctx: Ctx, + Path(group): Path<String>, + _token: AuthToken, +) -> Result<Json<Envelope<genotypes::ParentalDesign>>, ApiError> { + let rid = ctx.request_info(); + let config = Config::load(); + let directory = std::path::PathBuf::from(&config.genotype_files_dir); + let wanted = group.clone(); + let design = tokio::task::spawn_blocking(move || { + let resolved = genotypes::resolve(&directory, &wanted, None)?; + let design = genotypes::file_meta(&resolved.geno) + .ok() + .and_then(|meta| { + meta.labels + .iter() + .find(|(key, _)| key == "type") + .map(|(_, value)| value.clone()) + }); + Ok::<_, genotypes::GenotypeError>(genotypes::parental_design( + &directory, + &wanted, + Some(&resolved.panel), + design, + )) + }) + .await + .map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + error.to_string(), + "group_parental_design", + ) + .with_request_id(rid.clone()) + })? + .map_err(|error| { + 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", + "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(), "group_parental_design") + .with_request_id(rid.clone()) + })?; + + let mut envelope = ctx.envelope(design.clone()).with_note(&format!( + "Roles come from {}. A mapping excludes the parents and F1s by default; \ + `include_parents_f1: true` keeps them, and `individuals: {{\"include\": [...], \ + \"exclude\": [...]}}` selects by name. Including them changes the *kinship* (GEMMA and \ + R/qtl read no phenotypes for it), not the fit.", + if design.source == "metadata" { + "the deployment's parents_and_f1s.json" + } else { + "nothing -- this group is not listed, so only the `F1` name heuristic applies and the \ + parents are unknown" + } + )); + if !design.f1s.is_empty() && design.excluded_from_panel.is_empty() && !design.excluded_by_name.is_empty() { + // The common case for an RI set: the metadata names the *design's* F1s + // (B6D2F1), the panel carries *specific* intercross F1 individuals + // (C57BL/6JxBXD037F1), so the metadata alone would exclude nothing and + // the name heuristic does the work. + envelope = envelope.with_note( + "The F1 strains above describe the design; the panel's own F1 \ + individuals have different names (an intercross F1 is named after its \ + two parents, e.g. C57BL/6JxBXD037F1), so the exclusions come from the \ + `F1` name rule here. `excluded_by_name` lists exactly which members \ + that catches.", + ); + } + if design.source != "metadata" { + envelope = envelope.with_note( + "This group has no parental metadata: any parent strain in its panel will be mapped \ + as if it were a study individual. Add it to parents_and_f1s.json, or exclude it with \ + `individuals.exclude`.", + ); + } + Ok(Json(envelope.with_links(crate::suggest::root_links()))) +} + #[utoipa::path(get, path = "/groups/{group}/strains", summary = "List the strains/samples belonging to a group", params( ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"), ("used_for_mapping" = Option<bool>, Query, description = "Only strains/samples used for mapping") |
