about summary refs log tree commit diff
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-11-22 18:45:52 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-11-22 18:45:52 +0000
commitb223757bb5c04d03be5ccccf32488594134bb542 (patch)
treeab134383ab2dfe73878b0b785708a79e6195177b
parent3854e38fd8c4521df1f501dd6b093fe8b27a840a (diff)
downloadgenenetwork4-b223757bb5c04d03be5ccccf32488594134bb542.tar.gz
rqtl: the rows are `data`, and the permutation null is meta.permutation
Every compute endpoint kept its rows in `data` except this one, which put them
under `data.markers` beside `data.permutation`.  A script written from SKILL.md
("rows are positional") broke on the first scan it read, and the same script had
to special-case both shapes -- measured in Rob Williams's test drive of the
release service.

`data` is now the marker array (positional, `meta.columns` names the columns,
as /compute/gemma and /compute/qtl2 already did), and the permutation null goes
to `meta.permutation`, where Meta's own documentation says endpoint-specific
qualifier information belongs.  /plot/rqtl and scripts/plot-rqtl.py accept both
shapes, so a saved reply from an older build still plots.
-rw-r--r--scripts/plot-rqtl.py9
-rw-r--r--src/response.rs9
-rw-r--r--src/routes/plot.rs13
-rw-r--r--src/routes/rqtl.rs12
-rw-r--r--src/rqtl.rs65
-rw-r--r--tests/genoupload.rs5
-rw-r--r--tests/links.rs4
-rw-r--r--tests/peakgenotypes.rs4
-rw-r--r--tests/rqtl.rs13
9 files changed, 84 insertions, 50 deletions
diff --git a/scripts/plot-rqtl.py b/scripts/plot-rqtl.py
index 73d8c51..b24a14f 100644
--- a/scripts/plot-rqtl.py
+++ b/scripts/plot-rqtl.py
@@ -28,8 +28,13 @@ def main():
     if "data" not in doc:
         sys.exit(f"{a.result}: no 'data' member (error response?): {str(doc)[:200]}")
     res = doc["data"]
