diff options
| author | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-15 01:27:39 +0000 |
|---|---|---|
| committer | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-15 01:27:39 +0000 |
| commit | 41c70f042731e36fb91b8fb3f4f393a4aa654e9d (patch) | |
| tree | 25c8a8ffcccd7a6e533686c0906fc8c44ad89ef3 /src | |
| parent | 4dbb553d5e4e48a785bbb5f4b97a84836eef296a (diff) | |
| download | genenetwork4-41c70f042731e36fb91b8fb3f4f393a4aa654e9d.tar.gz | |
correlation: the sample-axis engine path, with the decided semantics
src/correlation.rs now holds the part the engine does not offer in memory, and nothing of the arithmetic: `Pearson`/`Spearman` and their p-values are correlation_rust's (and GSL's). What is ours is the alignment into the engine's parser, the minimum-overlap gate, the ordering and top-N: - alignment is by individual, never by position: an individual the target trait lacks becomes "NA", which the engine's parser drops together with its reference value, so a missing observation costs one pair, not the row; - minimum overlap 6, so a two- or four-point +-1 cannot appear; - ordering reuses correlation_rust's own `custom_float_sorter` -- |r| descending, NaNs last -- so GN2, GN3 and GN4 sort identically; - top-N after the sort, clamped to GN2's 20000 ceiling; - bicor is refused by name with the methods that exist, rather than answered with something else. Tests cover both methods, the six-pair minimum, name alignment across a reordered and sparse candidate, the ordering with top-N, and the method parsing. The route is still the stub; wiring it to the bulk fetch is next.
Diffstat (limited to 'src')
| -rw-r--r-- | src/correlation.rs | 352 | ||||
| -rw-r--r-- | src/lib.rs | 1 |
2 files changed, 353 insertions, 0 deletions
diff --git a/src/correlation.rs b/src/correlation.rs new file mode 100644 index 0000000..bd2b91a --- /dev/null +++ b/src/correlation.rs @@ -0,0 +1,352 @@ +//! Sample-axis correlation: one trait against every trait of a target dataset, +//! observations being individuals. +//! +//! The arithmetic is the `correlation_rust` engine's, not ours: `Pearson` and +//! `Spearman` (16c2a37 made the latter public) and its p-values, which come +//! from GSL's t-distribution. What lives here is the part the engine does not +//! offer in memory -- the row alignment into its parser, the minimum-overlap +//! gate, and the ordering/top-N policy -- plus the fetch, which is the +//! expensive half. +//! +//! Semantics, as decided in docs/correlations.md: +//! +//! - **minimum overlap 6**, the gn3/python value rather than the engine's 4, +//! so a two- or four-point correlation cannot appear at all; +//! - **|r| descending, NaNs last** -- the engine's own `custom_float_sorter`, +//! so GN2, GN3 and GN4 sort identically; +//! - **top-N after the sort**; +//! - pearson and spearman only. Bicor does not exist in the engine and is +//! refused by name rather than silently answered with something else. + +use correlation_rust::correlations::{Correlation, Pearson, Spearman}; +use correlation_rust::parser::parse_rows_with_names; +use correlation_rust::sorter::custom_float_sorter; + +/// The fewest paired observations a correlation may be computed from. +pub const MIN_OVERLAP: usize = 6; + +/// How many hits a request may ask for when it does not say. +pub const DEFAULT_TOP_N: usize = 500; + +/// The largest top-N we will run: GN2's menu tops out at 20000. +pub const MAX_TOP_N: usize = 20_000; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Method { + Pearson, + Spearman, +} + +impl Method { + /// Parse the request's method name. `Err` carries the names we do accept, + /// so the caller can say what the request should have been. + pub fn parse(name: &str) -> Result<Self, String> { + match name.trim().to_ascii_lowercase().as_str() { + "pearson" => Ok(Method::Pearson), + "spearman" => Ok(Method::Spearman), + "bicor" => Err( + "bicor is not available: the correlation engine implements pearson and \ + spearman only." + .to_string(), + ), + other => Err(format!( + "unknown correlation method '{other}'; use pearson or spearman." + )), + } + } + + pub fn as_str(&self) -> &'static str { + match self { + Method::Pearson => "pearson", + Method::Spearman => "spearman", + } + } +} + +/// One trait's correlation against the reference trait. +#[derive(Debug, Clone, PartialEq)] +pub struct Hit { + /// The trait's name in the target dataset (ProbeSet.Name). + pub name: String, + pub r: f64, + pub p: f64, + /// How many pairs the coefficient was computed from. + pub n: usize, +} + +/// The reference trait's values, one per individual, in a fixed order. +/// +/// `names` is the alignment key: a target trait's value is paired with the +/// reference value for the *same individual*, never by position, because two +/// traits of the same dataset need not list their individuals in the same +/// order -- and a dataset's rows may be sparse. +#[derive(Debug, Clone, Default)] +pub struct Reference { + pub names: Vec<String>, + pub values: Vec<f64>, +} + +impl Reference { + /// Build from (individual, value) pairs, keeping only those with a value. + pub fn from_pairs(pairs: impl IntoIterator<Item = (String, Option<f64>)>) -> Self { + let mut reference = Reference::default(); + for (name, value) in pairs { + if let Some(value) = value.filter(|value| value.is_finite()) { + reference.names.push(name); + reference.values.push(value); + } + } + reference + } + + pub fn len(&self) -> usize { + self.values.len() + } + + pub fn is_empty(&self) -> bool { + self.values.is_empty() + } + + /// The value vector the engine parses against. + pub fn x_vals(&self) -> &[f64] { + &self.values + } +} + +/// Correlate a target trait (given as (individual, value) pairs) against the +/// reference, returning `None` when there is too little overlap to say +/// anything. +/// +/// The alignment is delegated to the engine's own parser: it drops, together +/// with the matching reference value, any target value that does not parse -- +/// which is how a missing observation is expressed here, as the string "NA". +pub fn correlate_one(reference: &Reference, method: Method, pairs: &[(String, Option<f64>)]) -> Option<Hit> { + correlate_named(reference, method, "", pairs) +} + +/// As [`correlate_one`], but naming the result -- what the row-level entry +/// point uses. +pub fn correlate_named( + reference: &Reference, + method: Method, + name: &str, + pairs: &[(String, Option<f64>)], +) -> Option<Hit> { + if reference.is_empty() { + return None; + } + // The target's values in the reference's order; an individual it lacks is + // "NA", which the engine's parser drops together with its reference value. + let mut row: Vec<String> = Vec::with_capacity(reference.len() + 1); + row.push(name.to_string()); + row.extend( + reference + .names + .iter() + .map(|individual| match value_of(pairs, individual) { + Some(value) => value.to_string(), + None => "NA".to_string(), + }), + ); + let row: Vec<&str> = row.iter().map(String::as_str).collect(); + + let parsed = parse_rows_with_names(reference.x_vals(), &row); + let n = parsed.x_vals.len(); + if n < MIN_OVERLAP { + return None; + } + let (r, p) = match method { + Method::Pearson => Pearson::new(n).correlate(&parsed.x_vals, &parsed.y_vals), + Method::Spearman => Spearman::new(n).correlate(&parsed.x_vals, &parsed.y_vals), + }; + Some(Hit { + name: if parsed.row_name.is_empty() { + name.to_string() + } else { + parsed.row_name + }, + r, + p, + n, + }) +} + +/// Correlate every candidate trait against the reference, ordered and +/// truncated as the policy says. +/// +/// `rows` is one `(trait name, individual, value)` record per value: the shape +/// the bulk fetch returns, streamed rather than grouped so the caller can feed +/// it from a database cursor. +pub fn correlate_many( + reference: &Reference, + method: Method, + rows: impl IntoIterator<Item = (String, String, Option<f64>)>, + top_n: usize, +) -> Vec<Hit> { + // Group by trait, keeping the fetch's own order within a trait. + let mut by_trait: Vec<(String, Vec<(String, Option<f64>)>)> = Vec::new(); + let mut positions: std::collections::HashMap<String, usize> = std::collections::HashMap::new(); + for (trait_name, individual, value) in rows { + let position = match positions.get(&trait_name) { + Some(position) => *position, + None => { + by_trait.push((trait_name.clone(), Vec::new())); + let position = by_trait.len() - 1; + positions.insert(trait_name, position); + position + } + }; + by_trait[position].1.push((individual, value)); + } + + let mut hits: Vec<Hit> = by_trait + .iter() + .filter_map(|(name, pairs)| correlate_named(reference, method, name, pairs)) + .collect(); + + // The engine's ordering, reused rather than reimplemented: |r| descending, + // NaNs last. + let mut sortable: Vec<(String, f64, f64, i32)> = hits + .drain(..) + .map(|hit| (hit.name, hit.r, hit.p, hit.n as i32)) + .collect(); + custom_float_sorter(&mut sortable); + let take = top_n.clamp(1, MAX_TOP_N); + sortable.truncate(take); + sortable + .into_iter() + .map(|(name, r, p, n)| Hit { + name, + r, + p, + n: n as usize, + }) + .collect() +} + +/// One individual's value in a trait's pairs, if it has a usable one. +fn value_of(pairs: &[(String, Option<f64>)], individual: &str) -> Option<f64> { + pairs + .iter() + .find(|(name, _)| name == individual) + .and_then(|(_, value)| *value) + .filter(|value| value.is_finite()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn reference(pairs: &[(&str, f64)]) -> Reference { + Reference::from_pairs( + pairs + .iter() + .map(|(name, value)| (name.to_string(), Some(*value))), + ) + } + + /// A perfectly monotone relationship correlates 1 under both methods; the + /// point of the two-method test is that `Spearman` is reachable at all, + /// which it was not before 12c2a37. + #[test] + fn both_methods_answer_with_the_engine() { + let names = ["a", "b", "c", "d", "e", "f"]; + let x: Vec<(&str, f64)> = names.iter().enumerate().map(|(i, n)| (*n, i as f64)).collect(); + let reference = reference(&x); + let y: Vec<(String, Option<f64>)> = names + .iter() + .enumerate() + .map(|(i, n)| (n.to_string(), Some(2.0 * i as f64))) + .collect(); + let pearson = correlate_one(&reference, Method::Pearson, &y).expect("pearson"); + let spearman = correlate_one(&reference, Method::Spearman, &y).expect("spearman"); + assert!((pearson.r - 1.0).abs() < 1e-12, "{pearson:?}"); + assert!((spearman.r - 1.0).abs() < 1e-12, "{spearman:?}"); + assert_eq!(pearson.n, 6); + } + + /// Below the minimum overlap the row does not exist at all: this is the + /// decision that keeps a two-point +-1 out of the ranking. + #[test] + fn fewer_than_six_pairs_is_not_a_correlation() { + let reference = reference(&[("a", 1.0), ("b", 2.0), ("c", 3.0), ("d", 4.0), ("e", 5.0)]); + let y: Vec<(String, Option<f64>)> = ["a", "b", "c", "d", "e"] + .iter() + .map(|n| (n.to_string(), Some(1.0))) + .collect(); + assert!(correlate_one(&reference, Method::Pearson, &y).is_none()); + } + + /// Individuals are matched by name, never by position: a target trait that + /// lists them in another order still lines up, and one that lacks an + /// individual loses that pair only -- six of seven survive, which is + /// exactly the minimum. + #[test] + fn alignment_is_by_individual_not_by_position() { + let names = ["a", "b", "c", "d", "e", "f", "g"]; + let reference = reference( + &names + .iter() + .enumerate() + .map(|(i, name)| (*name, i as f64 + 1.0)) + .collect::<Vec<_>>(), + ); + // Reversed, and 'd' is absent: six pairs, all perfectly monotone. + let y: Vec<(String, Option<f64>)> = ["g", "f", "e", "c", "b", "a"] + .iter() + .map(|name| { + let value = names.iter().position(|n| n == name).unwrap() as f64 + 1.0; + (name.to_string(), Some(value)) + }) + .collect(); + let hit = correlate_one(&reference, Method::Pearson, &y).expect("six pairs is enough"); + assert_eq!(hit.n, 6); + assert!((hit.r - 1.0).abs() < 1e-12, "reversed order, same pairs: {hit:?}"); + } + + /// The ordering policy: |r| descending with NaNs last, top-N applied after. + #[test] + fn ordering_is_by_magnitude_and_top_n_truncates_afterwards() { + let reference = reference(&[("a", 1.0), ("b", 2.0), ("c", 3.0), ("d", 4.0), ("e", 5.0), ("f", 6.0)]); + // Three candidates: strong positive, strong negative, weak. + let mut rows: Vec<(String, String, Option<f64>)> = Vec::new(); + for (individual, value) in [("a", 1.0), ("b", 2.0), ("c", 3.0), ("d", 4.0), ("e", 5.0), ("f", 6.0)] { + rows.push(("strong_pos".to_string(), individual.to_string(), Some(value))); + } + for (individual, value) in [("a", 6.0), ("b", 5.0), ("c", 4.0), ("d", 3.0), ("e", 2.0), ("f", 1.0)] { + rows.push(("strong_neg".to_string(), individual.to_string(), Some(value))); + } + for (individual, value) in [("a", 1.0), ("b", 1.0), ("c", 1.0), ("d", 1.0), ("e", 1.0), ("f", 1.5)] { + rows.push(("weak".to_string(), individual.to_string(), Some(value))); + } + let hits = correlate_many(&reference, Method::Pearson, rows, 2); + assert_eq!(hits.len(), 2, "{hits:?}"); + // -1 and +1 tie on magnitude; the weak one must be absent. + assert!(hits.iter().all(|hit| hit.r.abs() > 0.99), "{hits:?}"); + assert!(!hits.iter().any(|hit| hit.name == "weak"), "{hits:?}"); + + let all = correlate_many( + &reference, + Method::Pearson, + vec![ + ("weak".to_string(), "a".to_string(), Some(1.0)), + ("weak".to_string(), "b".to_string(), Some(1.0)), + ("weak".to_string(), "c".to_string(), Some(1.0)), + ("weak".to_string(), "d".to_string(), Some(1.0)), + ("weak".to_string(), "e".to_string(), Some(1.0)), + ("weak".to_string(), "f".to_string(), Some(1.5)), + ], + 10, + ); + assert_eq!(all.len(), 1, "{all:?}"); + } + + #[test] + fn bicor_is_refused_by_name_and_pearson_is_not() { + assert_eq!(Method::parse("pearson").unwrap(), Method::Pearson); + assert_eq!(Method::parse(" Spearman ").unwrap(), Method::Spearman); + let error = Method::parse("bicor").unwrap_err(); + assert!(error.contains("bicor") && error.contains("pearson"), "{error}"); + assert!(Method::parse("kendall").is_err()); + } +} diff --git a/src/lib.rs b/src/lib.rs index 273554d..965ed14 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,7 @@ pub mod baskets; pub mod bnw; pub mod bulklmm; pub mod compute_gate; +pub mod correlation; pub mod covariates; pub mod config; pub mod db; |
