about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-11-15 04:08:15 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-11-15 04:08:15 +0000
commit07bf685a30c2e0d740fd22958a3a47ebaf48f98f (patch)
tree013e00292145db4d19bf74197274511f26dcde5c /src
parenta2f47b25669568f84965c8efd3b6f9ecac572144 (diff)
downloadgenenetwork4-07bf685a30c2e0d740fd22958a3a47ebaf48f98f.tar.gz
correlation: run over the group's sample axis, and report a perfect correlation as 0.0
Two divergences from the live genenetwork.org, both measured against it.

**The sample axis.** GN2's `get_sample_r_and_p_values` walks
`target_dataset.group.samplelist` and takes the reference value by name:
the correlation runs over the group's animals, not over every individual
the trait happens to have a value for. Trait 1427571_at of HC_M2_0606_P
carries 99 values, the BXD panel holds 67 of those individuals, and the
answer changes materially -- GN2's top hit is a -0.845 probe that does
not appear in our top five at all. `corr_samples_group` now takes
`samples_primary` (default, the group's genotype panel, which is where
GN2's list comes from) or `samples_all` (the old behaviour); the panel is
read with `genotypes::resolve`, falling back to the group's
used-for-mapping strains where a group has no genotype file on this
machine. `samples_other` is refused rather than guessed.

**A perfect correlation.** The engine's r can land at 1.0000000000000002,
which makes 1 - r^2 negative and its p-value NaN. The live API answers
0.0 for that row (scipy's pearsonr), so the reply now clamps: r to +-1 and
p to 0.0. That is the reference's *output* being reproduced, not a
computation being redone -- #96 stays resolved in the same direction.

With the axis fixed, n agrees with the live site exactly (67) and r
agrees with GN2's own published per-sample values to 1.4e-8. What does
not yet agree is GN2's reported r itself: over the same 67 individuals,
its `/correlation` endpoint says -0.8446202819617522 for 1447043_at while
correlating the values its own `/sample_data` endpoint publishes for the
same two traits gives -0.8393085803732605; on a second pair the gap is
-0.8479321530363810 against -0.8451666639589470. Both pairs are off in
the same direction and by a similar amount, so the two GN2 endpoints are
reading different values for the same samples -- not a difference of
sample sets (all four BXD genotype files give the same 67) and not a
transform (2**v, 10**v, exp, v**2 and log were all tried). Until that is
settled, our numbers are the reference's published values correlated
correctly, and the ranking cannot be identical to a number we cannot
reproduce from the reference's own data.
Diffstat (limited to 'src')
-rw-r--r--src/correlation.rs31
-rw-r--r--src/db.rs38
-rw-r--r--src/routes/correlation.rs87
3 files changed, 153 insertions, 3 deletions
diff --git a/src/correlation.rs b/src/correlation.rs
index 274bf56..cb16e6c 100644
--- a/src/correlation.rs
+++ b/src/correlation.rs
@@ -111,6 +111,28 @@ impl Reference {
     pub fn x_vals(&self) -> &[f64] {
         &self.values
     }
+
+    /// Keep only the individuals in `allowed`, returning how many remain.
+    ///
+    /// This is GN2's `samples_primary`: a correlation over a group is a
+    /// correlation among that group's animals, even when the reference trait
+    /// carries values for more of them.  Measured against the live API, the
+    /// difference is not cosmetic -- HC_M2_0606_P's trait 1427571_at has 99
+    /// values but the group has 67 animals, and the ranking changes
+    /// completely between the two sets.
+    pub fn retain_within(&mut self, allowed: &[String]) -> usize {
+        let mut names = Vec::with_capacity(self.names.len());
+        let mut values = Vec::with_capacity(self.values.len());
+        for (name, value) in self.names.iter().zip(self.values.iter()) {
+            if allowed.iter().any(|candidate| candidate == name) {
+                names.push(name.clone());
+                values.push(*value);
+            }
+        }
+        self.names = names;
+        self.values = values;
+        self.len()
+    }
 }
 
 /// Correlate a target trait (given as (individual, value) pairs) against the
@@ -159,6 +181,15 @@ pub fn correlate_named(
         Method::Pearson => Pearson::new(n).correlate(&parsed.x_vals, &parsed.y_vals),
         Method::Spearman => Spearman::new(n).correlate(&parsed.x_vals, &parsed.y_vals),
     };
+    // A perfect correlation: the engine's r can come out as 1.0000000000000002,
+    // so 1 - r^2 is negative and its p-value is NaN.  The live GN2 API answers
+    // 0.0 for the same row (scipy's pearsonr), so clamp to the reference's
+    // output rather than exposing the engine's last-bit artefact.
+    let (r, p) = if r.abs() >= 1.0 {
+        (r.signum(), 0.0)
+    } else {
+        (r, p)
+    };
     Some(Hit {
         name: if parsed.row_name.is_empty() {
             name.to_string()
diff --git a/src/db.rs b/src/db.rs
index 91734f7..2f9caf0 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -1552,6 +1552,44 @@ pub fn get_dataset_probeset_values(
     .map_err(DbError::from)
 }
 
+/// The short group name a dataset belongs to (`InbredSet.Name`), which is how
+/// genotype files are named.
+pub fn get_dataset_group_name(dataset_name: &str) -> Result<Option<String>, DbError> {
+    let pool = pool()?;
+    let mut conn = pool.get_conn()?;
+    let probeset: Option<String> = conn
+        .exec_first(
+            "SELECT InbredSet.Name FROM ProbeSetFreeze \
+             JOIN ProbeFreeze ON ProbeFreeze.ProbeFreezeId = ProbeSetFreeze.ProbeFreezeId \
+             JOIN InbredSet ON InbredSet.Id = ProbeFreeze.InbredSetId \
+             WHERE ProbeSetFreeze.Name = :name LIMIT 1",
+            mysql::params! { "name" => dataset_name },
+        )
+        .map_err(DbError::from)?;
+    if probeset.is_some() {
+        return Ok(probeset);
+    }
+    conn.exec_first(
+        "SELECT InbredSet.Name FROM PublishFreeze \
+         JOIN InbredSet ON InbredSet.Id = PublishFreeze.InbredSetId \
+         WHERE PublishFreeze.Name = :name LIMIT 1",
+        mysql::params! { "name" => dataset_name },
+    )
+    .map_err(DbError::from)
+}
+
+/// The group's strains that are used for mapping, the fallback sample axis
+/// when a group has no genotype file on this machine.
+pub fn get_group_mapping_samples(group_name: &str) -> Result<Vec<String>, DbError> {
+    let Some(group) = get_group_by_name(group_name)? else {
+        return Ok(Vec::new());
+    };
+    Ok(get_group_strains(group.id, Some(true))?
+        .into_iter()
+        .map(|strain| strain.name)
+        .collect())
+}
+
 /// Every value of every trait in a probeset dataset, restricted to a set of
 /// individuals: one record per (trait, individual, value).
 ///
diff --git a/src/routes/correlation.rs b/src/routes/correlation.rs
index 00442a9..9b91735 100644
--- a/src/routes/correlation.rs
+++ b/src/routes/correlation.rs
@@ -39,6 +39,12 @@ pub struct CorrelationRequest {
     /// How many hits to return, strongest by |r| first. Defaults to 500.
     #[serde(default)]
     pub top_n: Option<usize>,
+    /// Which individuals the correlation runs over, GN2's `corr_samples_group`:
+    /// "samples_primary" (default) restricts to the trait's own group,
+    /// "samples_all" uses every individual the trait has a value for.
+    /// "samples_other" is not supported yet (it needs the other sample lists).
+    #[serde(default)]
+    pub corr_samples_group: Option<String>,
 }
 
 #[utoipa::path(post, path = "/compute/correlation",
@@ -129,6 +135,39 @@ pub async fn correlation(
     ))
 }
 
+/// GN2's `corr_samples_group`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum SampleGroup {
+    /// The trait's own group -- GN2's default.
+    Primary,
+    /// Every individual the reference trait has a value for.
+    All,
+}
+
+impl SampleGroup {
+    fn parse(name: Option<&str>) -> Result<Self, Failure> {
+        match name.unwrap_or("samples_primary").trim().to_ascii_lowercase().as_str() {
+            "" | "samples_primary" => Ok(SampleGroup::Primary),
+            "samples_all" => Ok(SampleGroup::All),
+            "samples_other" => Err(Failure::NoValues(
+                "corr_samples_group=samples_other is not supported yet; use \
+                 samples_primary or samples_all"
+                    .to_string(),
+            )),
+            other => Err(Failure::NoValues(format!(
+                "unknown corr_samples_group '{other}'; use samples_primary or samples_all."
+            ))),
+        }
+    }
+
+    fn as_str(&self) -> &'static str {
+        match self {
+            SampleGroup::Primary => "samples_primary",
+            SampleGroup::All => "samples_all",
+        }
+    }
+}
+
 /// Why a correlation request could not be answered.
 enum Failure {
     NotFound(String),
@@ -162,6 +201,29 @@ impl Failure {
     }
 }
 
+/// The individuals a `samples_primary` correlation runs over: the group's
+/// genotype panel, which is where GN2's `group.samplelist` comes from.
+///
+/// Measured on the live site: trait 1427571_at of HC_M2_0606_P carries 99
+/// values, the BXD panel holds 67 of those individuals, and GN2 correlates
+/// over exactly those 67 -- not cosmetic, it reorders the whole reply.
+///
+/// A group with no genotype file on this machine falls back to its
+/// used-for-mapping strains; for BXD those are the same 67 individuals, so the
+/// axis survives either way.
+fn sample_axis(dataset: &str) -> Result<Option<Vec<String>>, Failure> {
+    let Some(group) = db::get_dataset_group_name(dataset).map_err(db_failure)? else {
+        return Ok(None);
+    };
+    let root = crate::config::Config::load().genotype_files_dir.clone();
+    match crate::genotypes::resolve(std::path::Path::new(&root), &group, None) {
+        Ok(resolved) => Ok(Some(resolved.panel)),
+        Err(_) => Ok(Some(
+            db::get_group_mapping_samples(&group).map_err(db_failure)?,
+        )),
+    }
+}
+
 /// The blocking half: resolve both datasets, fetch the values, correlate.
 ///
 /// Either side may be a ProbeSet (expression) dataset or a Publish (phenotype)
@@ -172,7 +234,25 @@ fn compute(
     method: Method,
     top_n: usize,
 ) -> Result<(String, Vec<correlation::Hit>), Failure> {
-    let reference = resolve_reference(request)?;
+    let group = SampleGroup::parse(request.corr_samples_group.as_deref())?;
+    let mut reference = resolve_reference(request)?;
+    let kept = match group {
+        SampleGroup::Primary => {
+            let axis = sample_axis(&request.dataset)?;
+            match axis {
+                Some(samples) => reference.retain_within(&samples),
+                // No group behind the dataset: nothing to restrict to.
+                None => reference.len(),
+            }
+        }
+        SampleGroup::All => reference.len(),
+    };
+    if kept == 0 {
+        return Err(Failure::NoValues(format!(
+            "'{}' has no values among the individuals this request selects",
+            request.trait_name
+        )));
+    }
     if reference.values.is_empty() {
         return Err(Failure::NoValues(format!(
             "'{}' has no values in '{}', so there is nothing to correlate",
@@ -192,10 +272,11 @@ fn compute(
     let hits = correlation::correlate_many(&reference, method, rows, top_n);
     Ok((
         format!(
-            "{} ({}, {} observations)",
+            "{} ({}, {} observations, {})",
             request.trait_name,
             request.dataset,
-            reference.len()
+            reference.len(),
+            group.as_str()
         ),
         hits,
     ))