about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-10-05 15:25:22 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-10-07 08:26:56 +0200
commit7631cf515ffe1a81424aa53ab7052a61a3ff2b4d (patch)
tree9a02a521de26b54da79c5e7c1b86af4d343b2e66 /src
parent15a5c8abeb73584eeae6cae1d92176da42fa6bc3 (diff)
downloadgenenetwork4-7631cf515ffe1a81424aa53ab7052a61a3ff2b4d.tar.gz
Add GET /groups/{group}/case-attributes
Per-strain metadata beyond genotype/phenotype data (age, sex,
treatment, etc.), backed by MariaDB CaseAttribute/CaseAttributeXRefNew.
Combines GeneNetwork3's separate /case-attribute/{id}/names and
/case-attribute/{id}/values (gn3.api.case_attributes) into one
response -- neither list is large enough on its own to need splitting.
This is the only one of GeneNetwork2/3/gn-guile with the concept at
all: GeneNetwork2 delegates to GeneNetwork3 rather than storing case
attributes itself, and gn-guile doesn't have it.

db::get_group_case_attributes returns {names: [...], values: [{strain,
case_attributes: {...}}]}; values is built by folding adjacent
(strain, attribute, value) rows (ordered by strain name) rather than
grouping afterwards, since SQL already guarantees the adjacency.

Found and fixed a real bug while verifying this live: GeneNetwork3's
own query joins CaseAttribute to CaseAttributeXRefNew on
CaseAttributeId alone, but CaseAttributeId is not unique across groups
-- it's a shared vocabulary (id 37 means "Epoch" for dozens of
unrelated groups simultaneously); the actual key is
(InbredSetId, CaseAttributeId). Confirmed against this database:
without also joining on InbredSetId, BXD's result included a spurious
"Strain": "Live" attribute belonging to a different, unrelated group.
Fixed on genenetwork4's side by adding the missing join condition.

A group with no case attributes defined returns 200 with both lists
empty, not a 404 (the group itself exists) -- verified against LXS,
a real group with zero CaseAttribute rows.

tests/group_case_attributes.rs and its Python mirror cover BXD's 4
real attributes (asserting each strain has exactly those 4, not more,
to catch the join bug above), the empty-group case, missing token, and
unknown group.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XDDpXvZBQat9uSgDeEMJ8d
Diffstat (limited to 'src')
-rw-r--r--src/db.rs98
-rw-r--r--src/lib.rs1
-rw-r--r--src/routes/groups.rs56
3 files changed, 155 insertions, 0 deletions
diff --git a/src/db.rs b/src/db.rs
index afc8f82..10bef16 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -466,6 +466,104 @@ pub fn get_group_datasets(group_id: u16) -> Result<Vec<Dataset>, mysql::Error> {
     )
 }
 
+/// One strain's case-attribute values within a group: extra per-strain
+/// metadata (e.g. age, sex, treatment) beyond genotype/phenotype data,
+/// matching GeneNetwork3's gn3.api.case_attributes (genenetwork4's own
+/// read-only equivalent of its /case-attribute/{id}/values -- the only
+/// place this concept exists; neither GeneNetwork2 nor gn-guile expose
+/// it). Keyed by attribute name rather than a fixed field set, since
+/// which attributes exist is itself per-group data (see CaseAttribute
+/// below).
+#[derive(Serialize, utoipa::ToSchema)]
+pub struct StrainCaseAttributes {
+    pub strain: String,
+    pub case_attributes: std::collections::HashMap<String, String>,
+}
+
+/// A group's case attributes: every attribute name defined for it
+/// (`CaseAttribute.Name`) and, for each strain that has at least one
+/// value set, that strain's values -- combined into one response
+/// rather than GN3's separate .../names and .../values endpoints,
+/// since neither list is large enough on its own to need splitting.
+#[derive(Serialize, utoipa::ToSchema)]
+pub struct CaseAttributes {
+    pub names: Vec<String>,
+    pub values: Vec<StrainCaseAttributes>,
+}
+
+/// Fetch every case-attribute name defined for a group, matching
+/// GeneNetwork3's gn3.api.case_attributes.__case_attribute_labels_by_inbred_set__
+/// (trimmed to just the name -- Description isn't used by genenetwork4
+/// yet, and CaseAttributeId/InbredSetId are already implied by this
+/// being scoped to one group).
+fn get_group_case_attribute_names(group_id: u16) -> Result<Vec<String>, mysql::Error> {
+    let pool = pool()?;
+    let mut conn = pool.get_conn()?;
+    conn.exec(
+        "SELECT Name FROM CaseAttribute WHERE InbredSetId = :group_id ORDER BY Name",
+        mysql::params! { "group_id" => group_id },
+    )
+}
+
+/// Fetch every strain's case-attribute values for a group, based on
+/// GeneNetwork3's gn3.api.case_attributes.__case_attribute_values_by_inbred_set__,
+/// fixed to also join on InbredSetId: `CaseAttributeId` alone is not
+/// unique across groups (it's a shared vocabulary -- e.g. id 37 means
+/// "Epoch" for dozens of unrelated groups at once; the table's real
+/// key is the pair `(InbredSetId, CaseAttributeId)`), so GN3's version
+/// of this join -- `ON ca.CaseAttributeId=caxrn.CaseAttributeId`,
+/// `WHERE caxrn.InbredSetId=...` with no matching condition on `ca`'s
+/// own InbredSetId -- pulls in every other group's attribute that
+/// happens to share a `CaseAttributeId` number, not just this group's.
+/// Confirmed against this database: without the extra join condition
+/// below, BXD's (group 1) result included a spurious "Strain" = "Live"
+/// attribute that belongs to a different, unrelated group entirely.
+/// Rows come back one (strain, attribute, value) triple at a time,
+/// ordered by strain name, so adjacent rows for the same strain are
+/// folded into one `StrainCaseAttributes` as they're read rather than
+/// grouped afterwards.
+fn get_group_case_attribute_values(group_id: u16) -> Result<Vec<StrainCaseAttributes>, mysql::Error> {
+    let pool = pool()?;
+    let mut conn = pool.get_conn()?;
+    let rows: Vec<(String, String, String)> = conn.exec(
+        "SELECT s.Name, ca.Name, caxrn.Value \
+         FROM CaseAttribute AS ca \
+         JOIN CaseAttributeXRefNew AS caxrn \
+                ON ca.CaseAttributeId = caxrn.CaseAttributeId \
+                AND ca.InbredSetId = caxrn.InbredSetId \
+         JOIN Strain AS s ON caxrn.StrainId = s.Id \
+         WHERE caxrn.InbredSetId = :group_id \
+         ORDER BY s.Name",
+        mysql::params! { "group_id" => group_id },
+    )?;
+    let mut values: Vec<StrainCaseAttributes> = Vec::new();
+    for (strain, attribute_name, attribute_value) in rows {
+        match values.last_mut() {
+            Some(last) if last.strain == strain => {
+                last.case_attributes.insert(attribute_name, attribute_value);
+            }
+            _ => {
+                let mut case_attributes = std::collections::HashMap::new();
+                case_attributes.insert(attribute_name, attribute_value);
+                values.push(StrainCaseAttributes {
+                    strain,
+                    case_attributes,
+                });
+            }
+        }
+    }
+    Ok(values)
+}
+
+/// Fetch a group's case attributes: every attribute name defined for
+/// it, and every strain's values for them. See `CaseAttributes`.
+pub fn get_group_case_attributes(group_id: u16) -> Result<CaseAttributes, mysql::Error> {
+    Ok(CaseAttributes {
+        names: get_group_case_attribute_names(group_id)?,
+        values: get_group_case_attribute_values(group_id)?,
+    })
+}
+
 /// Fetch the expression datasets belonging to a species (across all of
 /// its groups), the species-scoped equivalent of get_group_datasets.
 /// GeneNetwork2's own species-scoped variant of
