about summary refs log tree commit diff
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-11 13:46:24 +0000
committerPjotr <wrk@bosa.lan>2026-11-11 13:46:24 +0000
commit9cb59caa1f13ee44ed6fcf7bc6526a87311e8e9f (patch)
treec33a6fe1a61ee76dcb688abab2c19a1df6832963
parent25f376a8d9e7b5511e0799fd3b09898bb682a202 (diff)
downloadgenenetwork4-9cb59caa1f13ee44ed6fcf7bc6526a87311e8e9f.tar.gz
plot/gemma: draw thresholds computed elsewhere, labelled with their source
GEMMA has no permutation test here, so its plot carries a Bonferroni line.
A threshold from /compute/bulklmm belongs to a different null and must not
look like GEMMA's, so it is passed in and named:

  POST /plot/gemma?thresholds=3.50,3.65
                   &threshold_labels=bulklmm%20alpha%200.10,bulklmm%20alpha%200.05

Each is drawn dashed in the series colour with "label: value" beside the
line, with GEMMA's Bonferroni line still there, and the plotter's
x-plot-summary names the reference lines it drew. A threshold that is not
a positive number is a 422 invalid_threshold rather than a silent omission.

/compute/bulklmm's reply offers that href already, with its alpha 0.05
threshold filled in -- so "same values, two models, one picture" is one
link from the scan, and the labels keep the two nulls apart.

tests/plot.rs: the plain plot has no bulklmm line; with thresholds both
are drawn and labelled; a non-numeric threshold is refused.
-rw-r--r--README.md14
-rw-r--r--scripts/plot-gemma.py25
-rw-r--r--src/routes/bulklmm.rs14
-rw-r--r--src/routes/plot.rs65
-rw-r--r--tests/plot.rs79
5 files changed, 195 insertions, 2 deletions
diff --git a/README.md b/README.md
index ab4e08b..9cc014e 100644
--- a/README.md
+++ b/README.md
@@ -1887,6 +1887,20 @@ which is the trait's published locus (`PublishXRef.Locus` `rsm10000000888`, LOD
 9.59) and a genome-wide-significant peak against a threshold this API could not
 compute before. Rows are `marker, chr, pos (Mb), lod, beta, h2`.
 
