diff options
| -rwxr-xr-x | bin/monitor-gn4 | 35 | ||||
| -rwxr-xr-x | scripts/plot-compare.py | 124 | ||||
| -rw-r--r-- | src/config.rs | 8 | ||||
| -rw-r--r-- | src/lib.rs | 2 | ||||
| -rw-r--r-- | src/pca.rs | 90 | ||||
| -rw-r--r-- | src/routes/compare.rs | 290 | ||||
| -rw-r--r-- | src/routes/correlation.rs | 2 | ||||
| -rw-r--r-- | src/routes/correlation_matrix.rs | 80 | ||||
| -rw-r--r-- | src/routes/mod.rs | 1 | ||||
| -rw-r--r-- | src/routes/plot.rs | 2 |
10 files changed, 627 insertions, 7 deletions
diff --git a/bin/monitor-gn4 b/bin/monitor-gn4 index 609fdb8..f7f0365 100755 --- a/bin/monitor-gn4 +++ b/bin/monitor-gn4 @@ -685,6 +685,14 @@ def build_checks(found, tiers): "top_n": 5}, judge=has_rows, hint="no external tool: pure Rust + MariaDB")) + # Two traits, their shared individuals, and the scatter data. + add(Check("compute-compare", "compute", "POST", "/compute/compare", + "two traits, shared individuals and r (pure Rust)", + body={"a": {"dataset": found.publish, "trait_name": found.trait}, + "b": {"dataset": found.publish, + "trait_name": found.control_trait}}, + judge=has_comparison, + hint="no external tool: pure Rust + MariaDB")) add(Check("compute-rqtl", "compute", "POST", "/compute/rqtl", "R + r-qtl", body={"group": g, "method": "hk", "trait_name": found.trait, @@ -741,6 +749,11 @@ def build_checks(found, tiers): "clustered matrix -> heatmap svg (HEATMAP_PLOTTER)", body=heatmap_plot_body(found), expect=200, hint="HEATMAP_PLOTTER and python3", judge=has_svg)) + if found.control_trait: + add(Check("plot-compare", "plots", "POST", "/plot/compare", + "comparison -> scatter svg (COMPARE_PLOTTER)", + body=compare_plot_body(found), expect=200, + hint="COMPARE_PLOTTER and python3", judge=has_svg)) if found.samples: # The Manhattan plot: a GEMMA run's reply, posted back as-is. add(Check("plot-gemma", "plots", "POST", "/plot/gemma", @@ -785,6 +798,19 @@ def perturbed(body): return None +def has_comparison(reply): + """r, n and the pairs behind them.""" + data = (reply.json or {}).get("data") or {} + pairs = data.get("pairs") + if not isinstance(pairs, list) or len(pairs) < 2: + return FAIL, "no pairs in the answer" + if data.get("n") != len(pairs): + return FAIL, "n=%s but %d pairs" % (data.get("n"), len(pairs)) + if not isinstance(data.get("r"), (int, float)): + return FAIL, "r is %r" % (data.get("r"),) + return OK, "r %.4f over %d individual(s)" % (data["r"], len(pairs)) + + def has_clustering(reply): """A clustered order that is a permutation, with n-1 merges.""" data = (reply.json or {}).get("data") or {} @@ -868,6 +894,15 @@ def _post_result(client, path, body, what): return reply.json or {} +def compare_plot_body(found): + def build(client): + return _post_result(client, "/compute/compare", + {"a": {"dataset": found.publish, "trait_name": found.trait}, + "b": {"dataset": found.publish, + "trait_name": found.control_trait}}, "comparison") + return build + + def heatmap_plot_body(found): def build(client): return _post_result(client, "/compute/correlation/matrix", diff --git a/scripts/plot-compare.py b/scripts/plot-compare.py new file mode 100755 index 0000000..77aeae2 --- /dev/null +++ b/scripts/plot-compare.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Scatter plot of two compared traits, as one SVG panel. + +Input is the JSON response of POST /compute/compare (saved as-is): the paired +values, the individual names, and the r/p/n they came with. The line is the +ordinary least-squares line implied by r and the two means -- nothing is +refitted here, and nothing is invented beyond what the reply carries. + + python3 plot-compare.py compare.json -o compare.svg --trait "1427571_at vs 1427641_at" + +Standard library only; writes plain SVG (light/dark aware). +""" +import argparse +import json +import sys + +W, H = 760, 520 +L, R, T, B = 64, 150, 78, 64 + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + ap.add_argument("result", help="saved /compute/compare response (JSON)") + ap.add_argument("-o", "--out", default="compare.svg") + ap.add_argument("--trait", default="", help="label for the title") + ap.add_argument("--title", default=None) + a = ap.parse_args() + + doc = json.load(open(a.result)) + data = doc.get("data") if isinstance(doc.get("data"), dict) else doc + pairs = data.get("pairs") or [] + if len(pairs) < 2: + sys.exit(f"{a.result}: no `pairs` -- post a /compute/compare reply") + r_value = data.get("r") + p_value = data.get("p") + n = data.get("n") or len(pairs) + first = (data.get("a") or {}) + second = (data.get("b") or {}) + + xs = [float(row[1]) for row in pairs] + ys = [float(row[2]) for row in pairs] + xmin, xmax = min(xs), max(xs) + ymin, ymax = min(ys), max(ys) + pad_x = (xmax - xmin) * 0.06 or 0.5 + pad_y = (ymax - ymin) * 0.06 or 0.5 + xmin, xmax = xmin - pad_x, xmax + pad_x + ymin, ymax = ymin - pad_y, ymax + pad_y + + pw, ph = W - L - R, H - T - B + + def X(v): + return L + (v - xmin) / (xmax - xmin) * pw + + def Y(v): + return T + ph - (v - ymin) / (ymax - ymin) * ph + + label = a.trait or (f"{first.get('trait_name', 'a')} vs {second.get('trait_name', 'b')}") + title = a.title or f"{label}: scatter" + method = data.get("method") or "pearson" + sub = (f"{method} r = {r_value:+.4f}" if isinstance(r_value, (int, float)) else f"{method} r = ?") + if isinstance(p_value, (int, float)): + sub += f", p = {p_value:.3g}" + sub += f", n = {n}" + if data.get("only_one_side"): + sub += f" ยท {data['only_one_side']} individual(s) had a value for only one trait" + desc = (f"Scatter of {first.get('trait_name', 'a')} ({first.get('dataset', '')}) against " + f"{second.get('trait_name', 'b')} ({second.get('dataset', '')}) over {n} individuals, " + f"{method} r {r_value}.") + + s = [f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}" role="img" aria-labelledby="t d" font-family="system-ui,-apple-system,Segoe UI,sans-serif"> +<title id="t">{title}</title> +<desc id="d">{desc}</desc> +<style> +:root{{--surface:#fcfcfb;--ink:#0b0b0b;--ink2:#52514e;--grid:#e6e5e1;--dot:#2a6fdb;--line:#eb6834}} +@media (prefers-color-scheme:dark){{:root{{--surface:#1a1a19;--ink:#f0efec;--ink2:#c3c2b7;--grid:#333330;--dot:#5b8def;--line:#d95926}}}} +text{{fill:var(--ink2);font-size:12px}} .ttl{{fill:var(--ink);font-size:16px;font-weight:600}} +</style> +<rect width="{W}" height="{H}" fill="var(--surface)"/> +<text class="ttl" x="{L}" y="26">{title}</text> +<text x="{L}" y="46">{sub}</text>'''] + + for step in range(5): + value = ymin + (ymax - ymin) * step / 4 + y = Y(value) + s.append(f'<line x1="{L}" x2="{W - R}" y1="{y:.1f}" y2="{y:.1f}" stroke="var(--grid)" stroke-width="1"/>') + s.append(f'<text x="{L - 8}" y="{y + 4:.1f}" text-anchor="end">{value:.3g}</text>') + for step in range(5): + value = xmin + (xmax - xmin) * step / 4 + x = X(value) + s.append(f'<text x="{x:.1f}" y="{T + ph + 16}" text-anchor="middle">{value:.3g}</text>') + + # Least-squares line implied by r and the two standard deviations. + if isinstance(r_value, (int, float)) and n > 2: + mean_x = sum(xs) / n + mean_y = sum(ys) / n + var_x = sum((v - mean_x) ** 2 for v in xs) / (n - 1) + var_y = sum((v - mean_y) ** 2 for v in ys) / (n - 1) + if var_x > 0 and var_y > 0: + slope = r_value * (var_y / var_x) ** 0.5 + y_at = lambda v: mean_y + slope * (v - mean_x) + s.append(f'<line x1="{X(xmin):.1f}" y1="{Y(y_at(xmin)):.1f}" ' + f'x2="{X(xmax):.1f}" y2="{Y(y_at(xmax)):.1f}" stroke="var(--line)" ' + f'stroke-width="2" stroke-dasharray="6 4"/>') + + for row in pairs: + name, xv, yv = row[0], float(row[1]), float(row[2]) + s.append(f'<circle cx="{X(xv):.1f}" cy="{Y(yv):.1f}" r="4" fill="var(--dot)" ' + f'fill-opacity="0.85"><title>{name}: {xv:.4g} vs {yv:.4g}</title></circle>') + + s.append(f'<text transform="translate(18 {T + ph / 2}) rotate(-90)" text-anchor="middle">' + f'{second.get("trait_name", "b")}</text>') + s.append(f'<text x="{L + pw / 2:.1f}" y="{H - 16}" text-anchor="middle">' + f'{first.get("trait_name", "a")}</text>') + s.append(f'<text x="{W - R + 12}" y="{T + 14}">r = {r_value:+.4f}</text>' if isinstance(r_value, (int, float)) else "") + s.append(f'<text x="{W - R + 12}" y="{T + 34}">n = {n}</text>') + s.append(f'<text x="{W - R + 12}" y="{T + 54}" opacity="0.75">dashed: OLS</text>') + s.append(f'<text x="{W - R + 12}" y="{T + 70}" opacity="0.75">from r and the means</text>') + s.append("</svg>") + open(a.out, "w").write("\n".join(s) + "\n") + print(f"{a.out}: {n} points, r {r_value}") + + +if __name__ == "__main__": + main() diff --git a/src/config.rs b/src/config.rs index c6a1553..0061070 100644 --- a/src/config.rs +++ b/src/config.rs @@ -175,6 +175,8 @@ pub struct Config { pub pca_plotter: String, /// Script that draws the clustered heatmap of a correlation matrix (HEATMAP_PLOTTER). pub heatmap_plotter: String, + /// Script that draws the scatter plot of a two-trait comparison (COMPARE_PLOTTER). + pub compare_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. @@ -419,6 +421,10 @@ impl Config { "HEATMAP_PLOTTER".to_string(), "scripts/plot-heatmap.py".to_string(), ); + values.insert( + "COMPARE_PLOTTER".to_string(), + "scripts/plot-compare.py".to_string(), + ); // Per-user baskets: one SQLite file each (src/baskets.rs). Never // MariaDB -- a user's edited column is theirs. values.insert( @@ -487,6 +493,7 @@ impl Config { "GENOTYPE_PLOTTER", "PCA_PLOTTER", "HEATMAP_PLOTTER", + "COMPARE_PLOTTER", "BNW_CMD", "BNW_BIN_DIR", "BNW_CACHE_DIR", @@ -554,6 +561,7 @@ impl Config { bnw_plotter: values["BNW_PLOTTER"].clone(), pca_plotter: values["PCA_PLOTTER"].clone(), heatmap_plotter: values["HEATMAP_PLOTTER"].clone(), + compare_plotter: values["COMPARE_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 976b2f1..c025c46 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -231,6 +231,8 @@ pub fn app() -> Router { .routes(routes!(routes::traits::trait_values)) .routes(routes!(routes::publications::publication_traits)) .routes(routes!(routes::search::search)) + .routes(routes!(routes::compare::compare)) + .routes(routes!(routes::compare::plot_compare)) .routes(routes!(routes::correlation::correlation)) .routes(routes!(routes::correlation_matrix::correlation_matrix)) .routes(routes!(routes::baskets::list_baskets)) diff --git a/src/pca.rs b/src/pca.rs index 23e3105..e924882 100644 --- a/src/pca.rs +++ b/src/pca.rs @@ -55,6 +55,29 @@ pub struct Pca { /// Eigenvalues should sum to the number of traits; reported so a caller can /// check that the decomposition is sane rather than trust it. pub trace: f64, + /// The components *as traits*: one value per individual per component, so + /// they can be used the way GN2's "PCA traits" are -- correlated, mapped, + /// plotted, saved in a basket. Empty when the caller did not ask, or when + /// the values were not available to project. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub traits: Vec<PcTrait>, +} + +/// One principal component as a trait: a value per individual. +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +pub struct PcTrait { + /// `PC1`, `PC2`, ... in eigenvalue order. + pub name: String, + /// Score per individual, in the same order as `individuals`. + pub values: Vec<PcValue>, + /// Share of total variance this component explains. + pub explained_variance_ratio: f64, +} + +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +pub struct PcValue { + pub name: String, + pub value: f64, } #[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] @@ -189,6 +212,7 @@ pub fn analyse(matrix: &Matrix) -> Pca { scree: Vec::new(), dropped, trace: 0.0, + traits: Vec::new(), }; } let small: Vec<Vec<f64>> = kept @@ -201,6 +225,7 @@ pub fn analyse(matrix: &Matrix) -> Pca { scree: Vec::new(), dropped, trace: 0.0, + traits: Vec::new(), }; }; let trace: f64 = eigenvalues.iter().sum(); @@ -221,7 +246,72 @@ pub fn analyse(matrix: &Matrix) -> Pca { scree: eigenvalues, dropped, trace, + traits: Vec::new(), + } +} + +/// Project standardised trait values onto the components, giving PC scores. +/// +/// `values` is traits x individuals for the traits the PCA kept, in the kept +/// order and already aligned to `individuals`; a trait is standardised with the +/// **sample** standard deviation (n-1), because that is what the correlation +/// matrix was built from -- using the population one would rescale every score +/// by a constant and quietly disagree with `r`. +/// +/// Returns one [`PcTrait`] per component. `None` when the shapes disagree or a +/// value is missing, rather than filling a zero into a score. +pub fn scores( + pca: &Pca, + values: &[Vec<f64>], + individuals: &[String], +) -> Option<Vec<PcTrait>> { + let n_traits = values.len(); + if n_traits == 0 || individuals.len() != values[0].len() || values.iter().any(|v| v.len() != individuals.len()) { + return None; + } + if pca.components.len() < n_traits || pca.components[0].loadings.len() != n_traits { + return None; + } + let n = individuals.len(); + if n < 2 { + return None; + } + // z-scores per trait + let mut standardised: Vec<Vec<f64>> = Vec::with_capacity(n_traits); + for trait_values in values { + if trait_values.iter().any(|v| !v.is_finite()) { + return None; + } + let mean = trait_values.iter().sum::<f64>() / n as f64; + let variance = trait_values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / (n - 1) as f64; + let sd = variance.sqrt(); + // A constant trait has no z-score; it also has no correlation with + // anything, so it should have been dropped before we get here. + if !(sd > 0.0) { + return None; + } + standardised.push(trait_values.iter().map(|v| (v - mean) / sd).collect()); + } + let mut out = Vec::with_capacity(pca.components.len()); + for (index, component) in pca.components.iter().enumerate() { + let mut scores = vec![0.0; n]; + for (trait_index, loading) in component.loadings.iter().enumerate() { + for (individual, z) in standardised[trait_index].iter().enumerate() { + scores[individual] += loading * z; + } + } + out.push(PcTrait { + name: format!("PC{}", index + 1), + values: individuals + .iter() + .cloned() + .zip(scores) + .map(|(name, value)| PcValue { name, value }) + .collect(), + explained_variance_ratio: component.explained_variance_ratio, + }); } + Some(out) } #[cfg(test)] diff --git a/src/routes/compare.rs b/src/routes/compare.rs new file mode 100644 index 0000000..9879b8a --- /dev/null +++ b/src/routes/compare.rs @@ -0,0 +1,290 @@ +//! Compare two traits: their shared individuals, the correlation, and a +//! scatter plot of one against the other. +//! +//! GN1's "compare traits" and GN2's trait page both show this, and every piece +//! of it already existed here -- `values_of` for the values, the engine for r +//! and p, the plot family for the figure. What was missing was one endpoint +//! that says "these two, over the individuals they share", with the individual +//! names in the reply so a reader can see which points they are looking at. +//! +//! Deliberate choices: +//! +//! * **The minimum overlap is the correlation floor** (6), not 2: two points +//! always fit a line, and a scatter of two points would look like a result. +//! * **The individuals travel with the numbers**, because a scatter plot is +//! read by looking at outliers, and "which animal is that" is the first +//! question. GN2's page answers it with a hover label; here it is in the +//! reply and in the plot's tooltips. +//! * **Nothing is regressed.** The line in the plot is drawn from r and the two +//! means (an ordinary least-squares line through standardised values), which +//! is the only slope implied by the numbers; no fitted model is invented. + +use axum::Json; +use serde::Deserialize; +use utoipa::ToSchema; + +use crate::auth::AuthToken; +use crate::correlation::{self, Method, Reference}; +use crate::error::ApiError; +use crate::error::Unauthorized; +use crate::response::{Ctx, Envelope}; + +use super::correlation::{db_failure, values_of, TraitRef}; +use crate::plot; +use gnauth_macros::gnauth; + +#[derive(Debug, Clone, Deserialize, ToSchema)] +pub struct CompareRequest { + /// The first trait. + pub a: TraitRef, + /// The second trait. + pub b: TraitRef, + /// "pearson" (default) or "spearman". + #[serde(default)] + pub method: Option<String>, +} + +#[utoipa::path(post, path = "/compute/compare", + summary = "Compare two traits: their shared individuals, r, p and n", + description = "Fetches both traits, keeps the individuals that have a value for both, and \ +returns the correlation over them together with the paired values -- so the reply is both the \ +statistic and the data a scatter plot is drawn from. Needs the same six paired observations the \ +rest of the correlation surface needs: two points always fit a line. `spearman` ranks the pairs \ +first, as everywhere else.", + request_body = CompareRequest, + responses( + (status = 200, description = "The comparison", body = Envelope<serde_json::Value>), + Unauthorized, + (status = 422, description = "Unknown method, a trait with no values, or fewer than six shared individuals", body = ApiError), + (status = 500, description = "Internal error", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn compare( + ctx: Ctx, + _token: AuthToken, + Json(request): Json<CompareRequest>, +) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { + let rid = ctx.request_info(); + let fail = |code: &str, title: &str, detail: String| { + ApiError::new( + axum::http::StatusCode::UNPROCESSABLE_ENTITY, + code, + title, + detail, + "compare_traits", + ) + .with_request_id(rid.clone()) + }; + let method = Method::parse(request.method.as_deref().unwrap_or("pearson")) + .map_err(|detail| fail("invalid_method", "Invalid correlation method", detail))?; + + let wanted = request.clone(); + let computed = tokio::task::spawn_blocking(move || align(&request)) + .await + .map_err(|error| { + ApiError::new( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + error.to_string(), + "compare_traits", + ) + .with_request_id(rid.clone()) + })? + .map_err(|failure| failure.into_api(rid.clone()))?; + + let aligned = computed; + let n = aligned.pairs.len(); + if n < correlation::MIN_OVERLAP { + return Err(fail( + "too_few_shared", + "Too few shared individuals", + format!( + "these two traits share {n} individual(s) with values; a comparison needs at \ + least {}", + correlation::MIN_OVERLAP + ), + )); + } + let x: Vec<f64> = aligned.pairs.iter().map(|(_, a, _)| *a).collect(); + let y: Vec<f64> = aligned.pairs.iter().map(|(_, _, b)| *b).collect(); + let (r, p) = correlation::correlate_named_value(&x, &y, n, method).ok_or_else(|| { + fail( + "no_correlation", + "No correlation", + "the coefficient is not a number over these individuals \ + (a constant trait has no correlation with anything)" + .to_string(), + ) + })?; + + let rows = serde_json::Value::Array( + aligned + .pairs + .iter() + .map(|(individual, a, b)| serde_json::json!([individual, a, b])) + .collect(), + ); + let mut body = serde_json::json!({ + "a": {"dataset": wanted.a.dataset, "trait_name": wanted.a.trait_name}, + "b": {"dataset": wanted.b.dataset, "trait_name": wanted.b.trait_name}, + "method": method.as_str(), + "r": r, + "p": if p.is_finite() { serde_json::Value::from(p) } else { serde_json::Value::Null }, + "n": n, + "pairs": rows, + }); + if let Some(extra) = aligned.only_one_side { + body["only_one_side"] = serde_json::Value::from(extra); + } + Ok(Json( + ctx.envelope(body) + .with_columns( + vec!["individual".to_string(), "a".to_string(), "b".to_string()], + n, + ) + .with_note(&format!( + "{} ({}) against {} ({}), {} over the {n} individual(s) with a value for both.", + wanted.a.trait_name, wanted.a.dataset, wanted.b.trait_name, wanted.b.dataset, + method.as_str() + )) + .with_note( + "`pairs` is positional: individual, first trait's value, second trait's value. \ + The individuals that had a value for only one side are counted in \ + `only_one_side`.", + ) + .with_next("/plot/compare", "The same numbers as a scatter plot"), + )) +} + +#[utoipa::path(post, path = "/plot/compare", + summary = "Draw the scatter plot of two compared traits, as an SVG", + description = "Post the response of POST /compute/compare back (as-is) and get the figure \ +scripts/plot-compare.py draws from it: one point per individual that has both values, the \ +individual's name in each point's tooltip, and the least-squares line implied by r and the two \ +means. Nothing is refitted and nothing is recomputed. image/svg+xml, not the JSON envelope; \ +`x-plot-summary` carries the plotter's one-line summary.", + params(super::plot::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 is not a comparison", body = ApiError), + (status = 502, description = "The plotter failed", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn plot_compare( + ctx: Ctx, + _token: AuthToken, + axum::extract::Query(plot_params): axum::extract::Query<super::plot::PlotParams>, + Json(posted): Json<serde_json::Value>, +) -> Result<axum::response::Response, ApiError> { + let rid = ctx.request_info(); + let data = posted.get("data").unwrap_or(&posted); + let pairs = data.get("pairs").and_then(|pairs| pairs.as_array()); + if pairs.map(|rows| rows.len()).unwrap_or(0) < 2 { + return Err(ApiError::new( + axum::http::StatusCode::UNPROCESSABLE_ENTITY, + "not_a_comparison", + "Not a comparison", + "the posted body has fewer than two `pairs`: post a /compute/compare reply".to_string(), + "plot_compare", + ) + .with_request_id(rid)); + } + let config = crate::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.compare_plotter, + std::path::Path::new(&config.gemma_cache_dir), + &posted, + plot_params.trait_label.as_deref().unwrap_or(""), + &borrowed, + ) + .await + .map_err(|error| { + ApiError::new( + axum::http::StatusCode::BAD_GATEWAY, + "plot_failed", + "The plotter failed", + error.to_string(), + "plot_compare", + ) + .with_request_id(rid) + })?; + Ok(super::plot::svg_response(rendered)) +} + +/// The aligned pairs, plus a count of individuals only one side had. +struct Aligned { + pairs: Vec<(String, f64, f64)>, + only_one_side: Option<usize>, +} + +fn align(request: &CompareRequest) -> Result<Aligned, super::correlation::Failure> { + let a = values_of(&request.a.dataset, &request.a.trait_name)?; + let b = values_of(&request.b.dataset, &request.b.trait_name)?; + let mut pairs = Vec::new(); + let mut only_one_side = 0usize; + for (index, name) in a.names.iter().enumerate() { + match b.names.iter().position(|candidate| candidate == name) { + Some(position) => pairs.push((name.clone(), a.values[index], b.values[position])), + None => only_one_side += 1, + } + } + // Individuals only in B are not visited by the loop above. + for name in &b.names { + if !a.names.contains(name) { + only_one_side += 1; + } + } + Ok(Aligned { + pairs, + only_one_side: if only_one_side > 0 { + Some(only_one_side) + } else { + None + }, + }) +} + +/// Keep `Reference` in scope for readers of `align`. +#[allow(dead_code)] +fn _reference_is_used(_: &Reference) {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pairs_are_the_shared_individuals() { + let a = Reference::from_pairs(vec![ + ("s1".to_string(), Some(1.0)), + ("s2".to_string(), Some(2.0)), + ("s3".to_string(), Some(3.0)), + ]); + let b = Reference::from_pairs(vec![ + ("s2".to_string(), Some(20.0)), + ("s3".to_string(), Some(30.0)), + ("s4".to_string(), Some(40.0)), + ]); + let mut pairs = Vec::new(); + for (index, name) in a.names.iter().enumerate() { + if let Some(position) = b.names.iter().position(|candidate| candidate == name) { + pairs.push((name.clone(), a.values[index], b.values[position])); + } + } + assert_eq!(pairs, vec![ + ("s2".to_string(), 2.0, 20.0), + ("s3".to_string(), 3.0, 30.0), + ]); + } +} diff --git a/src/routes/correlation.rs b/src/routes/correlation.rs index 2a7f8a2..a3620f6 100644 --- a/src/routes/correlation.rs +++ b/src/routes/correlation.rs @@ -702,7 +702,7 @@ fn resolve_reference(request: &CorrelationRequest) -> Result<correlation::Refere /// One trait's values, from whichever kind of dataset holds it: a probeset by /// name, a phenotype trait by numeric id. -fn values_of(dataset: &str, trait_name: &str) -> Result<correlation::Reference, Failure> { +pub(crate) fn values_of(dataset: &str, trait_name: &str) -> Result<correlation::Reference, Failure> { let request = CorrelationRequest { dataset: dataset.to_string(), trait_name: trait_name.to_string(), diff --git a/src/routes/correlation_matrix.rs b/src/routes/correlation_matrix.rs index 9a433b6..9676cd4 100644 --- a/src/routes/correlation_matrix.rs +++ b/src/routes/correlation_matrix.rs @@ -167,7 +167,7 @@ pub async fn correlation_matrix( } let wanted = request.clone(); - let matrix = tokio::task::spawn_blocking(move || build(&request, method, min_overlap)) + let (matrix, references) = tokio::task::spawn_blocking(move || build(&request, method, min_overlap)) .await .map_err(|error| { ApiError::new( @@ -192,11 +192,22 @@ pub async fn correlation_matrix( } } let measured = measured / 2; - let pca = if wanted.pca.unwrap_or(false) { + let mut pca = if wanted.pca.unwrap_or(false) { Some(crate::pca::analyse(&matrix)) } else { None }; + // The components as *traits*: a PC is only usable (correlated, mapped, + // plotted, saved in a basket) if it has a value per individual, and that + // needs the values the matrix was built from -- which is why it happens + // here and not in pca::analyse. + if let Some(pca) = pca.as_mut() { + if let Some((values, individuals)) = kept_values_in_order(&references, pca) { + if let Some(traits) = crate::pca::scores(pca, &values, &individuals) { + pca.traits = traits; + } + } + } let mut body = serde_json::json!({ "traits": matrix.traits, "r": matrix.r, @@ -278,6 +289,64 @@ pub async fn correlation_matrix( )) } +/// The aligned values of the traits the PCA kept, over the individuals that +/// have a value for **every** kept trait. +/// +/// PCA of standardised traits is only defined on a complete rectangle, which is +/// the same rule that already dropped traits with a gap: a different individual +/// set per trait would make the scores incomparable across individuals. +fn kept_values_in_order( + references: &[Reference], + pca: &crate::pca::Pca, +) -> Option<(Vec<Vec<f64>>, Vec<String>)> { + let components = pca.components.first()?; + let n_kept = components.loadings.len(); + if n_kept == 0 || n_kept > references.len() { + return None; + } + // The kept traits are the first n_kept that have values; the PCA was built + // from the matrix's own kept order, so take that same order. + let kept: Vec<&Reference> = references + .iter() + .filter(|reference| !reference.is_empty()) + .take(n_kept) + .collect(); + if kept.len() != n_kept { + return None; + } + let individuals: Vec<String> = kept[0] + .names + .iter() + .filter(|name| { + kept.iter().all(|reference| { + reference + .names + .iter() + .position(|candidate| candidate == *name) + .map(|position| true) + .unwrap_or(false) + }) + }) + .cloned() + .collect(); + if individuals.len() < 3 { + return None; + } + let mut values: Vec<Vec<f64>> = Vec::with_capacity(n_kept); + for reference in &kept { + let mut row = Vec::with_capacity(individuals.len()); + for name in &individuals { + let position = reference + .names + .iter() + .position(|candidate| candidate == name)?; + row.push(reference.values[position]); + } + values.push(row); + } + Some((values, individuals)) +} + /// How many traits the request asked for. fn matrix_trait_count(matrix: &Matrix) -> usize { matrix.traits.len() @@ -299,9 +368,10 @@ fn build( request: &MatrixRequest, method: Method, min_overlap: usize, -) -> Result<Matrix, Failure> { +) -> Result<(Matrix, Vec<Reference>), Failure> { let axis = matrix_axis(request)?; let references = resolve_traits(request, axis.as_deref())?; + let references_out = references.clone(); let count = references.len(); let mut r = vec![vec![None; count]; count]; @@ -343,7 +413,7 @@ fn build( } } - Ok(Matrix { + Ok((Matrix { traits: request .traits .iter() @@ -355,7 +425,7 @@ fn build( r, p, n, - }) + }, references_out)) } /// The individuals every trait is measured over: the first trait's group. diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 0461165..0da2eaa 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -7,6 +7,7 @@ pub mod accessions; pub mod baskets; pub mod bnw; pub mod bulklmm; +pub mod compare; pub mod correlation; pub mod correlation_matrix; pub mod datasets; diff --git a/src/routes/plot.rs b/src/routes/plot.rs index 2b4c043..d33f5d7 100644 --- a/src/routes/plot.rs +++ b/src/routes/plot.rs @@ -346,7 +346,7 @@ pub async fn plot_gemma( } /// The SVG, with the plotter's summary alongside it. -fn svg_response(rendered: plot::Plot) -> Response { +pub(crate) fn svg_response(rendered: plot::Plot) -> Response { let mut response = rendered.svg.into_response(); let headers = response.headers_mut(); headers.insert( |
