about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-11 12:37:26 +0000
committerPjotr <wrk@bosa.lan>2026-11-11 12:37:26 +0000
commit84aced61986f229931b5e7738b4c64df45251a85 (patch)
tree8561fd6c863be1ccf828716817e1a34cb8db0f67 /src
parent3022797b55bae96322439770ea48e74eb2e0eb8d (diff)
downloadgenenetwork4-84aced61986f229931b5e7738b4c64df45251a85.tar.gz
bulklmm: exact marker-block parallelism, and what the cores are actually doing
Reported: a BulkLMM run does not look multicore. It is not a
misconfiguration. BulkLMM's single-trait `scan()` -- what this endpoint
calls -- has no `Threads.@threads` at all; the package threads
`bulkscan()` (many traits) and bulkscan_helpers, not scan. The
parallelism that was visible before was BLAS (OpenBLAS defaulting to all
96 cores here), which is why `user` time ran 4x `real` while Julia
threads made no difference: --threads 1 13.7 s, --threads 4 12.3 s.

  * The driver splits the markers into independent blocks and scans them
    on Julia threads (--blocks, default = BULKLMM_THREADS). It is exact:
    the LOD for each marker is independent given the null variance
    components, which depend on y and K only. Verified identical -- peak
    LOD 9.589938 and the same permutation thresholds at 1 and 4 blocks --
    and permutation thresholds combine by taking each permutation's
    maximum across blocks before the quantiles, which is what a
    genome-wide threshold is.
  * The parsed matrix and the kinship are cached per panel (read 1.3 s ->
    0.4 s, kinship 0.9 s -> 0), because both depend only on the cross.
  * The summary in `notes` now says what ran: julia threads, blocks, BLAS
    threads, and the read/scan split.
  * The hand parser is back: CSV.jl into a DataFrame is an order of
    magnitude slower for a 21056 x 235 matrix (14-17 s against 2 s).
  * BLAS is capped at 4 threads -- 96 was slower (10.5 s against 7.7 s for
    one scan).

