diff options
| author | Pjotr <wrk@bosa.lan> | 2026-11-13 14:02:52 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-11-13 14:02:52 +0000 |
| commit | a5d6437a90686e97b5c410af3a3479114e4ab9c5 (patch) | |
| tree | a49835e5e5dc668b470d6b631ed3528d5d62e115 /src | |
| parent | e552bb6407718c986123e574a59494ca6184f2e2 (diff) | |
| download | genenetwork4-a5d6437a90686e97b5c410af3a3479114e4ab9c5.tar.gz | |
bnw: module scores as trait values, and BNW's worked examples
Two additions that make the endpoint usable rather than merely correct.
POST /compute/bnw/features -- from a network to a mappable trait. Every node
with at least one parent at the threshold is a module (the node plus its
parents), scored per sample by the first principal component of the module's
standardised members, sign-corrected so the score rises with the node. Without
?module= the reply is one row per module -- module, members, size,
variance_explained -- where variance_explained says whether the score is a fair
summary at all. With ?module=NAME it is that module's per-sample scores in the
{name, value} shape every mapping endpoint already takes, so the chain runs
network -> module -> /compute/rqtl or /compute/gemma with no translation layer.
That is what BNW is for in GeneNetwork; the diagram is a by-product. The notes
name the construction (a citable module score must say what it is) and repeat
the caveat: a module is a correlation structure, not a QTL.
GET /compute/bnw/examples and /compute/bnw/examples/{name} -- BNW's own worked
examples, for an agent to explore instead of inventing data. The five datasets
its tutorial and examples pages present are listed with their sizes, and each is
served as a matrix in the values shape /compute/bnw takes, with a ready-to-post
action carrying the body. ?columns= restricts the matrix (the spleen example
has 14 variables and a caller may want fewer). genotype_column warns that a
column is a genotype code: this driver is continuous-only, so it enters the
network as a number, the way the web application's GeneNetwork path treats it.
Files come from BNW_EXAMPLES_DIR (a gn-bnw checkout's sourcecodes/
example_datasets); a deployment without it answers 404 no_examples.
Measured on the dev instance: features over five BXD traits gives two modules
(BXD::10001 with BXD::10003 and BXD::10041, 60.4% of variance; BXD::10044 with
BXD::10001, 27.2%), and BXD::10001's 19 scores posted straight to /compute/rqtl
and /compute/gemma both return 200 -- gemma peaks on chromosome 6. tests/bnw.rs
covers the module list, one module's scores in mapping shape, the unknown-module
422, the example list, one example's matrix and its ready-to-post action, and a
404 for a name that does not exist.
Diffstat (limited to 'src')
| -rw-r--r-- | src/bnw.rs | 414 | ||||
| -rw-r--r-- | src/config.rs | 7 | ||||
| -rw-r--r-- | src/lib.rs | 3 | ||||
| -rw-r--r-- | src/routes/bnw.rs | 434 |
4 files changed, 857 insertions, 1 deletions
diff --git a/src/bnw.rs b/src/bnw.rs index cc73efd..551e21f 100644 --- a/src/bnw.rs +++ b/src/bnw.rs @@ -359,6 +359,350 @@ pub fn matrix_path(cache_dir: &str, unique: &str) -> PathBuf { Path::new(cache_dir).join(format!("{unique}-matrix.tsv")) } + +/// One module of a learned network: a node and its parents, scored per sample. +#[derive(Debug, Clone)] +pub struct Module { + /// The node whose parents define the module (the network's "child"). + pub name: String, + /// The node and its parents, in that order. + pub members: Vec<String>, + /// The module score per sample. + pub scores: Vec<(String, f64)>, + /// Share of the module's variance the score explains (the first principal + /// component's eigenvalue over the number of members) -- how much of a + /// summary the score really is. + pub variance_explained: f64, +} + +/// Score each node's module -- the node plus its parents -- per sample. +/// +/// The score is the **first principal component** of the module's standardised +/// members, sign-corrected so that it correlates positively with the node +/// itself (a principal component's sign is arbitrary; a score that means "more +/// of the child" must not come out negated). That is the definition the reply's +/// notes state, because a module score is only citable if its construction is +/// named. +/// +/// Only nodes with at least one parent form a module: a node the search left +/// unconnected is not a summary of anything, and inventing a score for it would +/// be exactly the kind of number that gets mapped and then over-interpreted. +pub fn module_scores(matrix: &Matrix, edges: &[Value], threshold: f64) -> Vec<Module> { + // node -> its parents, in the network at or above the threshold + let mut parents: Vec<(String, Vec<String>)> = Vec::new(); + for edge in edges { + let Some(from) = edge.get(0).and_then(Value::as_str) else { continue }; + let Some(to) = edge.get(1).and_then(Value::as_str) else { continue }; + let posterior = edge.get(2).and_then(Value::as_f64).unwrap_or(0.0); + if posterior < threshold { + continue; + } + match parents.iter_mut().find(|(node, _)| node == to) { + Some((_, list)) => { + if !list.iter().any(|name| name == from) { + list.push(from.to_string()); + } + } + None => parents.push((to.to_string(), vec![from.to_string()])), + } + } + parents.sort_by(|a, b| a.0.cmp(&b.0)); + + let mut modules = Vec::new(); + for (node, node_parents) in parents { + let members: Vec<String> = std::iter::once(node.clone()).chain(node_parents).collect(); + let columns: Vec<Vec<f64>> = members + .iter() + .map(|member| { + let index = matrix + .variables + .iter() + .position(|name| name == member) + .unwrap_or(usize::MAX); + matrix + .rows + .iter() + .map(|(_, values)| values.get(index).copied().unwrap_or(f64::NAN)) + .collect() + }) + .collect(); + let standardised: Option<Vec<Vec<f64>>> = columns.iter().map(|column| standardise(column)).collect(); + let Some(standardised) = standardised else { continue }; + let d = standardised.len(); + let n = matrix.rows.len(); + if d < 2 || n < 3 { + continue; + } + // Correlation matrix of the members. + let mut correlation = vec![vec![0.0; d]; d]; + for i in 0..d { + for j in 0..d { + let dot: f64 = (0..n).map(|s| standardised[i][s] * standardised[j][s]).sum(); + correlation[i][j] = dot / (n as f64 - 1.0); + } + } + let (loadings, eigenvalue) = first_component(&correlation); + // Sign: the score must rise with the child. + let mut score: Vec<f64> = (0..n) + .map(|s| (0..d).map(|k| loadings[k] * standardised[k][s]).sum()) + .collect(); + let child = &standardised[0]; + let covariance: f64 = (0..n).map(|s| score[s] * child[s]).sum(); + if covariance < 0.0 { + for value in &mut score { + *value = -*value; + } + } + modules.push(Module { + name: node, + members, + scores: matrix + .rows + .iter() + .enumerate() + .map(|(index, (sample, _))| (sample.clone(), score[index])) + .collect(), + variance_explained: if d > 0 { eigenvalue / d as f64 } else { 0.0 }, + }); + } + modules +} + +/// Standardise a column: mean 0, standard deviation 1. `None` when it does not +/// vary (a constant variable has no component to contribute, and dividing by +/// its zero deviation would produce NaNs that travel into the score). +fn standardise(column: &[f64]) -> Option<Vec<f64>> { + let n = column.len() as f64; + if column.is_empty() { + return None; + } + let mean: f64 = column.iter().sum::<f64>() / n; + let variance: f64 = column.iter().map(|value| (value - mean).powi(2)).sum::<f64>() / (n - 1.0).max(1.0); + if !variance.is_finite() || variance <= f64::EPSILON { + return None; + } + let deviation = variance.sqrt(); + Some(column.iter().map(|value| (value - mean) / deviation).collect()) +} + +/// The dominant eigenvector of a symmetric matrix, by power iteration. +/// +/// Deterministic -- it starts from the vector of ones -- which matters because +/// a score that changes run to run is not a trait anyone can map. Returns the +/// eigenvector (normalised) and its eigenvalue. +fn first_component(matrix: &[Vec<f64>]) -> (Vec<f64>, f64) { + let d = matrix.len(); + let mut vector = vec![1.0 / (d as f64).sqrt(); d]; + for _ in 0..200 { + let mut next: Vec<f64> = (0..d) + .map(|i| (0..d).map(|j| matrix[i][j] * vector[j]).sum()) + .collect(); + let norm: f64 = next.iter().map(|value| value * value).sum::<f64>().sqrt(); + if norm <= f64::EPSILON { + break; + } + for value in &mut next { + *value /= norm; + } + let change: f64 = next + .iter() + .zip(vector.iter()) + .map(|(a, b)| (a - b).abs()) + .fold(0.0, f64::max); + vector = next; + if change < 1e-12 { + break; + } + } + let eigenvalue: f64 = (0..d) + .map(|i| (0..d).map(|j| vector[i] * matrix[i][j] * vector[j]).sum::<f64>()) + .sum(); + // Canonical orientation: the largest-magnitude loading positive, so the + // vector does not flip between runs on a sign-symmetric matrix. + if let Some((index, _)) = vector + .iter() + .enumerate() + .max_by(|a, b| a.1.abs().partial_cmp(&b.1.abs()).unwrap_or(std::cmp::Ordering::Equal)) + { + if vector[index] < 0.0 { + for value in &mut vector { + *value = -*value; + } + } + } + (vector, eigenvalue) +} + +/// One worked example shipped with BNW, as the endpoint offers it. +#[derive(Debug, Clone)] +pub struct Example { + /// File stem, e.g. "example_data_8nodes". + pub name: String, + /// BNW's own description of it, when we know it. + pub title: String, + pub variables: usize, + pub samples: usize, + /// True when a column looks like a genotype code (whole numbers 1..4): + /// this driver is continuous-only, so such a column enters the network as + /// a number, which is what the web application does too on the GN2 path. + pub has_genotype_column: bool, +} + +/// A small, curated table: the datasets in the gn-bnw checkout that BNW's own +/// workflow page presents, with the titles it gives them. Anything else in the +/// directory is listed by file stem, without a title. +const KNOWN_EXAMPLES: [(&str, &str); 5] = [ + ( + "example_data_8nodes", + "Synthetic genetic network: 2 genotypes and 6 traits (BNW tutorial 1 / example 3)", + ), + ( + "sci_5node_input_data", + "Scientific 5-node network: a genotype, 3 genes and a phenotype (BNW tutorial 2)", + ), + ( + "sci_5node_input_data2", + "The same 5-node design with 500 samples instead of 100", + ), + ( + "spleen_chr2_example_data", + "Immune-related genes in the spleens of BXD mice, chromosome 2 (BNW example 1)", + ), + ( + "time_series_example", + "Synthetic time-series network: a genotype and three traits at three time points (BNW example 4)", + ), +]; + +/// The worked examples available in `dir`. +pub fn examples(dir: &Path) -> Result<Vec<Example>, BnwError> { + let entries = std::fs::read_dir(dir).map_err(|error| { + BnwError::Io(format!( + "{}: {error} (set BNW_EXAMPLES_DIR to the gn-bnw checkout's \ + sourcecodes/example_datasets)", + dir.display() + )) + })?; + let mut found = Vec::new(); + for entry in entries.filter_map(Result::ok) { + let path = entry.path(); + if path.extension().and_then(|ext| ext.to_str()) != Some("txt") { + continue; + } + let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else { continue }; + if stem.ends_with('~') { + continue; + } + let Ok(matrix) = read_example(&path, None) else { continue }; + let has_genotype = (0..matrix.variables.len()).any(|column| { + matrix + .rows + .iter() + .all(|(_, values)| (1.0..=4.0).contains(&values[column]) && values[column].fract() == 0.0) + }); + found.push(Example { + name: stem.to_string(), + title: KNOWN_EXAMPLES + .iter() + .find(|(name, _)| *name == stem) + .map(|(_, title)| (*title).to_string()) + .unwrap_or_else(|| format!("{stem} (BNW example data)")), + variables: matrix.variables(), + samples: matrix.samples(), + has_genotype_column: has_genotype, + }); + } + found.sort_by(|a, b| a.name.cmp(&b.name)); + Ok(found) +} + +/// One example's matrix, optionally restricted to named columns. +/// +/// Restricting matters: BNW's spleen example has more variables than the +/// endpoint will search, so a caller has to choose a subset. +pub fn example_matrix(dir: &Path, name: &str, columns: Option<&[String]>) -> Result<Matrix, BnwError> { + if name.is_empty() + || !name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.') + { + return Err(BnwError::BadInput(format!("{name:?} is not an example name"))); + } + let path = dir.join(format!("{name}.txt")); + read_example(&path, columns) +} + +/// Read one BNW example file: a header of variable names, then data rows. +/// +/// These files carry no type line (that is written by the web application's +/// preparation step), so every column is taken as continuous -- and the +/// endpoint says so when a column is a genotype code. +fn read_example(path: &Path, columns: Option<&[String]>) -> Result<Matrix, BnwError> { + let text = std::fs::read_to_string(path) + .map_err(|error| BnwError::Io(format!("{}: {error}", path.display())))?; + let mut lines = text.lines().filter(|line| !line.trim().is_empty()); + let Some(header) = lines.next() else { + return Err(BnwError::BadInput(format!("{} is empty", path.display()))); + }; + let names: Vec<String> = header.split('\t').map(|cell| cell.trim().to_string()).collect(); + let keep: Vec<usize> = match columns { + None => (0..names.len()).collect(), + Some(wanted) => { + let mut keep = Vec::new(); + for name in wanted { + match names.iter().position(|candidate| candidate == name) { + Some(index) => keep.push(index), + None => { + return Err(BnwError::BadInput(format!( + "no column {name:?} in {}; it has: {}", + path.file_stem().and_then(|stem| stem.to_str()).unwrap_or("the example"), + names.join(", ") + ))) + } + } + } + keep + } + }; + let mut rows: Vec<(String, Vec<f64>)> = Vec::new(); + for (index, line) in lines.enumerate() { + let cells: Vec<&str> = line.split('\t').collect(); + if cells.len() != names.len() { + return Err(BnwError::BadInput(format!( + "{} line {}: {} field(s), expected {}", + path.display(), + index + 2, + cells.len(), + names.len() + ))); + } + let mut row = Vec::with_capacity(keep.len()); + for &column in &keep { + match cells[column].trim().parse::<f64>() { + Ok(value) if value.is_finite() => row.push(value), + _ => return Err(BnwError::BadInput(format!( + "{} line {}: {:?} is not a number (BNW's example {} may be discrete data, \ + which this driver does not model)", + path.display(), + index + 2, + cells[column], + path.file_stem().and_then(|stem| stem.to_str()).unwrap_or("set") + ))), + } + } + rows.push((format!("sample{}", index + 1), row)); + } + let variables: Vec<String> = keep.iter().map(|&index| names[index].clone()).collect(); + if rows.len() < 3 { + return Err(BnwError::BadInput(format!( + "{} has {} data row(s); a network needs at least 3", + path.display(), + rows.len() + ))); + } + Ok(Matrix { variables, rows }) +} + #[cfg(test)] mod tests { use super::*; @@ -444,6 +788,76 @@ mod tests { )); } + + fn matrix_of(variables: &[&str], rows: &[&[f64]]) -> Matrix { + Matrix { + variables: variables.iter().map(|name| (*name).to_string()).collect(), + rows: rows + .iter() + .enumerate() + .map(|(index, row)| (format!("s{index}"), row.to_vec())) + .collect(), + } + } + + #[test] + fn a_module_is_the_child_and_its_parents_at_or_above_the_threshold() { + let matrix = matrix_of( + &["a", "b", "c"], + &[&[1.0, 2.0, 9.0], &[2.0, 4.1, 9.0], &[3.0, 5.9, 9.0], &[4.0, 8.2, 9.0]], + ); + let edges = vec![ + serde_json::json!(["a", "b", 1.0, true]), + serde_json::json!(["c", "b", 0.2, false]), // below 0.5: not a parent + ]; + let modules = module_scores(&matrix, &edges, 0.5); + assert_eq!(modules.len(), 1, "only b has a parent above the threshold"); + assert_eq!(modules[0].name, "b"); + assert_eq!(modules[0].members, vec!["b", "a"]); + assert_eq!(modules[0].scores.len(), 4); + } + + #[test] + fn a_score_rises_with_its_child_and_is_signed_that_way() { + // b tracks a closely; the principal component could point either way, + // so the sign correction is what makes "more of b" mean "higher score". + let matrix = matrix_of( + &["a", "b", "c"], + &[&[1.0, 1.1, 5.0], &[2.0, 1.9, 4.0], &[3.0, 3.2, 3.0], &[4.0, 3.8, 2.0]], + ); + let edges = vec![serde_json::json!(["a", "b", 1.0, true])]; + let modules = module_scores(&matrix, &edges, 0.5); + let scores: Vec<f64> = modules[0].scores.iter().map(|(_, value)| *value).collect(); + assert!(scores[0] < scores[3], "the score must rise with b: {scores:?}"); + assert!( + (0.5..=1.0).contains(&modules[0].variance_explained), + "two correlated variables should be summarised well: {}", + modules[0].variance_explained + ); + } + + #[test] + fn an_unconnected_node_gets_no_module() { + let matrix = matrix_of( + &["a", "b"], + &[&[1.0, 2.0], &[2.0, 3.0], &[3.0, 4.0]], + ); + assert!(module_scores(&matrix, &[], 0.5).is_empty()); + } + + #[test] + fn a_constant_member_is_dropped_rather_than_dividing_by_zero() { + let matrix = matrix_of( + &["a", "b"], + &[&[1.0, 2.0], &[1.0, 3.0], &[1.0, 4.0]], + ); + let edges = vec![serde_json::json!(["a", "b", 1.0, true])]; + assert!( + module_scores(&matrix, &edges, 0.5).is_empty(), + "a constant column has no component to contribute" + ); + } + #[test] fn the_drivers_own_words_become_the_complaint() { assert_eq!( diff --git a/src/config.rs b/src/config.rs index a4654fa..58cc219 100644 --- a/src/config.rs +++ b/src/config.rs @@ -160,6 +160,10 @@ pub struct Config { pub bnw_cache_dir: String, /// The script `/plot/bnw` runs to draw a network (`BNW_PLOTTER`). pub bnw_plotter: String, + /// Directory holding BNW's worked example datasets (`BNW_EXAMPLES_DIR`), + /// served by `/compute/bnw/examples`. Empty means the endpoint reports + /// that no examples are configured. + pub bnw_examples_dir: String, /// The `julia` binary for BulkLMM (`BULKLMM_CMD`), the project its /// packages are instantiated into (`BULKLMM_ENV`), the depot they live in /// (`BULKLMM_DEPOT`), the driver script (`BULKLMM_SCRIPT`), the threads it @@ -345,6 +349,7 @@ impl Config { // in. `guix.scm` supplies the binary; the depot is built once. values.insert("BNW_CMD".to_string(), "bnw".to_string()); values.insert("BNW_BIN_DIR".to_string(), String::new()); + values.insert("BNW_EXAMPLES_DIR".to_string(), String::new()); values.insert( "BNW_PLOTTER".to_string(), "scripts/plot-bnw.py".to_string(), @@ -457,6 +462,7 @@ impl Config { "BNW_BIN_DIR", "BNW_CACHE_DIR", "BNW_PLOTTER", + "BNW_EXAMPLES_DIR", "BULKLMM_CMD", "BULKLMM_ENV", "BULKLMM_DEPOT", @@ -515,6 +521,7 @@ impl Config { bnw_bin_dir: values["BNW_BIN_DIR"].clone(), bnw_cache_dir: values["BNW_CACHE_DIR"].clone(), bnw_plotter: values["BNW_PLOTTER"].clone(), + bnw_examples_dir: values["BNW_EXAMPLES_DIR"].clone(), bulklmm_cmd: values["BULKLMM_CMD"].clone(), bulklmm_env: values["BULKLMM_ENV"].clone(), bulklmm_depot: values["BULKLMM_DEPOT"].clone(), diff --git a/src/lib.rs b/src/lib.rs index 7b9182c..a47f3ca 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -165,6 +165,9 @@ pub fn app() -> Router { .routes(routes!(routes::genotypes::unlisted_genotype_markers)) .routes(routes!(routes::genotypes::unlisted_marker_location)) .routes(routes!(routes::bnw::compute_bnw)) + .routes(routes!(routes::bnw::compute_bnw_features)) + .routes(routes!(routes::bnw::bnw_examples)) + .routes(routes!(routes::bnw::bnw_example)) .routes(routes!(routes::bulklmm::compute_bulklmm)) .routes(routes!(routes::gemma::compute_gemma)) .routes(routes!(routes::gemma::compute_gemma_ravanan)) diff --git a/src/routes/bnw.rs b/src/routes/bnw.rs index eb8e17b..02cb591 100644 --- a/src/routes/bnw.rs +++ b/src/routes/bnw.rs @@ -19,10 +19,11 @@ //! because it is the easiest thing for a reader to over-interpret. use axum::Json; +use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::Deserialize; -use gnauth_macros::compute_gate; +use gnauth_macros::{compute_gate, gnauth}; use crate::auth::AuthToken; use crate::bnw::{self, BnwError, Matrix, Parameters}; @@ -347,3 +348,434 @@ fn bnw_error_to_api_error(error: BnwError, rid: RequestInfo) -> ApiError { } } } + +/// What `/compute/bnw/features` takes: the same inputs as `/compute/bnw`, +/// because a module score comes from the network those inputs learn. +#[derive(Deserialize, utoipa::ToSchema)] +pub struct BnwFeaturesRequest { + /// Group whose published traits form the variables; give with `traits`. + pub group: Option<String>, + #[serde(default)] + pub traits: Vec<u32>, + /// An explicit matrix instead of `group` + `traits`. + pub values: Option<Vec<BnwVariable>>, + pub maxparents: Option<u32>, + pub k: Option<u32>, + pub tiers: Option<u32>, + pub threshold: Option<f64>, + pub trait_name: Option<String>, +} + +#[derive(Deserialize, utoipa::IntoParams)] +pub struct BnwFeaturesParams { + /// Return this one module's scores as `{name, value}` per sample -- the + /// shape every mapping endpoint takes -- instead of the module list. + pub module: Option<String>, +} + +#[utoipa::path(post, path = "/compute/bnw/features", + summary = "Score each module of a learned network, as trait values", + description = "Learns the network (or reuses the same computation as \ +POST /compute/bnw), then scores every node that has parents: the node plus its \ +parents form a module, and its score is the first principal component of the \ +module's standardised members, sign-corrected to rise with the node. Without \ +`?module=` the reply is one row per module -- name, members, size, and the \ +share of the module's variance the score explains. With `?module=NAME` the \ +reply is that module's per-sample scores in the `{name, value}` shape every \ +mapping endpoint (`/compute/rqtl`, `/compute/gemma`, `/compute/qtl2`) already \ +takes, so a module can be mapped without any translation.", + params(BnwFeaturesParams), + request_body = BnwFeaturesRequest, + responses( + (status = 200, description = "One row per module, or one value per sample with ?module=", body = Envelope<serde_json::Value>), + crate::error::Unauthorized, + (status = 409, description = "A BNW run is already in progress for this caller", body = ApiError), + (status = 422, description = "Unusable inputs, or no module with that name", body = ApiError), + (status = 502, description = "The BNW driver failed", body = ApiError) + ) +)] +#[compute_gate(bnw, label = "BNW features")] +pub async fn compute_bnw_features( + ctx: Ctx, + token: AuthToken, + Query(params): Query<BnwFeaturesParams>, + Json(request): Json<BnwFeaturesRequest>, +) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { + let rid = ctx.request_info(); + let config = Config::load(); + let parameters = Parameters { + maxparents: request.maxparents.unwrap_or(bnw::DEFAULT_MAXPARENTS), + k: request.k.unwrap_or(bnw::DEFAULT_K), + tiers: request.tiers.unwrap_or(bnw::DEFAULT_TIERS), + threshold: request.threshold.unwrap_or(bnw::DEFAULT_THRESHOLD), + }; + let (variables, label) = resolve_variables(&request.group, &request.traits, &request.values, request.trait_name.as_deref(), rid.clone()).await?; + let matrix = Matrix::from_values(variables).map_err(|error| bnw_error_to_api_error(error, rid.clone()))?; + let learned = bnw::learn( + &config.bnw_cmd, + Some(&config.bnw_bin_dir), + &config.bnw_cache_dir, + &matrix, + parameters, + ) + .await + .map_err(|error| bnw_error_to_api_error(error, rid.clone()))?; + let modules = bnw::module_scores(&matrix, &learned.rows, parameters.threshold); + if modules.is_empty() { + return Err(unprocessable( + "no_modules", + "No modules to score", + format!( + "the network has no node with a parent at or above threshold {}; nothing to \ + summarise. Lower the threshold, or widen the variables.", + parameters.threshold + ), + rid, + )); + } + + if let Some(wanted) = params.module.as_deref() { + let Some(module) = modules.iter().find(|module| module.name == wanted) else { + let names: Vec<&str> = modules.iter().map(|module| module.name.as_str()).collect(); + return Err(unprocessable( + "unknown_module", + "No such module", + format!("no module {wanted:?} in this network; it has: {}", names.join(", ")), + rid, + )); + }; + let values: Vec<serde_json::Value> = module + .scores + .iter() + .map(|(name, value)| serde_json::json!({"name": name, "value": value})) + .collect(); + return Ok(Json( + ctx.envelope(serde_json::Value::Array(values)) + .with_note(&format!( + "Module {label}::{}: the node and its parents ({}), scored by the first \ + principal component of their standardised values, sign-corrected to rise with \ + the node. These are trait values in the shape /compute/rqtl, /compute/gemma \ + and /compute/qtl2 take: post them as `samples` to map the module.", + module.name, + module.members.join(" + ") + )) + .with_note(&format!( + "The score explains {:.1}% of the module's variance over {} samples; a low \ + share means the module is not one thing and the score is a poor summary.", + module.variance_explained * 100.0, + module.scores.len() + )), + )); + } + + let rows: Vec<serde_json::Value> = modules + .iter() + .map(|module| { + serde_json::json!([ + module.name, + module.members.join(","), + module.members.len(), + (module.variance_explained * 10000.0).round() / 10000.0 + ]) + }) + .collect(); + let mut envelope = ctx + .envelope(serde_json::Value::Array(rows)) + .with_columns( + vec![ + "module".to_string(), + "members".to_string(), + "size".to_string(), + "variance_explained".to_string(), + ], + modules.len(), + ) + .with_note(&format!( + "Modules of the network {label}: every node with at least one parent at or above \ + threshold {}, scored as the first principal component of the node and its parents' \ + standardised values, sign-corrected to rise with the node. `variance_explained` is \ + the share of the module's variance that component explains.", + parameters.threshold + )) + .with_note( + "Post `?module=<name>` to get one module's per-sample scores in the `{name, value}` \ + shape the mapping endpoints take, then map them like any trait. A module is a \ + correlation structure, not a QTL: a mapped module says where its members' shared \ + variation comes from, not which member causes which.", + ); + for module in &modules { + envelope = envelope.with_action(crate::response::SuggestedCall { + method: "POST".to_string(), + href: format!("/compute/bnw/features?module={}", module.name), + description: format!( + "The per-sample scores of module {} ({} members), ready to post as `samples` to a \ + mapping endpoint", + module.name, + module.members.len() + ), + body: None, + }); + } + Ok(Json(envelope)) +} + +/// The variables a BNW request names, from the database or the request body. +async fn resolve_variables( + group: &Option<String>, + traits: &[u32], + values: &Option<Vec<BnwVariable>>, + trait_name: Option<&str>, + rid: RequestInfo, +) -> Result<(Vec<(String, Vec<(String, Option<f64>)>)>, String), ApiError> { + match (group, values) { + (Some(group), None) => { + if traits.len() < 2 { + return Err(unprocessable( + "too_few_variables", + "Too few variables", + format!( + "{} trait(s) given; a network needs at least 2 (and at most {}).", + traits.len(), + bnw::MAX_VARIABLES + ), + rid, + )); + } + let group_name = group.clone(); + let wanted = traits.to_vec(); + let fetched = tokio::task::spawn_blocking(move || { + let row = db::get_group_by_name(&group_name) + .map_err(|error| error.to_string())? + .ok_or_else(|| format!("no group named '{group_name}'"))?; + let mut variables = Vec::with_capacity(wanted.len()); + for trait_id in wanted { + let values = db::get_group_trait_values(row.id, trait_id) + .map_err(|error| error.to_string())?; + if values.is_empty() { + return Err(format!("group '{group_name}' has no values for trait {trait_id}")); + } + variables.push(( + format!("{group_name}::{trait_id}"), + values.into_iter().map(|value| (value.name, value.value)).collect::<Vec<_>>(), + )); + } + Ok::<_, String>(variables) + }) + .await + .map_err(|error| internal(error.to_string(), rid.clone()))? + .map_err(|detail| unprocessable("invalid_variables", "Unusable variables", detail, rid.clone()))?; + let label = trait_name + .map(str::to_string) + .unwrap_or_else(|| format!("{group}::network")); + Ok((fetched, label)) + } + (None, Some(values)) => { + let variables = values + .iter() + .map(|variable| { + ( + variable.name.clone(), + variable.samples.iter().map(|sample| (sample.name.clone(), sample.value)).collect::<Vec<_>>(), + ) + }) + .collect(); + Ok((variables, trait_name.unwrap_or("network").to_string())) + } + _ => Err(unprocessable( + "ambiguous_input", + "Ambiguous network input", + "give `group` + `traits`, or `values` -- one of the two.".to_string(), + rid, + )), + } +} + +#[derive(Deserialize, utoipa::IntoParams)] +pub struct ExampleParams { + /// Restrict the matrix to these columns, comma separated. BNW's spleen + /// example has more variables than the endpoint will search, so a caller + /// chooses a subset. + pub columns: Option<String>, +} + +#[utoipa::path(get, path = "/compute/bnw/examples", + summary = "The worked examples BNW ships, ready to post to /compute/bnw", + description = "BNW's own example datasets -- the ones its tutorial and examples \ +pages present -- listed with the variables and samples each has, and an action \ +carrying a ready-to-post body for POST /compute/bnw. GET \ +/compute/bnw/examples/{name} returns one example's matrix in the `values` shape \ +/compute/bnw takes, so an agent can explore a real network without inventing \ +data. The files are read from BNW_EXAMPLES_DIR (the gn-bnw checkout's \ +sourcecodes/example_datasets).", + responses( + (status = 200, description = "One row per example", body = Envelope<serde_json::Value>), + crate::error::Unauthorized, + (status = 404, description = "No examples are configured on this deployment", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn bnw_examples( + ctx: Ctx, + _token: AuthToken, +) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { + let rid = ctx.request_info(); + let config = Config::load(); + if config.bnw_examples_dir.trim().is_empty() { + return Err(ApiError::new( + StatusCode::NOT_FOUND, + "no_examples", + "No examples configured", + "this deployment has no BNW_EXAMPLES_DIR; point it at a gn-bnw checkout's \ + sourcecodes/example_datasets to offer BNW's worked examples." + .to_string(), + "bnw_examples", + ) + .with_request_id(rid)); + } + let dir = std::path::PathBuf::from(&config.bnw_examples_dir); + let examples = tokio::task::spawn_blocking(move || bnw::examples(&dir)) + .await + .map_err(|error| internal(error.to_string(), rid.clone()))? + .map_err(|error| bnw_error_to_api_error(error, rid.clone()))?; + if examples.is_empty() { + return Err(ApiError::new( + StatusCode::NOT_FOUND, + "no_examples", + "No examples found", + format!("no *.txt example data in {}", config.bnw_examples_dir), + "bnw_examples", + ) + .with_request_id(rid)); + } + let rows: Vec<serde_json::Value> = examples + .iter() + .map(|example| { + serde_json::json!([ + example.name, + example.title, + example.variables, + example.samples, + example.has_genotype_column + ]) + }) + .collect(); + let mut envelope = ctx + .envelope(serde_json::Value::Array(rows)) + .with_columns( + vec![ + "name".to_string(), + "title".to_string(), + "variables".to_string(), + "samples".to_string(), + "genotype_column".to_string(), + ], + examples.len(), + ) + .with_note( + "These are BNW's own example datasets. GET /compute/bnw/examples/{name} returns one \ + as a matrix in the `values` shape POST /compute/bnw takes -- post that body straight \ + back to learn the network the web application's tutorial shows.", + ) + .with_note( + "`genotype_column` warns that a column is a genotype code (whole numbers). This \ + driver is continuous-only, so such a column enters the network as a number, exactly \ + as the web application's GeneNetwork path treats it -- not as a discrete variable \ + with its own multinomial model. Anything the examples page marks as discrete \ + (the car-diagnosis example) is not offered here.", + ); + for example in &examples { + envelope = envelope.with_next( + &format!("/compute/bnw/examples/{}", example.name), + example.title.as_str(), + ); + } + Ok(Json(envelope.with_links(crate::suggest::root_links()))) +} + +#[utoipa::path(get, path = "/compute/bnw/examples/{name}", + summary = "One of BNW's worked examples, as a matrix /compute/bnw takes", + description = "The example's data in the `values` shape POST /compute/bnw expects: \ +one entry per variable, each with its per-sample values. `?columns=a,b,c` restricts \ +the matrix -- the spleen example has more variables than the endpoint searches.", + params(ExampleParams, + ("name" = String, Path, description = "An example name from GET /compute/bnw/examples")), + responses( + (status = 200, description = "The matrix, as `values`", body = Envelope<serde_json::Value>), + crate::error::Unauthorized, + (status = 404, description = "No such example", body = ApiError), + (status = 422, description = "A named column does not exist, or the file is not numeric", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn bnw_example( + ctx: Ctx, + _token: AuthToken, + Path(name): Path<String>, + Query(params): Query<ExampleParams>, +) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { + let rid = ctx.request_info(); + let config = Config::load(); + if config.bnw_examples_dir.trim().is_empty() { + return Err(ApiError::new( + StatusCode::NOT_FOUND, + "no_examples", + "No examples configured", + "this deployment has no BNW_EXAMPLES_DIR.".to_string(), + "bnw_example", + ) + .with_request_id(rid)); + } + let columns: Option<Vec<String>> = params.columns.as_deref().map(|list| { + list.split(',') + .map(|column| column.trim().to_string()) + .filter(|column| !column.is_empty()) + .collect() + }); + let dir = std::path::PathBuf::from(&config.bnw_examples_dir); + let wanted = name.clone(); + let matrix = tokio::task::spawn_blocking(move || { + bnw::example_matrix(&dir, &wanted, columns.as_deref()) + }) + .await + .map_err(|error| internal(error.to_string(), rid.clone()))? + .map_err(|error| match error { + BnwError::Io(detail) if detail.contains("No such file") => ApiError::new( + StatusCode::NOT_FOUND, + "no_such_example", + "No such example", + format!("no example named {name:?}; see GET /compute/bnw/examples"), + "bnw_example", + ) + .with_request_id(rid.clone()), + other => bnw_error_to_api_error(other, rid.clone()), + })?; + let values: Vec<serde_json::Value> = matrix + .variables + .iter() + .enumerate() + .map(|(column, variable)| { + let samples: Vec<serde_json::Value> = matrix + .rows + .iter() + .map(|(sample, row)| serde_json::json!({"name": sample, "value": row[column]})) + .collect(); + serde_json::json!({"name": variable, "samples": samples}) + }) + .collect(); + Ok(Json( + ctx.envelope(serde_json::json!({"values": serde_json::Value::Array(values.clone())})) + .with_note(&format!( + "BNW example {name}: {} variables over {} samples.\nPost this body (or its \ + `values`) to /compute/bnw to learn the network the web application's tutorial \ + shows; add `maxparents`, `k` or `threshold` to explore how the structure moves.", + matrix.variables.len(), + matrix.rows.len() + )) + .with_action(crate::response::SuggestedCall { + method: "POST".to_string(), + href: "/compute/bnw".to_string(), + description: format!("Learn the network for example {name}"), + body: Some(serde_json::json!({"values": serde_json::Value::Array(values.clone())})), + }), + )) +} |
