From 304b92e310df9570a67ef3cdd3bbcc714569bc83 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Mon, 16 Nov 2026 18:14:29 +0000 Subject: correlation: PC traits as basket columns, and compare-two-traits **PC traits.** `pca.traits` carries each component *as a trait*: PC1, PC2, ... with a score per individual, so a component can be used the way GN2's "PCA traits" are -- correlated, mapped, plotted, saved. Scores are the standardised values projected onto the loadings, standardised with the sample standard deviation because that is what the correlation matrix was built from; a constant trait has no z-score and refuses rather than filling a zero. They live on the complete cases of the kept traits (31 of 34 in the fixture), which is the honest reading of "a PCA is defined on a rectangle". The module story is a basket: POST /baskets with a PC's values gives a per-user, versioned, digest-recorded column (verified: 201, revision 1, values read back), which the mapping and plotting endpoints already accept. No new store, no new dataset concept. **Compare traits.** POST /compute/compare takes two trait references, keeps the individuals with a value for both, and returns r, p, n *and* the pairs -- the statistic and the data behind it. It agrees with the matrix: the same pair is r = 0.6756270426459695 in both. POST /plot/compare draws the scatter (6 303 bytes) with the individual's name in each tooltip and the OLS line implied by r and the two means; nothing is refitted. Monitor gained compute-compare and plot-compare; full run 49 ok, 0 failed, 1 skipped. Not done, deliberately: limit_to/ids_only/names_only. The listing handlers return typed rows (Envelope>), so "names only" is a shape change in every one of them -- a pass of its own rather than a query parameter. --- src/config.rs | 8 ++ src/lib.rs | 2 + src/pca.rs | 90 ++++++++++++ src/routes/compare.rs | 290 +++++++++++++++++++++++++++++++++++++++ src/routes/correlation.rs | 2 +- src/routes/correlation_matrix.rs | 80 ++++++++++- src/routes/mod.rs | 1 + src/routes/plot.rs | 2 +- 8 files changed, 468 insertions(+), 7 deletions(-) create mode 100644 src/routes/compare.rs (limited to 'src') diff --git a/src/config.rs b/src/config.rs index c6a1553..0061070 100644 --- a/src/config.rs +++ b/src/config.rs @@ -175,6 +175,8 @@ pub struct Config { pub pca_plotter: String, /// Script that draws the clustered heatmap of a correlation matrix (HEATMAP_PLOTTER). pub heatmap_plotter: String, + /// Script that draws the scatter plot of a two-trait comparison (COMPARE_PLOTTER). + pub compare_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. @@ -419,6 +421,10 @@ impl Config { "HEATMAP_PLOTTER".to_string(), "scripts/plot-heatmap.py".to_string(), ); + values.insert( + "COMPARE_PLOTTER".to_string(), + "scripts/plot-compare.py".to_string(), + ); // Per-user baskets: one SQLite file each (src/baskets.rs). Never // MariaDB -- a user's edited column is theirs. values.insert( @@ -487,6 +493,7 @@ impl Config { "GENOTYPE_PLOTTER", "PCA_PLOTTER", "HEATMAP_PLOTTER", + "COMPARE_PLOTTER", "BNW_CMD", "BNW_BIN_DIR", "BNW_CACHE_DIR", @@ -554,6 +561,7 @@ impl Config { bnw_plotter: values["BNW_PLOTTER"].clone(), pca_plotter: values["PCA_PLOTTER"].clone(), heatmap_plotter: values["HEATMAP_PLOTTER"].clone(), + compare_plotter: values["COMPARE_PLOTTER"].clone(), bnw_examples_dir: values["BNW_EXAMPLES_DIR"].clone(), bulklmm_cmd: values["BULKLMM_CMD"].clone(), bulklmm_env: values["BULKLMM_ENV"].clone(), diff --git a/src/lib.rs b/src/lib.rs index 976b2f1..c025c46 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -231,6 +231,8 @@ pub fn app() -> Router { .routes(routes!(routes::traits::trait_values)) .routes(routes!(routes::publications::publication_traits)) .routes(routes!(routes::search::search)) + .routes(routes!(routes::compare::compare)) + .routes(routes!(routes::compare::plot_compare)) .routes(routes!(routes::correlation::correlation)) .routes(routes!(routes::correlation_matrix::correlation_matrix)) .routes(routes!(routes::baskets::list_baskets)) diff --git a/src/pca.rs b/src/pca.rs index 23e3105..e924882 100644 --- a/src/pca.rs +++ b/src/pca.rs @@ -55,6 +55,29 @@ pub struct Pca { /// Eigenvalues should sum to the number of traits; reported so a caller can /// check that the decomposition is sane rather than trust it. pub trace: f64, + /// The components *as traits*: one value per individual per component, so + /// they can be used the way GN2's "PCA traits" are -- correlated, mapped, + /// plotted, saved in a basket. Empty when the caller did not ask, or when + /// the values were not available to project. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub traits: Vec, +} + +/// One principal component as a trait: a value per individual. +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +pub struct PcTrait { + /// `PC1`, `PC2`, ... in eigenvalue order. + pub name: String, + /// Score per individual, in the same order as `individuals`. + pub values: Vec, + /// Share of total variance this component explains. + pub explained_variance_ratio: f64, +} + +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +pub struct PcValue { + pub name: String, + pub value: f64, } #[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] @@ -189,6 +212,7 @@ pub fn analyse(matrix: &Matrix) -> Pca { scree: Vec::new(), dropped, trace: 0.0, + traits: Vec::new(), }; } let small: Vec> = kept @@ -201,6 +225,7 @@ pub fn analyse(matrix: &Matrix) -> Pca { scree: Vec::new(), dropped, trace: 0.0, + traits: Vec::new(), }; }; let trace: f64 = eigenvalues.iter().sum(); @@ -221,7 +246,72 @@ pub fn analyse(matrix: &Matrix) -> Pca { scree: eigenvalues, dropped, trace, + traits: Vec::new(), + } +} + +/// Project standardised trait values onto the components, giving PC scores. +/// +/// `values` is traits x individuals for the traits the PCA kept, in the kept +/// order and already aligned to `individuals`; a trait is standardised with the +/// **sample** standard deviation (n-1), because that is what the correlation +/// matrix was built from -- using the population one would rescale every score +/// by a constant and quietly disagree with `r`. +/// +/// Returns one [`PcTrait`] per component. `None` when the shapes disagree or a +/// value is missing, rather than filling a zero into a score. +pub fn scores( + pca: &Pca, + values: &[Vec], + individuals: &[String], +) -> Option> { + let n_traits = values.len(); + if n_traits == 0 || individuals.len() != values[0].len() || values.iter().any(|v| v.len() != individuals.len()) { + return None; + } + if pca.components.len() < n_traits || pca.components[0].loadings.len() != n_traits { + return None; + } + let n = individuals.len(); + if n < 2 { + return None; + } + // z-scores per trait + let mut standardised: Vec> = Vec::with_capacity(n_traits); + for trait_values in values { + if trait_values.iter().any(|v| !v.is_finite()) { + return None; + } + let mean = trait_values.iter().sum::() / n as f64; + let variance = trait_values.iter().map(|v| (v - mean).powi(2)).sum::() / (n - 1) as f64; + let sd = variance.sqrt(); + // A constant trait has no z-score; it also has no correlation with + // anything, so it should have been dropped before we get here. + if !(sd > 0.0) { + return None; + } + standardised.push(trait_values.iter().map(|v| (v - mean) / sd).collect()); + } + let mut out = Vec::with_capacity(pca.components.len()); + for (index, component) in pca.components.iter().enumerate() { + let mut scores = vec![0.0; n]; + for (trait_index, loading) in component.loadings.iter().enumerate() { + for (individual, z) in standardised[trait_index].iter().enumerate() { + scores[individual] += loading * z; + } + } + out.push(PcTrait { + name: format!("PC{}", index + 1), + values: individuals + .iter() + .cloned() + .zip(scores) + .map(|(name, value)| PcValue { name, value }) + .collect(), + explained_variance_ratio: component.explained_variance_ratio, + }); } + Some(out) } #[cfg(test)] diff --git a/src/routes/compare.rs b/src/routes/compare.rs new file mode 100644 index 0000000..9879b8a --- /dev/null +++ b/src/routes/compare.rs @@ -0,0 +1,290 @@ +//! Compare two traits: their shared individuals, the correlation, and a +//! scatter plot of one against the other. +//! +//! GN1's "compare traits" and GN2's trait page both show this, and every piece +//! of it already existed here -- `values_of` for the values, the engine for r +//! and p, the plot family for the figure. What was missing was one endpoint +//! that says "these two, over the individuals they share", with the individual +//! names in the reply so a reader can see which points they are looking at. +//! +//! Deliberate choices: +//! +//! * **The minimum overlap is the correlation floor** (6), not 2: two points +//! always fit a line, and a scatter of two points would look like a result. +//! * **The individuals travel with the numbers**, because a scatter plot is +//! read by looking at outliers, and "which animal is that" is the first +//! question. GN2's page answers it with a hover label; here it is in the +//! reply and in the plot's tooltips. +//! * **Nothing is regressed.** The line in the plot is drawn from r and the two +//! means (an ordinary least-squares line through standardised values), which +//! is the only slope implied by the numbers; no fitted model is invented. + +use axum::Json; +use serde::Deserialize; +use utoipa::ToSchema; + +use crate::auth::AuthToken; +use crate::correlation::{self, Method, Reference}; +use crate::error::ApiError; +use crate::error::Unauthorized; +use crate::response::{Ctx, Envelope}; + +use super::correlation::{db_failure, values_of, TraitRef}; +use crate::plot; +use gnauth_macros::gnauth; + +#[derive(Debug, Clone, Deserialize, ToSchema)] +pub struct CompareRequest { + /// The first trait. + pub a: TraitRef, + /// The second trait. + pub b: TraitRef, + /// "pearson" (default) or "spearman". + #[serde(default)] + pub method: Option, +} + +#[utoipa::path(post, path = "/compute/compare", + summary = "Compare two traits: their shared individuals, r, p and n", + description = "Fetches both traits, keeps the individuals that have a value for both, and \ +returns the correlation over them together with the paired values -- so the reply is both the \ +statistic and the data a scatter plot is drawn from. Needs the same six paired observations the \ +rest of the correlation surface needs: two points always fit a line. `spearman` ranks the pairs \ +first, as everywhere else.", + request_body = CompareRequest, + responses( + (status = 200, description = "The comparison", body = Envelope), + Unauthorized, + (status = 422, description = "Unknown method, a trait with no values, or fewer than six shared individuals", body = ApiError), + (status = 500, description = "Internal error", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn compare( + ctx: Ctx, + _token: AuthToken, + Json(request): Json, +) -> Result>, ApiError> { + let rid = ctx.request_info(); + let fail = |code: &str, title: &str, detail: String| { + ApiError::new( + axum::http::StatusCode::UNPROCESSABLE_ENTITY, + code, + title, + detail, + "compare_traits", + ) + .with_request_id(rid.clone()) + }; + let method = Method::parse(request.method.as_deref().unwrap_or("pearson")) + .map_err(|detail| fail("invalid_method", "Invalid correlation method", detail))?; + + let wanted = request.clone(); + let computed = tokio::task::spawn_blocking(move || align(&request)) + .await + .map_err(|error| { + ApiError::new( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + error.to_string(), + "compare_traits", + ) + .with_request_id(rid.clone()) + })? + .map_err(|failure| failure.into_api(rid.clone()))?; + + let aligned = computed; + let n = aligned.pairs.len(); + if n < correlation::MIN_OVERLAP { + return Err(fail( + "too_few_shared", + "Too few shared individuals", + format!( + "these two traits share {n} individual(s) with values; a comparison needs at \ + least {}", + correlation::MIN_OVERLAP + ), + )); + } + let x: Vec = aligned.pairs.iter().map(|(_, a, _)| *a).collect(); + let y: Vec = aligned.pairs.iter().map(|(_, _, b)| *b).collect(); + let (r, p) = correlation::correlate_named_value(&x, &y, n, method).ok_or_else(|| { + fail( + "no_correlation", + "No correlation", + "the coefficient is not a number over these individuals \ + (a constant trait has no correlation with anything)" + .to_string(), + ) + })?; + + let rows = serde_json::Value::Array( + aligned + .pairs + .iter() + .map(|(individual, a, b)| serde_json::json!([individual, a, b])) + .collect(), + ); + let mut body = serde_json::json!({ + "a": {"dataset": wanted.a.dataset, "trait_name": wanted.a.trait_name}, + "b": {"dataset": wanted.b.dataset, "trait_name": wanted.b.trait_name}, + "method": method.as_str(), + "r": r, + "p": if p.is_finite() { serde_json::Value::from(p) } else { serde_json::Value::Null }, + "n": n, + "pairs": rows, + }); + if let Some(extra) = aligned.only_one_side { + body["only_one_side"] = serde_json::Value::from(extra); + } + Ok(Json( + ctx.envelope(body) + .with_columns( + vec!["individual".to_string(), "a".to_string(), "b".to_string()], + n, + ) + .with_note(&format!( + "{} ({}) against {} ({}), {} over the {n} individual(s) with a value for both.", + wanted.a.trait_name, wanted.a.dataset, wanted.b.trait_name, wanted.b.dataset, + method.as_str() + )) + .with_note( + "`pairs` is positional: individual, first trait's value, second trait's value. \ + The individuals that had a value for only one side are counted in \ + `only_one_side`.", + ) + .with_next("/plot/compare", "The same numbers as a scatter plot"), + )) +} + +#[utoipa::path(post, path = "/plot/compare", + summary = "Draw the scatter plot of two compared traits, as an SVG", + description = "Post the response of POST /compute/compare back (as-is) and get the figure \ +scripts/plot-compare.py draws from it: one point per individual that has both values, the \ +individual's name in each point's tooltip, and the least-squares line implied by r and the two \ +means. Nothing is refitted and nothing is recomputed. image/svg+xml, not the JSON envelope; \ +`x-plot-summary` carries the plotter's one-line summary.", + params(super::plot::PlotParams), + request_body = serde_json::Value, + responses( + (status = 200, description = "The SVG", body = String, content_type = "image/svg+xml"), + Unauthorized, + (status = 422, description = "The posted body is not a comparison", body = ApiError), + (status = 502, description = "The plotter failed", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn plot_compare( + ctx: Ctx, + _token: AuthToken, + axum::extract::Query(plot_params): axum::extract::Query, + Json(posted): Json, +) -> Result { + let rid = ctx.request_info(); + let data = posted.get("data").unwrap_or(&posted); + let pairs = data.get("pairs").and_then(|pairs| pairs.as_array()); + if pairs.map(|rows| rows.len()).unwrap_or(0) < 2 { + return Err(ApiError::new( + axum::http::StatusCode::UNPROCESSABLE_ENTITY, + "not_a_comparison", + "Not a comparison", + "the posted body has fewer than two `pairs`: post a /compute/compare reply".to_string(), + "plot_compare", + ) + .with_request_id(rid)); + } + let config = crate::config::Config::load(); + let mut extra: Vec = Vec::new(); + if let Some(title) = plot_params.title.as_deref() { + extra.push("--title".to_string()); + extra.push(title.to_string()); + } + let borrowed: Vec<&str> = extra.iter().map(String::as_str).collect(); + let rendered = plot::render( + &config.plot_python, + &config.compare_plotter, + std::path::Path::new(&config.gemma_cache_dir), + &posted, + plot_params.trait_label.as_deref().unwrap_or(""), + &borrowed, + ) + .await + .map_err(|error| { + ApiError::new( + axum::http::StatusCode::BAD_GATEWAY, + "plot_failed", + "The plotter failed", + error.to_string(), + "plot_compare", + ) + .with_request_id(rid) + })?; + Ok(super::plot::svg_response(rendered)) +} + +/// The aligned pairs, plus a count of individuals only one side had. +struct Aligned { + pairs: Vec<(String, f64, f64)>, + only_one_side: Option, +} + +fn align(request: &CompareRequest) -> Result { + let a = values_of(&request.a.dataset, &request.a.trait_name)?; + let b = values_of(&request.b.dataset, &request.b.trait_name)?; + let mut pairs = Vec::new(); + let mut only_one_side = 0usize; + for (index, name) in a.names.iter().enumerate() { + match b.names.iter().position(|candidate| candidate == name) { + Some(position) => pairs.push((name.clone(), a.values[index], b.values[position])), + None => only_one_side += 1, + } + } + // Individuals only in B are not visited by the loop above. + for name in &b.names { + if !a.names.contains(name) { + only_one_side += 1; + } + } + Ok(Aligned { + pairs, + only_one_side: if only_one_side > 0 { + Some(only_one_side) + } else { + None + }, + }) +} + +/// Keep `Reference` in scope for readers of `align`. +#[allow(dead_code)] +fn _reference_is_used(_: &Reference) {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pairs_are_the_shared_individuals() { + let a = Reference::from_pairs(vec![ + ("s1".to_string(), Some(1.0)), + ("s2".to_string(), Some(2.0)), + ("s3".to_string(), Some(3.0)), + ]); + let b = Reference::from_pairs(vec![ + ("s2".to_string(), Some(20.0)), + ("s3".to_string(), Some(30.0)), + ("s4".to_string(), Some(40.0)), + ]); + let mut pairs = Vec::new(); + for (index, name) in a.names.iter().enumerate() { + if let Some(position) = b.names.iter().position(|candidate| candidate == name) { + pairs.push((name.clone(), a.values[index], b.values[position])); + } + } + assert_eq!(pairs, vec![ + ("s2".to_string(), 2.0, 20.0), + ("s3".to_string(), 3.0, 30.0), + ]); + } +} diff --git a/src/routes/correlation.rs b/src/routes/correlation.rs index 2a7f8a2..a3620f6 100644 --- a/src/routes/correlation.rs +++ b/src/routes/correlation.rs @@ -702,7 +702,7 @@ fn resolve_reference(request: &CorrelationRequest) -> Result Result { +pub(crate) fn values_of(dataset: &str, trait_name: &str) -> Result { let request = CorrelationRequest { dataset: dataset.to_string(), trait_name: trait_name.to_string(), diff --git a/src/routes/correlation_matrix.rs b/src/routes/correlation_matrix.rs index 9a433b6..9676cd4 100644 --- a/src/routes/correlation_matrix.rs +++ b/src/routes/correlation_matrix.rs @@ -167,7 +167,7 @@ pub async fn correlation_matrix( } let wanted = request.clone(); - let matrix = tokio::task::spawn_blocking(move || build(&request, method, min_overlap)) + let (matrix, references) = tokio::task::spawn_blocking(move || build(&request, method, min_overlap)) .await .map_err(|error| { ApiError::new( @@ -192,11 +192,22 @@ pub async fn correlation_matrix( } } let measured = measured / 2; - let pca = if wanted.pca.unwrap_or(false) { + let mut pca = if wanted.pca.unwrap_or(false) { Some(crate::pca::analyse(&matrix)) } else { None }; + // The components as *traits*: a PC is only usable (correlated, mapped, + // plotted, saved in a basket) if it has a value per individual, and that + // needs the values the matrix was built from -- which is why it happens + // here and not in pca::analyse. + if let Some(pca) = pca.as_mut() { + if let Some((values, individuals)) = kept_values_in_order(&references, pca) { + if let Some(traits) = crate::pca::scores(pca, &values, &individuals) { + pca.traits = traits; + } + } + } let mut body = serde_json::json!({ "traits": matrix.traits, "r": matrix.r, @@ -278,6 +289,64 @@ pub async fn correlation_matrix( )) } +/// The aligned values of the traits the PCA kept, over the individuals that +/// have a value for **every** kept trait. +/// +/// PCA of standardised traits is only defined on a complete rectangle, which is +/// the same rule that already dropped traits with a gap: a different individual +/// set per trait would make the scores incomparable across individuals. +fn kept_values_in_order( + references: &[Reference], + pca: &crate::pca::Pca, +) -> Option<(Vec>, Vec)> { + let components = pca.components.first()?; + let n_kept = components.loadings.len(); + if n_kept == 0 || n_kept > references.len() { + return None; + } + // The kept traits are the first n_kept that have values; the PCA was built + // from the matrix's own kept order, so take that same order. + let kept: Vec<&Reference> = references + .iter() + .filter(|reference| !reference.is_empty()) + .take(n_kept) + .collect(); + if kept.len() != n_kept { + return None; + } + let individuals: Vec = kept[0] + .names + .iter() + .filter(|name| { + kept.iter().all(|reference| { + reference + .names + .iter() + .position(|candidate| candidate == *name) + .map(|position| true) + .unwrap_or(false) + }) + }) + .cloned() + .collect(); + if individuals.len() < 3 { + return None; + } + let mut values: Vec> = Vec::with_capacity(n_kept); + for reference in &kept { + let mut row = Vec::with_capacity(individuals.len()); + for name in &individuals { + let position = reference + .names + .iter() + .position(|candidate| candidate == name)?; + row.push(reference.values[position]); + } + values.push(row); + } + Some((values, individuals)) +} + /// How many traits the request asked for. fn matrix_trait_count(matrix: &Matrix) -> usize { matrix.traits.len() @@ -299,9 +368,10 @@ fn build( request: &MatrixRequest, method: Method, min_overlap: usize, -) -> Result { +) -> Result<(Matrix, Vec), Failure> { let axis = matrix_axis(request)?; let references = resolve_traits(request, axis.as_deref())?; + let references_out = references.clone(); let count = references.len(); let mut r = vec![vec![None; count]; count]; @@ -343,7 +413,7 @@ fn build( } } - Ok(Matrix { + Ok((Matrix { traits: request .traits .iter() @@ -355,7 +425,7 @@ fn build( r, p, n, - }) + }, references_out)) } /// The individuals every trait is measured over: the first trait's group. diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 0461165..0da2eaa 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -7,6 +7,7 @@ pub mod accessions; pub mod baskets; pub mod bnw; pub mod bulklmm; +pub mod compare; pub mod correlation; pub mod correlation_matrix; pub mod datasets; diff --git a/src/routes/plot.rs b/src/routes/plot.rs index 2b4c043..d33f5d7 100644 --- a/src/routes/plot.rs +++ b/src/routes/plot.rs @@ -346,7 +346,7 @@ pub async fn plot_gemma( } /// The SVG, with the plotter's summary alongside it. -fn svg_response(rendered: plot::Plot) -> Response { +pub(crate) fn svg_response(rendered: plot::Plot) -> Response { let mut response = rendered.svg.into_response(); let headers = response.headers_mut(); headers.insert( -- cgit 1.4.1