Measured on BXD.8 trait 16627 (21056 markers): 1 block 20.9 s, 4 blocks
18.3 s, same answer. The gain is modest because the LMM loop is ~8 s of
the run and each block re-estimates its variance components. Where the
cores pay is bulkscan() -- many traits in one process, threaded over
trait blocks -- which is the shape the next endpoint wants; documented in
the README rather than left as folklore.
Diffstat (limited to 'src')
-rw-r--r--src/config.rs9
-rw-r--r--src/lib.rs1
-rw-r--r--src/routes/bulklmm.rs8
-rw-r--r--src/routes/gemma.rs15
-rw-r--r--src/routes/plot.rs92
5 files changed, 120 insertions, 5 deletions
diff --git a/src/config.rs b/src/config.rs
index 8bbaae0..42b74e7 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -159,6 +159,8 @@ pub struct Config {
     pub bulklmm_script: String,
     pub bulklmm_threads: u32,
     pub bulklmm_cache_dir: String,
+    /// The script that draws a BulkLMM scan (`BULKLMM_PLOTTER`).
+    pub bulklmm_plotter: String,
     /// Directory holding the genotype files (`GENOTYPE_FILES`): GN2's
     /// layout -- `genotype/<Group>.json` for the version list,
     /// `genotype/<stem>.geno`, `genotype/bimbam/<stem>_geno.txt` and
@@ -340,6 +342,10 @@ impl Config {
         );
         values.insert("BULKLMM_THREADS".to_string(), "4".to_string());
         values.insert(
+            "BULKLMM_PLOTTER".to_string(),
+            "scripts/plot-bulklmm.py".to_string(),
+        );
+        values.insert(
             "BULKLMM_CACHE_DIR".to_string(),
             std::env::temp_dir()
                 .join("gn4-bulklmm")
@@ -420,6 +426,7 @@ impl Config {
             "BULKLMM_SCRIPT",
             "BULKLMM_THREADS",
             "BULKLMM_CACHE_DIR",
+            "BULKLMM_PLOTTER",
         ] {
             if let Ok(value) = std::env::var(key) {
                 values.insert(key.to_string(), value);
@@ -472,6 +479,7 @@ impl Config {
             bulklmm_script: values["BULKLMM_SCRIPT"].clone(),
             bulklmm_threads: values["BULKLMM_THREADS"].parse().unwrap_or(4),
             bulklmm_cache_dir: values["BULKLMM_CACHE_DIR"].clone(),
+            bulklmm_plotter: values["BULKLMM_PLOTTER"].clone(),
             genotype_files_dir: values["GENOTYPE_FILES"].clone(),
             sql_check_health: parse_switch(&values["SQL_CHECK_HEALTH"]),
             rqtl_max_concurrent: values["RQTL_MAX_CONCURRENT"]
@@ -727,6 +735,7 @@ mod tests {
             "BULKLMM_SCRIPT",
             "BULKLMM_THREADS",
             "BULKLMM_CACHE_DIR",
+            "BULKLMM_PLOTTER",
         ] {
             if std::env::var(key).is_ok() {
                 eprintln!("skipping: {key} is set in the environment");
diff --git a/src/lib.rs b/src/lib.rs
index 0260399..1df4151 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -149,6 +149,7 @@ pub fn app() -> Router {
         .routes(routes!(routes::plot::plot_rqtl))
         .routes(routes!(routes::plot::plot_gemma))
         .routes(routes!(routes::plot::plot_genotypes))
+        .routes(routes!(routes::plot::plot_bulklmm))
         .routes(routes!(routes::phewas::group_phewas))
         .routes(routes!(routes::frequencies::group_version_frequencies))
         .routes(routes!(routes::frequencies::group_marker_frequencies))
diff --git a/src/routes/bulklmm.rs b/src/routes/bulklmm.rs
index b5a2f0f..f244e5d 100644
--- a/src/routes/bulklmm.rs
+++ b/src/routes/bulklmm.rs
@@ -605,6 +605,14 @@ pub async fn compute_bulklmm(
             body: None,
         });
     }
+    envelope = envelope.with_action(crate::response::SuggestedCall {
+        method: "POST".to_string(),
+        href: "/plot/bulklmm".to_string(),
+        description: "Draw this scan: post this reply back and get the LOD plot, with the \
+                      thresholds above drawn on it."
+            .to_string(),
+        body: None,
+    });
     envelope = envelope.with_links(crate::suggest::root_links());
     for note in &notes {
         envelope = envelope.with_note(note);
diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs
index 194e3c8..79bc445 100644
--- a/src/routes/gemma.rs
+++ b/src/routes/gemma.rs
@@ -304,14 +304,19 @@ pub async fn compute_gemma(
                 "{requested_permutations} permutations requested, but this endpoint runs none: \
                  each one repeats the entire LOCO association scan (gemma-wrapper --permutate), \
                  so a thousand is thousands of scans and hours of the one slot GEMMA has here. \
-                 For significance thresholds, send the same trait values to POST /compute/rqtl \
-                 with \"nperm\": 100 -- R/qtl has the permutation test and reports the \
-                 suggestive and significant LOD thresholds; judge a GEMMA peak against the \
-                 smallest p_lrt it reached."
+                 For significance thresholds, send the same trait values to POST /compute/bulklmm \
+                 with \"nperm\": 200: it fits an LMM with a global kinship matrix and permutes by \
+                 rotating the data through that matrix, so the thresholds belong to a mixed \
+                 model (R/qtl's nperm works too, but its null ignores relatedness). Judge a GEMMA \
+                 peak against whichever threshold you use, or against the smallest p_lrt it \
+                 reached -- and remember BulkLMM is global-kinship, not LOCO."
             ),
             "compute_gemma",
         )
-        .with_request_id(rid));
+        .with_request_id(rid)
+        // The error contract carries one `next` href; the description in the
+        // detail above says what to do with it.
+        .with_next("/compute/bulklmm"));
     }
 
     let config = Config::load();
diff --git a/src/routes/plot.rs b/src/routes/plot.rs
index f386526..cae2463 100644
--- a/src/routes/plot.rs
+++ b/src/routes/plot.rs
@@ -435,3 +435,95 @@ pub async fn plot_genotypes(
     })?;
     Ok(svg_response(rendered))
 }
+
+/// What `/plot/bulklmm` validates in a posted BulkLMM result: positional rows
+/// whose `meta.columns` carry a LOD, the shape `/compute/bulklmm` returns.
+fn check_bulklmm_result(result: &serde_json::Value) -> Result<(), String> {
+    let rows = result
+        .get("data")
+        .and_then(|data| data.as_array())
+        .ok_or("the posted body has no `data` array of rows")?;
+    if rows.is_empty() {
+        return Err("the posted body has no rows".to_string());
+    }
+    let columns: Vec<&str> = result
+        .get("meta")
+        .and_then(|meta| meta.get("columns"))
+        .and_then(|columns| columns.as_array())
+        .map(|columns| columns.iter().filter_map(|c| c.as_str()).collect())
+        .unwrap_or_default();
+    if columns.len() < 4 || columns.get(3) != Some(&"lod") {
+        return Err(format!(
+            "expected the columns of /compute/bulklmm (marker, chr, pos, lod, …), got {columns:?}"
+        ));
+    }
+    Ok(())
+}
+
+#[utoipa::path(post, path = "/plot/bulklmm",
+    summary = "Draw a BulkLMM scan, as an SVG",
+    description = "Post the response of POST /compute/bulklmm back (as-is) and get the LOD plot \
+scripts/plot-bulklmm.py draws from it, with the permutation thresholds the reply's own `notes` \
+carry (alpha 0.05 genome-wide, alpha 0.01) drawn as dashed lines. Nothing is recomputed. \
+image/svg+xml, not the JSON envelope; `x-plot-summary` carries the plotter's one-line peak \
+summary.",
+    params(PlotParams),
+    request_body = serde_json::Value,
+    responses(
+        (status = 200, description = "The plot, as image/svg+xml", body = String, content_type = "image/svg+xml"),
+        Unauthorized,
+        (status = 422, description = "The posted body is not a BulkLMM result", body = ApiError),
+        (status = 502, description = "The plotter could not run, or failed", body = ApiError)
+    )
+)]
+#[gnauth(token_only)]
+pub async fn plot_bulklmm(
+    ctx: Ctx,
+    _token: AuthToken,
+    Query(plot_params): Query<PlotParams>,
+    Json(posted): Json<serde_json::Value>,
+) -> Result<Response, ApiError> {
+    let rid = ctx.request_info();
+    if let Err(detail) = check_bulklmm_result(&posted) {
+        return Err(ApiError::new(
+            StatusCode::UNPROCESSABLE_ENTITY,
+            "not_a_bulklmm_result",
+            "Not a BulkLMM result",
+            detail,
+            "plot_bulklmm",
+        )
+        .with_request_id(rid));
+    }
+    let config = Config::load();
+    let mut extra: Vec<String> = Vec::new();
+    if let Some(title) = plot_params.title.as_deref() {
+        extra.push("--title".to_string());
+        extra.push(title.to_string());
+    }
+    let borrowed: Vec<&str> = extra.iter().map(String::as_str).collect();
+    let rendered = plot::render(
+        &config.plot_python,
+        &config.bulklmm_plotter,
+        std::path::Path::new(&config.bulklmm_cache_dir),
+        &posted,
+        plot_params
+            .trait_label
+            .clone()
+            .or_else(|| trait_from_document(&posted))
+            .as_deref()
+            .unwrap_or("bulklmm"),
+        &borrowed,
+    )
+    .await
+    .map_err(|error| {
+        ApiError::new(
+            StatusCode::BAD_GATEWAY,
+            "plot_failed",
+            "Could not draw the plot",
+            error.to_string(),
+            "plot_bulklmm",
+        )
+        .with_request_id(rid.clone())
+    })?;
+    Ok(svg_response(rendered))
+}