about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-10-07 10:42:51 +0000
committerPjotr <wrk@bosa.lan>2026-10-07 10:42:51 +0000
commite912c87deaf220fd5fce1299d669e8fa992b5338 (patch)
tree5a065b3178770291c8f9fda5c88e35d31d47243f /src
parent89c881605a5c94be75f27c2c82cb04cf8bb3b9a8 (diff)
downloadgenenetwork4-e912c87deaf220fd5fce1299d669e8fa992b5338.tar.gz
* src/routes/search.rs (search): add lod, locus, and sort/order.
Search hits gain `lod` (lrs / 4.61) and `locus` (the peak marker name,
looked up in PublishXRef in one batched query; null when the database
is unavailable). `sort=lrs|lod` with `order=asc|desc` ranks hits: gn3
is asked for its first 1000 matches, those are ranked, then `limit`
applies.

* src/db.rs (LRS_PER_LOD, lod, get_publish_loci): add the shared
LRS-to-LOD constant and the locus lookup; TraitInfo and ProbeSetInfo
gain `lod`, computed in SQL from the same constant.

* tests/search.rs, test/python/test_search.py: add the "highest LOD,
locus marker and additive effect for serotonin in BXD male midbrain"
scenario over a recorded production fixture, plus sort/order tests.
* tests/group_trait_info.rs, tests/dataset_probeset_info.rs and their
Python mirrors: assert lod (and locus for trait 17985).
* README.md (Endpoints): document sort, order, lod and locus.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Diffstat (limited to 'src')
-rw-r--r--src/db.rs91
-rw-r--r--src/routes/search.rs116
2 files changed, 193 insertions, 14 deletions
diff --git a/src/db.rs b/src/db.rs
index 10bef16..edc96e0 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -37,6 +37,17 @@ fn pool() -> Result<Pool, mysql::Error> {
     Ok(new_pool)
 }
 
+/// GeneNetwork stores LRS (likelihood ratio statistic); LOD = LRS / 4.61
+/// (4.61 ~ 2 ln 10). Every `lod` the API reports is derived with this one
+/// constant -- in SQL for rows read from the database, via `lod` for
+/// values that arrive as LRS (gn3 search hits).
+pub const LRS_PER_LOD: f64 = 4.61;
+
+/// LOD score for an LRS value; see LRS_PER_LOD.
+pub fn lod(lrs: f64) -> f64 {
+    lrs / LRS_PER_LOD
+}
+
 #[derive(Serialize, utoipa::ToSchema)]
 pub struct Species {
     pub name: String,
@@ -327,6 +338,7 @@ pub struct TraitInfo {
     pub mean: Option<f64>,
     pub locus: Option<String>,
     pub lrs: Option<f64>,
+    pub lod: Option<f64>,
     pub additive: Option<f64>,
     pub nsamples: Option<i32>,
     pub pre_publication_description: Option<String>,
@@ -353,9 +365,11 @@ pub fn get_group_trait_info(
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_first(
-        "SELECT PublishXRef.Id AS Id, PublishXRef.PhenotypeId AS PhenotypeId, \
+        format!(
+            "SELECT PublishXRef.Id AS Id, PublishXRef.PhenotypeId AS PhenotypeId, \
                 PublishXRef.PublicationId AS PublicationId, PublishXRef.mean AS Mean, \
                 PublishXRef.Locus AS Locus, PublishXRef.LRS AS Lrs, \
+                PublishXRef.LRS / {LRS_PER_LOD} AS Lod, \
                 PublishXRef.additive AS Additive, PublishXRef.NSamples AS Nsamples, \
                 Phenotype.Pre_publication_description AS PrePublicationDescription, \
                 Phenotype.Post_publication_description AS PostPublicationDescription, \
@@ -368,7 +382,8 @@ pub fn get_group_trait_info(
          FROM PublishXRef \
          LEFT JOIN Phenotype ON Phenotype.Id = PublishXRef.PhenotypeId \
          LEFT JOIN Publication ON Publication.Id = PublishXRef.PublicationId \
-         WHERE PublishXRef.InbredSetId = :group_id AND PublishXRef.Id = :trait_id",
+         WHERE PublishXRef.InbredSetId = :group_id AND PublishXRef.Id = :trait_id"
+        ),
         mysql::params! { "group_id" => group_id, "trait_id" => trait_id },
     )
 }
@@ -379,9 +394,11 @@ pub fn get_group_traits(group_id: u16) -> Result<Vec<TraitInfo>, mysql::Error> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec(
-        "SELECT PublishXRef.Id AS Id, PublishXRef.PhenotypeId AS PhenotypeId, \
+        format!(
+            "SELECT PublishXRef.Id AS Id, PublishXRef.PhenotypeId AS PhenotypeId, \
                 PublishXRef.PublicationId AS PublicationId, PublishXRef.mean AS Mean, \
                 PublishXRef.Locus AS Locus, PublishXRef.LRS AS Lrs, \
+                PublishXRef.LRS / {LRS_PER_LOD} AS Lod, \
                 PublishXRef.additive AS Additive, PublishXRef.NSamples AS Nsamples, \
                 Phenotype.Pre_publication_description AS PrePublicationDescription, \
                 Phenotype.Post_publication_description AS PostPublicationDescription, \
@@ -395,11 +412,39 @@ pub fn get_group_traits(group_id: u16) -> Result<Vec<TraitInfo>, mysql::Error> {
          LEFT JOIN Phenotype ON Phenotype.Id = PublishXRef.PhenotypeId \
          LEFT JOIN Publication ON Publication.Id = PublishXRef.PublicationId \
          WHERE PublishXRef.InbredSetId = :group_id \
-         ORDER BY PublishXRef.Id",
+         ORDER BY PublishXRef.Id"
+        ),
         mysql::params! { "group_id" => group_id },
     )
 }
 
