about summary refs log tree commit diff
path: root/src/db.rs
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-11-15 12:57:07 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-11-15 12:57:07 +0000
commita0eb72fcaeef0a9462dbf2dda383350e95696431 (patch)
treee50fc2e4ba2a02bd49ca8a42e83bfe90f24b5c8a /src/db.rs
parentcb0527d043ac041508f111451392c64fcaf3643c (diff)
downloadgenenetwork4-a0eb72fcaeef0a9462dbf2dda383350e95696431.tar.gz
correlation: tissue and literature axes, paired the way the data actually is
`type` on /compute/correlation now selects GN2's `corr_type`: sample
(default), tissue or literature. Partial is refused by name rather than
silently treated as sample.

**tissue** reduces each gene symbol to its highest-Mean probe in
TissueProbeSetXRef and pairs the two value vectors **by TissueID**. That
last word is the difference from GN2, which keeps each vector as a bare
list and pairs by position on the assumption that every probe covers the
same tissues. On this database it does not: every probe carries exactly
26 values (liver, kidney, spleen, ... peripheral) or exactly 32
(striatum, hippocampus, neocortex, ... brain regions), the two sets are
disjoint, and 45 281 probes are in each. Pairing those positionally
correlates liver expression with striatum expression because both happen
to be entry one. Pairing by tissue means a cross-panel pair has no
correlation at all, which is the honest answer and makes the panel
boundary visible instead of inventing a number.

Verified independently for Shh vs Hcrtr1: 0.7222718302270719 from the
endpoint, 0.7222719072696666 from a separate Pearson over the same
TissueID-aligned pairs (the residue is MySQL's single-precision `float`
column as printed by the client).

**literature** looks the pair up in LCorrRamin3 in both directions after
translating rat/human ids through GeneIDXRef, in chunks of 4 000 genes
(the first attempt died on MySQL's 65 535-placeholder limit). It is a
precomputed value, not a statistic: p and n are null. A trait with no
gene id or no row is left out and counted in the note, where GN2 reports
0.0 and fills the tail of its top-N with them -- that reads as "measured,
no relationship", which is not what happened.

Gene ids come from ProbeSet.GeneId, not ProbeSetXRef.GeneId: the latter
has no such column here, which GN3's own mapping also records.
Diffstat (limited to 'src/db.rs')
-rw-r--r--src/db.rs192
1 files changed, 192 insertions, 0 deletions
diff --git a/src/db.rs b/src/db.rs
index 2f9caf0..505ef51 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -1590,6 +1590,198 @@ pub fn get_group_mapping_samples(group_name: &str) -> Result<Vec<String>, DbErro
         .collect())
 }
 