-    rows = res["markers"]            # [name, chr, pos_mb, lod]
-    perm = res.get("permutation")
+    # `data` is the marker array itself (a reply from before that change kept
+    # it under `data.markers`), and the permutation null sits beside it in
+    # meta; older replies carried it inside data.
+    rows = res if isinstance(res, list) else res["markers"]
+    perm = (doc.get("meta") or {}).get("permutation") or (
+        res.get("permutation") if isinstance(res, dict) else None
+    )
     thr = []                          # (value, label, dash)
     if perm:
         thr = [(perm["significant"], "significant (95%)", "7 4"),
diff --git a/src/response.rs b/src/response.rs
index c2a6cc9..974a585 100644
--- a/src/response.rs
+++ b/src/response.rs
@@ -279,6 +279,15 @@ impl<T: Serialize + utoipa::ToSchema> Envelope<T> {
         self
     }
 
+    /// Puts one endpoint-specific value into `meta.extra` (qualified data that
+    /// belongs beside the rows rather than around them -- the permutation null
+    /// of a scan, say).
+    pub fn with_extra(mut self, key: &str, value: serde_json::Value) -> Self {
+        let extra = self.meta.extra.get_or_insert_with(serde_json::Map::new);
+        extra.insert(key.to_string(), value);
+        self
+    }
+
     /// Attaches [`Timing`] to `meta`.
     pub fn with_timing(mut self, timing: Timing) -> Self {
         self.meta.timing = Some(timing);
diff --git a/src/routes/plot.rs b/src/routes/plot.rs
index d33f5d7..0f698be 100644
--- a/src/routes/plot.rs
+++ b/src/routes/plot.rs
@@ -158,11 +158,16 @@ fn check_gemma_result(posted: &serde_json::Value) -> Result<(), String> {
 /// What `/plot/rqtl` validates in a posted R/qtl result: `data.markers`,
 /// each row `[name, chr, pos, lod, ...]`.
 fn check_rqtl_result(result: &serde_json::Value) -> Result<(), String> {
-    let rows = result["data"]["markers"]
-        .as_array()
-        .ok_or("`data.markers` must be the R/qtl marker array from /compute/rqtl -- post that response back, not a request")?;
+    // `data` is the marker array; a reply from a build before that change kept
+    // it under `data.markers`, and a caller may still be holding one.
+    let rows = if result["data"].is_array() {
+        result["data"].as_array()
+    } else {
+        result["data"]["markers"].as_array()
+    }
+    .ok_or("`data` must be the R/qtl marker array from /compute/rqtl -- post that response back, not a request")?;
     if rows.is_empty() {
-        return Err("`data.markers` is empty: nothing to plot".to_string());
+        return Err("`data` is empty: nothing to plot".to_string());
     }
     let first = rows[0]
         .as_array()
diff --git a/src/routes/rqtl.rs b/src/routes/rqtl.rs
index 84c43e2..0fbfdf4 100644
--- a/src/routes/rqtl.rs
+++ b/src/routes/rqtl.rs
@@ -546,11 +546,16 @@ pub async fn compute_rqtl(
         // responses from the same panel apart, and `/plot/rqtl` reads it
         // for the title.
         let mut envelope = ctx
-            .envelope(rqtl::to_json(output))
+            // `data` is the marker rows, like every other compute endpoint:
+            // the permutation null is qualifier information and goes to
+            // meta.extra, so a caller can write one script for all of them
+            // (measured: Rob Williams's test-drive read data.markers here and
+            // data itself on GEMMA, and had to special-case both).
+            .envelope(rqtl::marker_rows(&output))
             .with_columns(rqtl::MARKER_COLUMNS.iter().map(|s| s.to_string()).collect(), num_rows)
             .with_note(&format!("Trait: {}", request.trait_name))
             .with_note(
-                "markers come from R/qtl's scanone output, positional (see meta.columns for names); permutation is null unless nperm > 0 was requested.",
+                "markers come from R/qtl's scanone output, positional (see meta.columns for names); the permutation null, when nperm > 0 was requested, is meta.permutation.",
             )
             // The conversion is not silent in the status log, but it was
             // silent here: every heterozygous call is dropped and X becomes an
@@ -562,6 +567,9 @@ pub async fn compute_rqtl(
                  panel with heterozygotes at 0.5, so the two are different models, not two \
                  implementations of one.",
             );
+        if let Some(permutation) = rqtl::permutation_json(&output) {
+            envelope = envelope.with_extra("permutation", permutation);
+        }
         for note in &notes {
             envelope = envelope.with_note(note);
         }
diff --git a/src/rqtl.rs b/src/rqtl.rs
index 2bf6de3..7dd608d 100644
--- a/src/rqtl.rs
+++ b/src/rqtl.rs
@@ -495,32 +495,39 @@ pub const MARKER_COLUMNS: [&str; 4] = ["name", "chr", "pos", "lod"];
 /// is what utoipa needs here. `markers` rows are positional (see
 /// `MARKER_COLUMNS`), the same space-saving shape `crate::gemma::compute`
 /// uses for its own (much larger) marker rows.
-pub fn to_json(output: RqtlOutput) -> Value {
-    let markers: Vec<Value> = output
-        .markers
-        .into_iter()
-        .map(|m| {
-            let mut row = vec![
-                Value::String(m.name),
-                Value::String(m.chr),
-                serde_json::json!(m.pos),
-                serde_json::json!(m.lod),
-            ];
-            row.extend(m.extra.into_iter().map(Value::String));
-            Value::Array(row)
-        })
-        .collect();
-    serde_json::json!({
-        "markers": markers,
-        "permutation": output.permutation,
-    })
+pub fn marker_rows(output: &RqtlOutput) -> Value {
+    Value::Array(
+        output
+            .markers
+            .iter()
+            .map(|m| {
+                let mut row = vec![
+                    Value::String(m.name.clone()),
+                    Value::String(m.chr.clone()),
+                    serde_json::json!(m.pos),
+                    serde_json::json!(m.lod),
+                ];
+                row.extend(m.extra.iter().cloned().map(Value::String));
+                Value::Array(row)
+            })
+            .collect(),
+    )
+}
+
+/// The permutation null, for `meta.extra` beside the rows -- it qualifies the
+/// scan rather than being one of its rows, which is why it is not in `data`
+/// (that is where every other compute endpoint keeps its rows).
+pub fn permutation_json(output: &RqtlOutput) -> Option<Value> {
+    output
+        .permutation
+        .as_ref()
+        .and_then(|permutation| serde_json::to_value(permutation).ok())
 }
 
 /// The marker with the strongest LOD in a `to_json` result, if there is
 /// one: the QTL's peak, which is what a PheWAS wants to be centred on.
 pub fn peak_marker(data: &Value) -> Option<String> {
-    data.get("markers")?
-        .as_array()?
+    data.as_array()?
         .iter()
         .filter_map(|row| {
             let row = row.as_array()?;
@@ -661,16 +668,14 @@ mod tests {
 
     #[test]
     fn the_peak_marker_is_the_strongest_lod() {
-        let data = serde_json::json!({
-            "markers": [
-                ["rs1", "1", 3.0, 0.5],
-                ["rs2", "3", 9.0, 4.2],
-                ["rs3", "5", 12.0, 1.1]
-            ],
-            "permutation": null
-        });
+        // `data` is the rows themselves; the permutation null is in meta.
+        let data = serde_json::json!([
+            ["rs1", "1", 3.0, 0.5],
+            ["rs2", "3", 9.0, 4.2],
+            ["rs3", "5", 12.0, 1.1]
+        ]);
         assert_eq!(peak_marker(&data).as_deref(), Some("rs2"));
-        assert_eq!(peak_marker(&serde_json::json!({"markers": []})), None);
+        assert_eq!(peak_marker(&serde_json::json!([])), None);
         assert_eq!(peak_marker(&serde_json::json!({})), None);
     }
 
diff --git a/tests/genoupload.rs b/tests/genoupload.rs
index 9f8a8a5..4797376 100644
--- a/tests/genoupload.rs
+++ b/tests/genoupload.rs
@@ -335,9 +335,8 @@ async fn every_engine_maps_an_uploaded_genotype() {
         let bytes = response.into_body().collect().await.unwrap().to_bytes();
         assert_eq!(status, StatusCode::OK, "{endpoint}: {}", String::from_utf8_lossy(&bytes));
         let envelope: Value = serde_json::from_slice(&bytes).unwrap();
-        // /compute/rqtl wraps its rows in data.markers; /compute/qtl2 returns
-        // them as the array itself.
-        let rows = envelope["data"]["markers"]
+        // Both /compute/rqtl and /compute/qtl2 return their rows as `data`.
+        let rows = envelope["data"]
             .as_array()
             .or_else(|| envelope["data"].as_array())
             .unwrap_or_else(|| panic!("{endpoint}: no rows in {envelope}"));
diff --git a/tests/links.rs b/tests/links.rs
index 5291008..d36e5a7 100644
--- a/tests/links.rs
+++ b/tests/links.rs
@@ -221,8 +221,8 @@ async fn a_scan_points_at_the_class_counts_behind_its_peak() {
         "the trait id is the caller's to fill in: {hint}"
     );
     // And the marker it names is the peak the reply reported.
-    // /compute/rqtl's rows live under data.markers.
-    let rows = envelope["data"]["markers"].as_array().unwrap();
+    // /compute/rqtl's rows are `data` itself, like every compute endpoint's.
+    let rows = envelope["data"].as_array().unwrap();
     let peak = rows
         .iter()
         .max_by(|left, right| {
diff --git a/tests/peakgenotypes.rs b/tests/peakgenotypes.rs
index 56461f8..132cfca 100644
--- a/tests/peakgenotypes.rs
+++ b/tests/peakgenotypes.rs
@@ -34,7 +34,7 @@ async fn scan_peak(token: &str, values: &Value) -> Value {
     assert_eq!(response.status(), StatusCode::OK);
     let bytes = response.into_body().collect().await.unwrap().to_bytes();
     let envelope: Value = serde_json::from_slice(&bytes).unwrap();
-    envelope["data"]["markers"]
+    envelope["data"]
         .as_array()
         .unwrap()
         .iter()
@@ -148,7 +148,7 @@ async fn a_marker_away_from_the_peak_is_refused() {
     .await;
     let bytes = response.into_body().collect().await.unwrap().to_bytes();
     let envelope: Value = serde_json::from_slice(&bytes).unwrap();
-    let rows = envelope["data"]["markers"].as_array().unwrap();
+    let rows = envelope["data"].as_array().unwrap();
     let distant = rows
         .iter()
         .find(|row| row[1] != peak[1])
diff --git a/tests/rqtl.rs b/tests/rqtl.rs
index ae0e280..5eeaef4 100644
--- a/tests/rqtl.rs
+++ b/tests/rqtl.rs
@@ -115,7 +115,7 @@ async fn compute_rqtl_maps_a_qtl_from_the_bxd_riset_fixture() {
     );
 
     let data: Value = common::data(&bytes);
-    let markers = data["markers"].as_array().unwrap();
+    let markers = data.as_array().unwrap();
     // The fixture has 6 markers (3 per chromosome, 2 chromosomes).
     assert_eq!(markers.len(), 6);
     // Rows are positional (name, chr, pos, lod); see meta.columns.
@@ -179,8 +179,11 @@ async fn compute_rqtl_with_permutations_returns_thresholds() {
     );
 
     let data: Value = common::data(&bytes);
-    let perm = &data["permutation"];
-    assert!(!perm.is_null(), "{data}");
+    // The permutation null is qualifier information, so it lives in
+    // meta.permutation beside the rows rather than in data.
+    let envelope: Value = serde_json::from_slice(&bytes).unwrap();
+    let perm = &envelope["meta"]["permutation"];
+    assert!(!perm.is_null(), "{envelope}");
     assert_eq!(perm["values"].as_array().unwrap().len(), 20);
     let suggestive = perm["suggestive"].as_f64().unwrap();
     let significant = perm["significant"].as_f64().unwrap();
@@ -432,7 +435,7 @@ async fn compute_rqtl_fits_a_case_attribute_as_a_covariate() {
         String::from_utf8_lossy(&bytes)
     );
     let envelope: Value = serde_json::from_slice(&bytes).unwrap();
-    assert!(!envelope["data"]["markers"].as_array().unwrap().is_empty());
+    assert!(!envelope["data"].as_array().unwrap().is_empty());
 
     let notes: Vec<&str> = envelope["notes"]
         .as_array()
@@ -514,7 +517,7 @@ async fn a_cm_only_genotype_file_maps() {
     let bytes = response.into_body().collect().await.unwrap().to_bytes();
     assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&bytes));
     let envelope: Value = serde_json::from_slice(&bytes).unwrap();
-    let markers = envelope["data"]["markers"].as_array().unwrap();
+    let markers = envelope["data"].as_array().unwrap();
     assert_eq!(
         markers.len(),
         6,