diff --git a/src/lib.rs b/src/lib.rs
index f524429..46c4211 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -63,6 +63,7 @@ pub fn app() -> Router {
         .routes(routes!(routes::groups::group_trait_info))
         .routes(routes!(routes::groups::group_traits))
         .routes(routes!(routes::groups::group_datasets))
+        .routes(routes!(routes::groups::group_case_attributes))
         .routes(routes!(routes::datasets::dataset_by_name))
         .routes(routes!(routes::datasets::dataset_probesets))
         .routes(routes!(routes::datasets::dataset_probeset_info))
diff --git a/src/routes/groups.rs b/src/routes/groups.rs
index 51f12cc..12652ec 100644
--- a/src/routes/groups.rs
+++ b/src/routes/groups.rs
@@ -376,6 +376,62 @@ pub async fn group_traits(
     })
 }
 
+#[utoipa::path(get, path = "/groups/{group}/case-attributes", summary = "Get a group's case attributes: defined attribute names and every strain's values", params(
+    ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id")
+), responses(
+    (status = 200, description = "The group's case-attribute names and per-strain values", body = db::CaseAttributes),
+    Unauthorized,
+    (status = 404, description = "No matching group", body = ApiError),
+    (status = 500, description = "Database error", body = ApiError)
+))]
+pub async fn group_case_attributes(
+    Extension(request_id): Extension<RequestId>,
+    Path(group): Path<String>,
+    _token: AuthToken,
+) -> Result<Json<db::CaseAttributes>, ApiError> {
+    let rid = request_id_string(&request_id);
+    let not_found_name = group.clone();
+    tokio::task::spawn_blocking(move || {
+        db::get_group_by_name(&group).and_then(|group| match group {
+            Some(group) => db::get_group_case_attributes(group.id).map(Some),
+            None => Ok(None),
+        })
+    })
+    .await
+    .map_err(|e| {
+        ApiError::new(
+            StatusCode::INTERNAL_SERVER_ERROR,
+            "internal_error",
+            "Internal error",
+            e.to_string(),
+            "group_case_attributes",
+        )
+        .with_request_id(rid.clone())
+    })?
+    .map_err(|e| {
+        ApiError::new(
+            StatusCode::INTERNAL_SERVER_ERROR,
+            "database_error",
+            "Database error",
+            e.to_string(),
+            "group_case_attributes",
+        )
+        .with_request_id(rid.clone())
+    })?
+    .map(Json)
+    .ok_or_else(|| {
+        ApiError::new(
+            StatusCode::NOT_FOUND,
+            "group_not_found",
+            "Group not found",
+            format!("No group matching '{not_found_name}'."),
+            "group_case_attributes",
+        )
+        .with_request_id(rid)
+        .with_next("/groups")
+    })
+}
+
 #[utoipa::path(get, path = "/groups/{group}/datasets", summary = "List the expression (ProbeSet) datasets belonging to a group", params(
     ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id")
 ), responses(