+/// The species of the group a dataset belongs to (`InbredSet.SpeciesId` ->
+/// `Species.Name`), which is how GN2 decides whether a gene id needs
+/// translating to mouse before it is looked up in `LCorrRamin3`.
+pub fn get_dataset_species(dataset_name: &str) -> Result<Option<String>, DbError> {
+    let pool = pool()?;
+    let mut conn = pool.get_conn()?;
+    conn.exec_first(
+        "SELECT Species.Name FROM ProbeSetFreeze \
+         JOIN ProbeFreeze ON ProbeFreeze.ProbeFreezeId = ProbeSetFreeze.ProbeFreezeId \
+         JOIN InbredSet ON InbredSet.Id = ProbeFreeze.InbredSetId \
+         JOIN Species ON Species.Id = InbredSet.SpeciesId \
+         WHERE ProbeSetFreeze.Name = :name LIMIT 1",
+        mysql::params! { "name" => dataset_name },
+    )
+    .map_err(DbError::from)
+}
+
+/// `ProbeSet.Name` -> `ProbeSet.Symbol` for one probeset dataset, the axis
+/// the tissue correlation is keyed on.
+pub fn get_dataset_symbols(dataset_id: u16) -> Result<Vec<(String, String)>, DbError> {
+    let pool = pool()?;
+    let mut conn = pool.get_conn()?;
+    conn.exec_map(
+        "SELECT ProbeSet.Name, ProbeSet.Symbol \
+         FROM ProbeSet JOIN ProbeSetXRef ON ProbeSetXRef.ProbeSetId = ProbeSet.Id \
+         WHERE ProbeSetXRef.ProbeSetFreezeId = :dataset_id \
+           AND ProbeSet.Symbol IS NOT NULL AND ProbeSet.Symbol <> '' \
+         ORDER BY ProbeSet.Id",
+        mysql::params! { "dataset_id" => dataset_id },
+        |(name, symbol): (String, String)| (name, symbol),
+    )
+    .map_err(DbError::from)
+}
+
+/// `ProbeSet.Name` -> `ProbeSetXRef.GeneId` for one probeset dataset, the axis
+/// the literature correlation is keyed on.
+pub fn get_dataset_geneids(dataset_id: u16) -> Result<Vec<(String, String)>, DbError> {
+    let pool = pool()?;
+    let mut conn = pool.get_conn()?;
+    conn.exec_map(
+        // The gene id lives on ProbeSet, not on ProbeSetXRef: GN3's own mapping
+        // is `ProbeSet.GeneId`, and ProbeSetXRef has no GeneId column here.
+        "SELECT ProbeSet.Name, ProbeSet.GeneId \
+         FROM ProbeSet JOIN ProbeSetXRef ON ProbeSetXRef.ProbeSetId = ProbeSet.Id \
+         WHERE ProbeSetXRef.ProbeSetFreezeId = :dataset_id \
+           AND ProbeSet.GeneId IS NOT NULL AND ProbeSet.GeneId <> '' \
+         ORDER BY ProbeSet.Id",
+        mysql::params! { "dataset_id" => dataset_id },
+        |(name, gene_id): (String, String)| (name, gene_id),
+    )
+    .map_err(DbError::from)
+}
+
+/// Tissue values keyed by *symbol*, as `(TissueID, value)` pairs.
+///
+/// GN2 reduces a symbol to one probe -- the one with the largest `Mean` in
+/// `TissueProbeSetXRef` -- and then reads that probe's values.  It keeps them as
+/// a bare list and pairs two lists *by position*, which is only meaningful if
+/// both probes cover the same tissues: on this database they do not.  The
+/// values are keyed by `TissueID` here so a caller can pair them by tissue
+/// rather than by position.
+pub fn get_tissue_values(
+    symbols: &[String],
+) -> Result<std::collections::HashMap<String, Vec<(u16, f64)>>, DbError> {
+    if symbols.is_empty() {
+        return Ok(std::collections::HashMap::new());
+    }
+    let pool = pool()?;
+    let mut conn = pool.get_conn()?;
+    let placeholders = std::iter::repeat("?")
+        .take(symbols.len())
+        .collect::<Vec<_>>()
+        .join(", ");
+    let rows: Vec<(String, u16, f64)> = conn.exec(
+        format!(
+            "SELECT xref.Symbol, data.TissueID, data.value \
+             FROM TissueProbeSetData data \
+             JOIN TissueProbeSetXRef xref ON xref.DataId = data.Id \
+             JOIN (SELECT Symbol, MAX(Mean) AS best_mean FROM TissueProbeSetXRef \
+                   WHERE TissueProbeSetFreezeId = 1 AND Symbol IN ({placeholders}) \
+                   GROUP BY Symbol) best \
+               ON best.Symbol = xref.Symbol AND xref.Mean = best.best_mean \
+             WHERE xref.TissueProbeSetFreezeId = 1 \
+             ORDER BY xref.Symbol, data.TissueID"
+        ),
+        symbols.iter().collect::<Vec<_>>(),
+    )?;
+    let mut out: std::collections::HashMap<String, Vec<(u16, f64)>> =
+        std::collections::HashMap::new();
+    for (symbol, tissue_id, value) in rows {
+        out.entry(symbol.to_lowercase()).or_default().push((tissue_id, value));
+    }
+    Ok(out)
+}
+
+/// Gene ids translated to the mouse id `LCorrRamin3` is keyed on.
+///
+/// GN2's `convert_to_mouse_gene_id`: a mouse id is used as it stands, a rat or
+/// human id is looked up in `GeneIDXRef`.
+pub fn mouse_gene_ids(
+    species: &str,
+    gene_ids: &[String],
+) -> Result<std::collections::HashMap<String, i64>, DbError> {
+    let mut out = std::collections::HashMap::new();
+    if gene_ids.is_empty() {
+        return Ok(out);
+    }
+    let numeric: Vec<(String, i64)> = gene_ids
+        .iter()
+        .filter_map(|g| g.trim().parse::<i64>().ok().map(|v| (g.clone(), v)))
+        .collect();
+    if species.eq_ignore_ascii_case("mouse") {
+        for (raw, value) in numeric {
+            out.insert(raw, value);
+        }
+        return Ok(out);
+    }
+    let column = match species.to_ascii_lowercase().as_str() {
+        "rat" => "rat",
+        "human" => "human",
+        _ => return Ok(out),
+    };
+    let pool = pool()?;
+    let mut conn = pool.get_conn()?;
+    let placeholders = std::iter::repeat("?")
+        .take(numeric.len())
+        .collect::<Vec<_>>()
+        .join(", ");
+    let rows: Vec<(i64, i64)> = conn.exec(
+        format!("SELECT {column}, mouse FROM GeneIDXRef WHERE {column} IN ({placeholders})"),
+        numeric.iter().map(|(_, value)| *value).collect::<Vec<_>>(),
+    )?;
+    let by_source: std::collections::HashMap<i64, i64> = rows.into_iter().collect();
+    for (raw, value) in numeric {
+        if let Some(mouse) = by_source.get(&value) {
+            out.insert(raw, *mouse);
+        }
+    }
+    Ok(out)
+}
+
+/// `LCorrRamin3` values for one reference gene against many targets, in both
+/// directions, preferring GN2's direction (`GeneId1` = target, `GeneId2` =
+/// reference) where both rows exist.
+///
+/// Chunked because a probeset dataset has tens of thousands of gene ids and
+/// MySQL refuses a statement with more than 65 535 placeholders (measured:
+/// "Prepared statement contains too many placeholders" on the first attempt).
+pub fn get_literature_values(
+    reference: i64,
+    targets: &[i64],
+) -> Result<std::collections::HashMap<i64, f64>, DbError> {
+    let mut forward: std::collections::HashMap<i64, f64> = std::collections::HashMap::new();
+    let mut reverse: std::collections::HashMap<i64, f64> = std::collections::HashMap::new();
+    for chunk in targets.chunks(LITERATURE_CHUNK) {
+        let pool = pool()?;
+        let mut conn = pool.get_conn()?;
+        let placeholders = std::iter::repeat("?")
+            .take(chunk.len())
+            .collect::<Vec<_>>()
+            .join(", ");
+        let mut params: Vec<i64> = Vec::with_capacity(chunk.len() * 2 + 2);
+        params.push(reference);
+        params.extend(chunk.iter().copied());
+        params.push(reference);
+        params.extend(chunk.iter().copied());
+        let rows: Vec<(i64, i64, f64)> = conn.exec(
+            format!(
+                "SELECT GeneId1, GeneId2, value FROM LCorrRamin3 \
+                 WHERE (GeneId2 = ? AND GeneId1 IN ({placeholders})) \
+                    OR (GeneId1 = ? AND GeneId2 IN ({placeholders}))"
+            ),
+            params,
+        )?;
+        for (gene1, gene2, value) in rows {
+            if gene2 == reference {
+                forward.insert(gene1, value);
+            } else if gene1 == reference {
+                reverse.insert(gene2, value);
+            }
+        }
+    }
+    for (target, value) in reverse {
+        forward.entry(target).or_insert(value);
+    }
+    Ok(forward)
+}
+
+/// How many genes go into one `IN (...)` clause: MySQL's placeholder ceiling is
+/// 65 535 per statement, and this query uses two lists.
+const LITERATURE_CHUNK: usize = 4_000;
+
 /// Every value of every trait in a probeset dataset, restricted to a set of
 /// individuals: one record per (trait, individual, value).
 ///