about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-11-16 16:18:05 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-11-16 16:18:05 +0000
commit33e837e771e07936c808fb3aeb3540525691718c (patch)
tree597a452051f2cd6f901c39b95acad2d1bafc6352 /src
parent0e94a6a728e08feb69f183667f62dfabf86768d8 (diff)
downloadgenenetwork4-33e837e771e07936c808fb3aeb3540525691718c.tar.gz
plot: the scree plot of a matrix PCA, which GN2 draws client-side
GN2 renders a scree plot with Plotly in the browser, from the explained
variance ratios its matrix page computed. This is the same figure as a file:
`POST /plot/pca` takes the matrix reply (with `"pca": true`) as-is and returns
image/svg+xml, like every other plot endpoint -- the plot is of the numbers
that were computed, nothing is recomputed.

scripts/plot-pca.py draws a bar per component (its share of the variance,
GN2's number), a cumulative line with the 80%-of-variance crossing annotated
(what a reader actually uses to choose how many components to keep), the
eigenvalue in each bar's tooltip, and the traits the PCA had to drop for gaps
in the matrix -- the one thing GN2 hides by mutating its shared-sample list.
`kind=N` on the request caps how many components are drawn, since a
200-trait matrix would otherwise draw 200 bars.

Also: the monitor's SVG judge now understands a binary reply (the client hands
back content type and size, not the bytes), and `plot-pca` is a check of its
own: it asks the matrix for a PCA and posts the reply to the plotter.