+/// Peak marker names for published traits, keyed by (dataset name,
+/// PublishXRef.Id), in one query. Traits with no recorded Locus are
+/// absent from the result.
+pub fn get_publish_loci(
+    keys: &[(String, u32)],
+) -> Result<std::collections::HashMap<(String, u32), String>, mysql::Error> {
+    let pool = pool()?;
+    let mut conn = pool.get_conn()?;
+    let pairs = vec!["(?, ?)"; keys.len()].join(", ");
+    let rows: Vec<(String, u32, String)> = conn.exec(
+        format!(
+            "SELECT PublishFreeze.Name, PublishXRef.Id, PublishXRef.Locus \
+             FROM PublishXRef \
+             JOIN PublishFreeze ON PublishFreeze.InbredSetId = PublishXRef.InbredSetId \
+             WHERE PublishXRef.Locus IS NOT NULL \
+               AND (PublishFreeze.Name, PublishXRef.Id) IN ({pairs})"
+        ),
+        keys.iter()
+            .flat_map(|(dataset, id)| [mysql::Value::from(dataset), mysql::Value::from(*id)])
+            .collect::<Vec<_>>(),
+    )?;
+    Ok(rows
+        .into_iter()
+        .map(|(dataset, id, locus)| ((dataset, id), locus))
+        .collect())
+}
+
 /// One expression (ProbeSet) dataset: a ProbeSetFreeze row, matching
 /// the shape of GeneNetwork2's GET /api/v_pre1/datasets/<group_name>
 /// response (field names there: Id, ProbeFreezeId, AvgID,
@@ -754,6 +799,7 @@ pub struct ProbeSetInfo {
     pub mean: Option<f64>,
     pub locus: Option<String>,
     pub lrs: Option<f64>,
+    pub lod: Option<f64>,
     pub p_value: Option<f64>,
     pub additive: Option<f64>,
 }