+**Thresholds on another engine's plot.** `/plot/gemma` draws GEMMA's own
+Bonferroni line unless told otherwise; a threshold computed here travels with
+it, labelled, because the two are different nulls:
+
+```
+POST /plot/gemma?thresholds=3.50,3.65&threshold_labels=bulklmm%20alpha%200.10,bulklmm%20alpha%200.05
+{ the /compute/gemma reply }
+```
+
+Each line is drawn dashed in the series colour with its label and value
+(`bulklmm alpha 0.05: 3.65`), beside GEMMA's Bonferroni line, which stays.
+`/compute/bulklmm`'s reply already offers that href with its α = 0.05 threshold
+filled in, so the picture is one link away.
+
 **About cores.** BulkLMM's single-trait `scan()` — what this endpoint calls —
 is **serial in Julia by design**: the package threads `bulkscan()` (many traits)
 and its helpers, not `scan()` (checked in its source: `Threads.@threads` appears
diff --git a/scripts/plot-gemma.py b/scripts/plot-gemma.py
index f2a6302..3f75c2b 100644
--- a/scripts/plot-gemma.py
+++ b/scripts/plot-gemma.py
@@ -28,6 +28,9 @@ def main():
     ap.add_argument("--trait", default="", help="trait label for the title, e.g. 20010")
     ap.add_argument("--title", default=None, help="override the title text")
     ap.add_argument("--no-bonferroni", action="store_true", help="omit the threshold line")
+    ap.add_argument("--threshold", action="append", default=[],
+                    help="extra reference line as VALUE[:LABEL], e.g. 3.81:bulklmm alpha 0.05 "
+                         "(thresholds another engine computed for the same values)")
     a = ap.parse_args()
 
     doc = json.load(open(a.result))
@@ -56,7 +59,15 @@ def main():
 
     top = max(((v, c, pos, rs) for c in order for pos, v, rs in by[c]))
     bonf = -math.log10(0.05 / nrows)
-    ymax = max(4, math.ceil(max(top[0], 0 if a.no_bonferroni else bonf) + 0.3))
+    # Reference lines from elsewhere: (value, label). Whoever computed them gets
+    # named in the label, so a reader can tell a BulkLMM threshold from GEMMA's
+    # own Bonferroni line -- they are not the same null.
+    external = []
+    for spec in a.threshold:
+        value, _, label = spec.partition(":")
+        external.append((float(value), label.strip() or "bulklmm threshold"))
+    ymax = max(4, math.ceil(max([top[0], 0 if a.no_bonferroni else bonf] +
+                               [value for value, _ in external]) + 0.3))
     W, H, L, R, T, B = 1000, 430, 62, 20, 64, 52
     pw, ph = W - L - R, H - T - B
     X = lambda c, p: L + (off[c] + p) / tot * pw
@@ -107,11 +118,21 @@ text{{fill:var(--ink2);font-size:12px}} .ttl{{fill:var(--ink);font-size:16px;fon
         y = Y(bonf)
         s.append(f'<line x1="{L}" x2="{W - R}" y1="{y:.1f}" y2="{y:.1f}" stroke="var(--ink2)" stroke-width="1.25" stroke-dasharray="7 4"/>')
         s.append(f'<text x="{W - R - 4}" y="{y - 5:.1f}" text-anchor="end">Bonferroni, {nrows:,} markers: {bonf:.2f}</text>')
+    for value, label in external:
+        y = Y(value)
+        s.append(f'<line x1="{L}" x2="{W - R}" y1="{y:.1f}" y2="{y:.1f}" '
+                 f'stroke="var(--s2)" stroke-width="1.5" stroke-dasharray="2 4"/>')
+        s.append(f'<text x="{L + 6}" y="{y - 5:.1f}">{label}: {value:.2f}</text>')
     s.append(f'<circle cx="{tx:.1f}" cy="{ty:.1f}" r="4.5" fill="var(--s2)" stroke="var(--surface)" stroke-width="2"><title>{top[3]}: chr{top[1]} {top[2]:.1f} Mb, -log10 p {top[0]:.2f}</title></circle>')
     s.append(f'<text class="ann" x="{tx + 10:.1f}" y="{ty + 4:.1f}">chr{top[1]} {top[2]:.0f} Mb, -log10 p {top[0]:.2f}</text>')
     s.append("</svg>")
     open(a.out, "w").write("\n".join(s))
-    print(f"wrote {a.out}: peak {top[3]} chr{top[1]} {top[2]:.1f} Mb -log10p {top[0]:.2f}; Bonferroni {bonf:.2f} over {nrows} markers")
+    extra_note = ""
+    if external:
+        extra_note = "; reference line(s) " + ", ".join(
+            f"{label} {value:.2f}" for value, label in external)
+    print(f"wrote {a.out}: peak {top[3]} chr{top[1]} {top[2]:.1f} Mb -log10p {top[0]:.2f}; "
+          f"Bonferroni {bonf:.2f} over {nrows} markers{extra_note}")
 
 
 if __name__ == "__main__":
diff --git a/src/routes/bulklmm.rs b/src/routes/bulklmm.rs
index c173d5e..ea4b805 100644
--- a/src/routes/bulklmm.rs
+++ b/src/routes/bulklmm.rs
@@ -631,6 +631,20 @@ pub async fn compute_bulklmm(
             body: None,
         });
     }
+    // And, when thresholds were computed, the GEMMA plot can carry them: same
+    // values, two models, one picture -- labelled so the lines cannot be mixed up.
+    if let Some(lod) = output.thresholds.get("0.05") {
+        envelope = envelope.with_action(crate::response::SuggestedCall {
+            method: "POST".to_string(),
+            href: format!(
+                "/plot/gemma?thresholds={lod:.2}&threshold_labels=bulklmm%20alpha%200.05"
+            ),
+            description: "Or draw a GEMMA result for the same values with this threshold on it \
+                          (the request body is the /compute/gemma reply)"
+                .to_string(),
+            body: None,
+        });
+    }
     envelope = envelope.with_action(crate::response::SuggestedCall {
         method: "POST".to_string(),
         href: "/plot/bulklmm".to_string(),
diff --git a/src/routes/plot.rs b/src/routes/plot.rs
index cae2463..5ce7c4f 100644
--- a/src/routes/plot.rs
+++ b/src/routes/plot.rs
@@ -38,6 +38,61 @@ pub struct PlotParams {
     pub title: Option<String>,
     /// GEMMA only: set to false to omit the Bonferroni reference line.
     pub bonferroni: Option<String>,
+    /// Reference lines on a GEMMA plot, in LOD / -log10 p units, comma
+    /// separated: the thresholds another engine computed for the same values
+    /// (`/compute/bulklmm` prints them in its `notes`). Drawn alongside
+    /// GEMMA's own Bonferroni line and labelled, so the two are never confused.
+    pub thresholds: Option<String>,
+    /// Labels for those lines, comma separated and in the same order, e.g.
+    /// "bulklmm alpha 0.05". Anything missing defaults to "bulklmm threshold".
+    pub threshold_labels: Option<String>,
+}
+
+/// The reference lines a caller passed, validated: `(value, label)`.
+fn external_thresholds(
+    thresholds: Option<&str>,
+    labels: Option<&str>,
+    rid: &crate::response::RequestInfo,
+) -> Result<Vec<(f64, String)>, ApiError> {
+    let Some(thresholds) = thresholds else { return Ok(Vec::new()) };
+    let values: Vec<&str> = thresholds.split(',').map(str::trim).filter(|v| !v.is_empty()).collect();
+    if values.is_empty() {
+        return Ok(Vec::new());
+    }
+    let labels: Vec<&str> = labels
+        .map(|labels| labels.split(',').map(str::trim).collect())
+        .unwrap_or_default();
+    let mut lines = Vec::with_capacity(values.len());
+    for (index, value) in values.iter().enumerate() {
+        let parsed = value.parse::<f64>().map_err(|_| {
+            ApiError::new(
+                StatusCode::UNPROCESSABLE_ENTITY,
+                "invalid_threshold",
+                "Invalid threshold",
+                format!("'{value}' is not a number; `thresholds` takes LOD / -log10 p values"),
+                "plot",
+            )
+            .with_request_id(rid.clone())
+        })?;
+        if !parsed.is_finite() || parsed <= 0.0 {
+            return Err(ApiError::new(
+                StatusCode::UNPROCESSABLE_ENTITY,
+                "invalid_threshold",
+                "Invalid threshold",
+                format!("{parsed}: a reference line has to be a positive number"),
+                "plot",
+            )
+            .with_request_id(rid.clone()));
+        }
+        let label = labels
+            .get(index)
+            .copied()
+            .filter(|label| !label.is_empty())
+            .unwrap_or("bulklmm threshold")
+            .to_string();
+        lines.push((parsed, label));
+    }
+    Ok(lines)
 }
 
 /// The trait a posted compute response says it mapped: the `Trait: ...`
@@ -235,6 +290,16 @@ pub async fn plot_gemma(
     if matches!(plot_params.bonferroni.as_deref(), Some("false") | Some("0") | Some("no")) {
         extra.push("--no-bonferroni".to_string());
     }
+    // Thresholds from another engine (`/compute/bulklmm` prints them): drawn on
+    // GEMMA's own scale, labelled, so a reader can see which is which.
+    for (value, label) in external_thresholds(
+        plot_params.thresholds.as_deref(),
+        plot_params.threshold_labels.as_deref(),
+        &rid,
+    )? {
+        extra.push("--threshold".to_string());
+        extra.push(format!("{value}:{label}"));
+    }
     let borrowed: Vec<&str> = extra.iter().map(String::as_str).collect();
     let rendered = plot::render(
         &config.plot_python,
diff --git a/tests/plot.rs b/tests/plot.rs
index 123784b..594fc73 100644
--- a/tests/plot.rs
+++ b/tests/plot.rs
@@ -312,3 +312,82 @@ async fn two_traits_draw_two_different_plots() {
         "every chromosome's trace differs between the two traits"
     );
 }
+
+/// GEMMA's own reference line is a Bonferroni threshold; a threshold from
+/// another engine (BulkLMM's rotations) is a different null and must be
+/// labelled as such, not drawn as if it were GEMMA's.
+#[tokio::test]
+async fn a_gemma_plot_takes_labelled_thresholds_from_another_engine() {
+    let Some(token) = common::auth_token().await else {
+        eprintln!("skipping a_gemma_plot_takes_labelled_thresholds_from_another_engine: no token");
+        return;
+    };
+    if !common::db_available() {
+        eprintln!("skipping: no database");
+        return;
+    }
+    let values = common::get_with_token(
+        "GET /groups/BXD/traits/16627/values",
+        "/groups/BXD/traits/16627/values",
+        &token,
+    )
+    .await;
+    assert_eq!(values.status(), StatusCode::OK);
+    let bytes = values.into_body().collect().await.unwrap().to_bytes();
+    let samples: Value = common::data(&bytes);
+    let mapped = common::post_json_with_token(
+        "POST /compute/gemma (for the plot)",
+        "/compute/gemma",
+        &token,
+        &serde_json::json!({
+            "group": "BXD", "genotype_version": "BXD.8", "trait_name": "BXD::16627",
+            "samples": samples,
+        }),
+    )
+    .await;
+    assert_eq!(mapped.status(), StatusCode::OK);
+    let bytes = mapped.into_body().collect().await.unwrap().to_bytes();
+    let envelope: Value = serde_json::from_slice(&bytes).unwrap();
+
+    // Without them: GEMMA's Bonferroni line only.
+    let plain = common::post_json_with_token(
+        "POST /plot/gemma",
+        "/plot/gemma",
+        &token,
+        &envelope,
+    )
+    .await;
+    assert_eq!(plain.status(), StatusCode::OK);
+    let bytes = plain.into_body().collect().await.unwrap().to_bytes();
+    let svg = String::from_utf8_lossy(&bytes).to_string();
+    assert!(svg.contains("Bonferroni"), "GEMMA's own line is there");
+    assert!(!svg.contains("bulklmm"), "and nothing claims to be BulkLMM's");
+
+    // With them: drawn and named.
+    let with = common::post_json_with_token(
+        "POST /plot/gemma?thresholds=",
+        "/plot/gemma?thresholds=3.50,3.65&threshold_labels=bulklmm%20alpha%200.10,bulklmm%20alpha%200.05",
+        &token,
+        &envelope,
+    )
+    .await;
+    assert_eq!(with.status(), StatusCode::OK);
+    let bytes = with.into_body().collect().await.unwrap().to_bytes();
+    let svg = String::from_utf8_lossy(&bytes);
+    assert!(svg.contains("bulklmm alpha 0.10: 3.50"), "labelled with its source");
+    assert!(svg.contains("bulklmm alpha 0.05: 3.65"), "and the second one");
+    assert!(svg.contains("Bonferroni"), "GEMMA's line is still drawn beside them");
+
+    // A threshold that is not a number is refused, not silently dropped.
+    let bad = common::post_json_with_token(
+        "POST /plot/gemma?thresholds=",
+        "/plot/gemma?thresholds=abc",
+        &token,
+        &envelope,
+    )
+    .await;
+    assert_eq!(bad.status(), StatusCode::UNPROCESSABLE_ENTITY);
+    let bytes = bad.into_body().collect().await.unwrap().to_bytes();
+    let error: Value = serde_json::from_slice(&bytes).unwrap();
+    assert_eq!(error["code"], "invalid_threshold");
+}