Deployed: PCA_PLOTTER is pinned in env.sh (the code default is a relative
path, which only resolves when the service's working directory is the
checkout). plot-pca and plot-genotypes both ok.
Diffstat (limited to 'src')
-rw-r--r--src/config.rs8
-rw-r--r--src/lib.rs1
-rw-r--r--src/routes/plot.rs104
3 files changed, 113 insertions, 0 deletions
diff --git a/src/config.rs b/src/config.rs
index b23d39b..a4a078c 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -171,6 +171,8 @@ pub struct Config {
     pub bnw_cache_dir: String,
     /// The script `/plot/bnw` runs to draw a network (`BNW_PLOTTER`).
     pub bnw_plotter: String,
+    /// Script that draws the scree plot of a correlation-matrix PCA (PCA_PLOTTER).
+    pub pca_plotter: String,
     /// Directory holding BNW's worked example datasets (`BNW_EXAMPLES_DIR`),
     /// served by `/compute/bnw/examples`. Empty means the endpoint reports
     /// that no examples are configured.
@@ -407,6 +409,10 @@ impl Config {
             "GENOTYPE_PLOTTER".to_string(),
             "scripts/plot-genotypes.py".to_string(),
         );
+        values.insert(
+            "PCA_PLOTTER".to_string(),
+            "scripts/plot-pca.py".to_string(),
+        );
         // Per-user baskets: one SQLite file each (src/baskets.rs). Never
         // MariaDB -- a user's edited column is theirs.
         values.insert(
@@ -473,6 +479,7 @@ impl Config {
             "WIKIDATA_TTL_SECONDS",
             "BASKET_DIR",
             "GENOTYPE_PLOTTER",
+            "PCA_PLOTTER",
             "BNW_CMD",
             "BNW_BIN_DIR",
             "BNW_CACHE_DIR",
@@ -538,6 +545,7 @@ impl Config {
             bnw_bin_dir: values["BNW_BIN_DIR"].clone(),
             bnw_cache_dir: values["BNW_CACHE_DIR"].clone(),
             bnw_plotter: values["BNW_PLOTTER"].clone(),
+            pca_plotter: values["PCA_PLOTTER"].clone(),
             bnw_examples_dir: values["BNW_EXAMPLES_DIR"].clone(),
             bulklmm_cmd: values["BULKLMM_CMD"].clone(),
             bulklmm_env: values["BULKLMM_ENV"].clone(),
diff --git a/src/lib.rs b/src/lib.rs
index 9568983..1973652 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -259,6 +259,7 @@ pub fn app() -> Router {
         .routes(routes!(routes::plot::plot_genotypes))
         .routes(routes!(routes::plot::plot_bulklmm))
         .routes(routes!(routes::plot::plot_bnw))
+        .routes(routes!(routes::plot::plot_pca))
         .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/plot.rs b/src/routes/plot.rs
index 4a0c7ec..fd56abc 100644
--- a/src/routes/plot.rs
+++ b/src/routes/plot.rs
@@ -733,3 +733,107 @@ pub async fn plot_bulklmm(
     })?;
     Ok(svg_response(rendered))
 }
+
+#[utoipa::path(post, path = "/plot/pca",
+    summary = "Draw the scree plot of a correlation-matrix PCA, as an SVG",
+    description = "Post the response of POST /compute/correlation/matrix back (as-is) after \
+asking it for `\"pca\": true`, and get the figure scripts/plot-pca.py draws from it: one bar per \
+component for its share of the variance, a cumulative line so a reader can see how many \
+components carry the signal, and the traits the PCA had to drop for gaps. GN2 draws the same \
+figure client-side with Plotly; this is the same numbers as a file. Nothing is recomputed. \
+image/svg+xml, not the JSON envelope; `x-plot-summary` carries the plotter's one-line summary.",
+    params(PlotParams),
+    request_body = serde_json::Value,
+    responses(
+        (status = 200, description = "The SVG", body = String, content_type = "image/svg+xml"),
+        Unauthorized,
+        (status = 422, description = "The posted body carries no pca components", body = ApiError),
+        (status = 502, description = "The plotter failed", body = ApiError)
+    )
+)]
+#[gnauth(token_only)]
+pub async fn plot_pca(
+    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_pca_result(&posted) {
+        return Err(ApiError::new(
+            StatusCode::UNPROCESSABLE_ENTITY,
+            "not_a_pca_result",
+            "Not a PCA result",
+            detail,
+            "plot_pca",
+        )
+        .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());
+    }
+    if let Some(kind) = plot_params.kind.as_deref() {
+        // `--max-components N`, so a 200-trait matrix does not draw 200 bars.
+        let n: usize = kind.trim().parse().map_err(|_| {
+            ApiError::new(
+                StatusCode::UNPROCESSABLE_ENTITY,
+                "invalid_kind",
+                "Unknown figure",
+                format!("kind must be a number of components to draw, not {kind:?}"),
+                "plot_pca",
+            )
+            .with_request_id(rid.clone())
+        })?;
+        extra.push("--max-components".to_string());
+        extra.push(n.to_string());
+    }
+    let borrowed: Vec<&str> = extra.iter().map(String::as_str).collect();
+    let rendered = plot::render(
+        &config.plot_python,
+        &config.pca_plotter,
+        std::path::Path::new(&config.gemma_cache_dir),
+        &posted,
+        plot_params
+            .trait_label
+            .as_deref()
+            .or(plot_params.title.as_deref())
+            .unwrap_or(""),
+        &borrowed,
+    )
+    .await
+    .map_err(|error| {
+        ApiError::new(
+            StatusCode::BAD_GATEWAY,
+            "plot_failed",
+            "The plotter failed",
+            error.to_string(),
+            "plot_pca",
+        )
+        .with_request_id(rid)
+    })?;
+    Ok(svg_response(rendered))
+}
+
+/// The posted body must carry `pca.components`, from the matrix endpoint.
+fn check_pca_result(result: &serde_json::Value) -> Result<(), String> {
+    let pca = result
+        .get("data")
+        .and_then(|data| data.get("pca"))
+        .or_else(|| result.get("pca"))
+        .ok_or("the posted body has no `pca` object: ask /compute/correlation/matrix for \
+                \"pca\": true first")?;
+    let components = pca
+        .get("components")
+        .and_then(|components| components.as_array())
+        .ok_or("`pca.components` is missing")?;
+    if components.is_empty() {
+        return Err("`pca.components` is empty -- the PCA had nothing to decompose".to_string());
+    }
+    if components.len() < 2 {
+        return Err("a scree plot needs at least two components".to_string());
+    }
+    Ok(())
+}