@@ -771,6 +817,7 @@ type ProbeSetInfoRow = (
     Option<f64>,
     Option<f64>,
     Option<f64>,
+    Option<f64>,
 );
 
 /// Fetch one expression trait's metadata (see ProbeSetInfo) within a
@@ -785,12 +832,15 @@ pub fn get_dataset_probeset_info(
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_first(
-        "SELECT ProbeSet.Id, ProbeSet.Name, ProbeSet.Symbol, ProbeSet.description, \
+        format!(
+            "SELECT ProbeSet.Id, ProbeSet.Name, ProbeSet.Symbol, ProbeSet.description, \
                 ProbeSet.Chr, ProbeSet.Mb, ProbeSetXRef.mean, ProbeSetXRef.Locus, \
-                ProbeSetXRef.LRS, ProbeSetXRef.pValue, ProbeSetXRef.additive \
+                ProbeSetXRef.LRS, ProbeSetXRef.LRS / {LRS_PER_LOD}, ProbeSetXRef.pValue, \
+                ProbeSetXRef.additive \
          FROM ProbeSet \
          JOIN ProbeSetXRef ON ProbeSetXRef.ProbeSetId = ProbeSet.Id \
-         WHERE ProbeSetXRef.ProbeSetFreezeId = :dataset_id AND ProbeSet.Name = :probeset_name",
+         WHERE ProbeSetXRef.ProbeSetFreezeId = :dataset_id AND ProbeSet.Name = :probeset_name"
+        ),
         mysql::params! { "dataset_id" => dataset_id, "probeset_name" => probeset_name },
     )
     .map(|row: Option<ProbeSetInfoRow>| {
@@ -805,6 +855,7 @@ pub fn get_dataset_probeset_info(
                 mean,
                 locus,
                 lrs,
+                lod,
                 p_value,
                 additive,
             )| {
@@ -818,6 +869,7 @@ pub fn get_dataset_probeset_info(
                     mean,
                     locus,
                     lrs,
+                    lod,
                     p_value,
                     additive,
                 }
@@ -833,15 +885,31 @@ pub fn get_dataset_probesets(dataset_id: u16) -> Result<Vec<ProbeSetInfo>, mysql
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_map(
-        "SELECT ProbeSet.Id, ProbeSet.Name, ProbeSet.Symbol, ProbeSet.description, \
+        format!(
+            "SELECT ProbeSet.Id, ProbeSet.Name, ProbeSet.Symbol, ProbeSet.description, \
                 ProbeSet.Chr, ProbeSet.Mb, ProbeSetXRef.mean, ProbeSetXRef.Locus, \
-                ProbeSetXRef.LRS, ProbeSetXRef.pValue, ProbeSetXRef.additive \
+                ProbeSetXRef.LRS, ProbeSetXRef.LRS / {LRS_PER_LOD}, ProbeSetXRef.pValue, \
+                ProbeSetXRef.additive \
          FROM ProbeSet \
          JOIN ProbeSetXRef ON ProbeSetXRef.ProbeSetId = ProbeSet.Id \
          WHERE ProbeSetXRef.ProbeSetFreezeId = :dataset_id \
-         ORDER BY ProbeSet.Id",
+         ORDER BY ProbeSet.Id"
+        ),
         mysql::params! { "dataset_id" => dataset_id },
-        |(probeset_id, name, symbol, description, chr, mb, mean, locus, lrs, p_value, additive)| {
+        |(
+            probeset_id,
+            name,
+            symbol,
+            description,
+            chr,
+            mb,
+            mean,
+            locus,
+            lrs,
+            lod,
+            p_value,
+            additive,
+        )| {
             ProbeSetInfo {
                 probeset_id,
                 name,
@@ -852,6 +920,7 @@ pub fn get_dataset_probesets(dataset_id: u16) -> Result<Vec<ProbeSetInfo>, mysql
                 mean,
                 locus,
                 lrs,
+                lod,
                 p_value,
                 additive,
             }
diff --git a/src/routes/search.rs b/src/routes/search.rs
index 0a61878..78e3b7c 100644
--- a/src/routes/search.rs
+++ b/src/routes/search.rs
@@ -3,17 +3,21 @@
 //! Phase A (gn4-api-foundation.gmi "Pilot: search"): proxies gn3's
 //! /api/search (xapian-backed) and re-wraps the hits in the
 //! descriptive envelope. gn3's hit objects pass through untouched;
-//! gn4 contributes boundary validation and the contract.
+//! gn4 contributes boundary validation and the contract, plus three
+//! additions gn3's hits lack: `lod` (derived from `lrs`), `locus` (the
+//! peak marker's name, looked up in PublishXRef) and `sort`/`order`.
 
 use axum::Json;
 use axum::extract::{Extension, Query};
 use axum::http::StatusCode;
 use serde::Deserialize;
+use std::collections::HashMap;
 use std::sync::OnceLock;
 use std::time::Duration;
 use tower_http::request_id::RequestId;
 
 use crate::auth::AuthToken;
+use crate::db;
 use crate::error::{ApiError, Unauthorized};
 use crate::request_id_string;
 use crate::response::Envelope;
@@ -48,8 +52,18 @@ pub struct SearchParams {
     pub r#type: Option<String>,
     /// Maximum hits to return (default 20, capped at 100).
     pub limit: Option<u64>,
+    /// Rank hits by "lrs" or "lod" (the same order) instead of
+    /// relevance; hits without a value come last. The ranking covers
+    /// the first 1000 relevance-ranked matches, then `limit` applies.
+    pub sort: Option<String>,
+    /// "desc" (default) or "asc"; only meaningful with `sort`.
+    pub order: Option<String>,
 }
 
+/// With `sort`, gn3 is asked for this many hits (not just `limit`) so
+/// the ranking spans more than one page of relevance-ordered results.
+const SORT_FETCH_LIMIT: u64 = 1000;
+
 /// One search hit, in gn3's shape.
 ///
 /// Every field is optional because gn3 omits computed values (`lrs`,
@@ -69,6 +83,12 @@ pub struct SearchHit {
     pub mean: Option<f64>,
     pub additive: Option<f64>,
     pub lrs: Option<f64>,
+    /// LOD score, LRS / 4.61; computed here from `lrs`.
+    pub lod: Option<f64>,
+    /// Name of the peak marker (a Geno.Name such as "rsm10000012461"),
+    /// looked up in PublishXRef for phenotype hits; null for other
+    /// hits, or when the database is unavailable.
+    pub locus: Option<String>,
     pub geno_chr: Option<String>,
     pub geno_mb: Option<f64>,
     pub inbredsetcode: Option<String>,
@@ -77,6 +97,47 @@ pub struct SearchHit {
     pub extra: std::collections::BTreeMap<String, serde_json::Value>,
 }
 
+/// Orders hits by `lrs` (which orders LOD identically), descending
+/// unless `ascending`; hits with no `lrs` always come last.
+fn sort_by_lrs(hits: &mut [SearchHit], ascending: bool) {
+    hits.sort_by(|a, b| match (a.lrs, b.lrs) {
+        (Some(x), Some(y)) if ascending => x.total_cmp(&y),
+        (Some(x), Some(y)) => y.total_cmp(&x),
+        (Some(_), None) => std::cmp::Ordering::Less,
+        (None, Some(_)) => std::cmp::Ordering::Greater,
+        (None, None) => std::cmp::Ordering::Equal,
+    });
+}
+
+/// Fills in `locus` for phenotype hits from one PublishXRef lookup.
+/// A database failure leaves `locus` null rather than failing the
+/// search: the hits are still correct, and the marker is also on
+/// GET /traits/{dataset}/{trait}.
+async fn add_loci(hits: &mut [SearchHit]) {
+    let keys: Vec<(String, u32)> = hits
+        .iter()
+        .filter_map(|hit| {
+            let dataset = hit.dataset.as_deref().filter(|d| d.ends_with("Publish"))?;
+            Some((dataset.to_string(), hit.name.as_deref()?.parse().ok()?))
+        })
+        .collect();
+    if keys.is_empty() {
+        return;
+    }
+    let loci: HashMap<(String, u32), String> =
+        match tokio::task::spawn_blocking(move || db::get_publish_loci(&keys)).await {
+            Ok(Ok(loci)) => loci,
+            _ => return,
+        };
+    for hit in hits {
+        let key = (
+            hit.dataset.clone().unwrap_or_default(),
+            hit.name.as_deref().and_then(|n| n.parse().ok()).unwrap_or(0),
+        );
+        hit.locus = loci.get(&key).cloned();
+    }
+}
+
 /// gn3's error body for rejected queries: {"error": "<diagnostic>",
 /// "error_type": "..."}. The diagnostic lives under "error";
 /// "error_type" leaks Python reprs (e.g. "b'QueryParserError'"), so
@@ -124,6 +185,19 @@ pub async fn search(
         ));
     }
     let limit = params.limit.unwrap_or(20).min(100);
+    if !matches!(params.sort.as_deref(), None | Some("lrs") | Some("lod")) {
+        return Err(bad_request("sort must be \"lrs\" or \"lod\""));
+    }
+    let ascending = match params.order.as_deref() {
+        None | Some("desc") => false,
+        Some("asc") => true,
+        Some(_) => return Err(bad_request("order must be \"asc\" or \"desc\"")),
+    };
+    let fetch_limit = if params.sort.is_some() {
+        SORT_FETCH_LIMIT
+    } else {
+        limit
+    };
 
     // Every gn3-side failure maps to one 502 shape; the caller can tell
     // connectivity, protocol, and backend errors apart by `code`.
@@ -144,7 +218,7 @@ pub async fn search(
         [
             ("query", q),
             ("type", search_type),
-            ("per_page", &limit.to_string()),
+            ("per_page", &fetch_limit.to_string()),
         ],
     )
     .map_err(|e| {
@@ -198,8 +272,44 @@ pub async fn search(
         ));
     }
 
-    let hits: Vec<SearchHit> = serde_json::from_str(&body)
+    let mut hits: Vec<SearchHit> = serde_json::from_str(&body)
         .map_err(|e| backend_error("backend_misbehaving", e.to_string()))?;
+    for hit in &mut hits {
+        hit.lod = hit.lrs.map(db::lod);
+    }
+    if params.sort.is_some() {
+        sort_by_lrs(&mut hits, ascending);
+    }
+    hits.truncate(limit as usize);
+    add_loci(&mut hits).await;
 
     Ok(Json(Envelope::of(hits)))
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use serde_json::json;
+
+    fn hit(lrs: Option<f64>) -> SearchHit {
+        serde_json::from_value(json!({ "lrs": lrs })).unwrap()
+    }
+
+    fn lrs_of(hits: &[SearchHit]) -> Vec<Option<f64>> {
+        hits.iter().map(|h| h.lrs).collect()
+    }
+
+    #[test]
+    fn sort_by_lrs_descending_puts_missing_values_last() {
+        let mut hits = vec![hit(Some(2.0)), hit(None), hit(Some(9.0)), hit(Some(5.0))];
+        sort_by_lrs(&mut hits, false);
+        assert_eq!(lrs_of(&hits), [Some(9.0), Some(5.0), Some(2.0), None]);
+    }
+
+    #[test]
+    fn sort_by_lrs_ascending_still_puts_missing_values_last() {
+        let mut hits = vec![hit(Some(2.0)), hit(None), hit(Some(9.0)), hit(Some(5.0))];
+        sort_by_lrs(&mut hits, true);
+        assert_eq!(lrs_of(&hits), [Some(2.0), Some(5.0), Some(9.0), None]);
+    }
+}