Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions lib/analysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { describeCohortDef } from "./cohort2.ts";
import type { AnalysisDoc, AnalysisResult, Clause, CohortDef, PartitionDef, ViewResult, ViewKind, ViewParticipation, TemplateDoc, SplitBy, LockDrift } from "./types.ts";
import { plainResult } from "./types.ts";
import { resolveSplitBy, type AttributeDistribution } from "./cohort-splitby.ts";
import { resolverFor, PatientLevelResolver, AggregateResolver, studyRouting, restrictedStudies, studyAccess, hasViewAggregates, attributeCutsSql, type Resolver } from "./federation.ts";
import { resolverFor, PatientLevelResolver, AggregateResolver, studyRouting, restrictedStudies, studyAccess, hasViewAggregates, attributeCutsSql, attributeLevels, type Resolver } from "./federation.ts";
import { cantDraw } from "./view-coverage.ts";
import { describeSources, sourceIndex } from "./provenance.ts";
import { resolveParams } from "./params.ts";
Expand Down Expand Up @@ -166,7 +166,8 @@ export interface RunOpts {
* A categorical attribute's value counts within a cohort, merged across every study the cohort
* spans. Each study answers for its own part of the cohort (attributeStats is on AggregateCapable, so an
* aggregate-only or remote participant answers too), and disagreeing declared types across
* studies are refused, not silently merged, as the clinical view's cross-study comparison does.
* studies are refused, not silently merged, as the clinical view's cross-study comparison does — and so
* are studies storing it at different levels, whose counts would add patients to samples.
*/
async function mergedDistribution(cohortName: string, def: CohortDef, studies: string[],
resolverOf: (s: string) => Promise<Resolver>, attribute: string, opts?: { topValues?: number }): Promise<AttributeDistribution & { partial?: boolean }> {
Expand All @@ -180,8 +181,10 @@ async function mergedDistribution(cohortName: string, def: CohortDef, studies: s
if (kinds.size > 1)
return { kind: "cat", per: "patient",
skipped: "'" + attribute + "' is declared inconsistently (numeric in one study, categorical in another) across “" + cohortName + "”'s studies" };
const levels = attributeLevels(studies.map((study, i) => ({ study, stat: perStudyStats[i] })));
if (levels.conflict) return { kind: "cat", per: levels.level ?? "patient", skipped: "'" + attribute + "' across “" + cohortName + "”'s studies: " + levels.conflict };
const kind = (perStudyStats[0]?.kind ?? "cat") as "cat" | "num";
const per = (perStudyStats[0]?.per ?? "patient") as "patient" | "sample";
const per = (levels.level ?? perStudyStats[0]?.per ?? "patient") as "patient" | "sample";
if (kind === "num") return { kind, per };
const merged = new Map<string, number>();
for (const s of perStudyStats) for (const { v, n } of (s?.values || [])) merged.set(v, (merged.get(v) || 0) + n);
Expand Down
29 changes: 27 additions & 2 deletions lib/federation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,29 @@ export interface AttrStats {
/** set when THIS site declines to describe it, with the reason */
skipped?: string;
}

/** true when the answer holds values: only those say which level they were counted at */
const holdsValues = (x: AttrStats | undefined): x is AttrStats =>
!!x && !x.skipped && (x.kind === "cat" ? !!x.values?.length : !!x.n);

/**
* Answers about one attribute, one per (cohort, study), counted per patient where a study stores
* it per patient and per sample where per sample. Pooled, they would add patients to samples, so
* a disagreement is a refusal: why, or null when the answers holding values share one level.
* `level` is the first value-holding answer's level, for the row that reports either outcome.
*/
export function attributeLevels(answers: { study: string; stat: AttrStats | undefined }[]): { level: "patient" | "sample" | null; conflict: string | null } {
const held = answers.filter((a): a is { study: string; stat: AttrStats } => holdsValues(a.stat));
const at = (lvl: string) => [...new Set(held.filter((a) => a.stat.per === lvl).map((a) => a.study))].sort();
const patient = at("patient"), sample = at("sample");
const level = held.length ? held[0].stat.per : null;
if (!patient.length || !sample.length) return { level, conflict: null };
const both = patient.filter((s) => sample.includes(s));
const why = both.length
? both.join(", ") + (both.length === 1 ? " stores" : " store") + " it both per patient and per sample"
: "the participating studies store it at different levels (patient in " + patient.join(", ") + "; sample in " + sample.join(", ") + ")";
return { level, conflict: why + "; its counts would mix patients with samples" };
}
/** One gene pair's 2x2 among samples profiled for BOTH genes. Counts only. */
export interface PairCounts {
a: string; b: string;
Expand Down Expand Up @@ -1811,13 +1834,15 @@ abstract class BaseResolver implements AggregateCapable {
const db = this.instance.conn.db, conn = this.instance.conn;
const list = attrs.map(sq).join(",");
const meta = await this.runQuiet<ChRow>(aggregateSql(
"SELECT cam.attr_id AS a, upper(cam.datatype) AS dt\n" +
"SELECT cam.attr_id AS a, upper(cam.datatype) AS dt, lower(toString(cam.patient_attribute)) AS pa\n" +
"FROM " + clinicalMetaTable(db) + " cam\n" +
"JOIN " + db + ".cancer_study cs ON cs.cancer_study_id = cam.cancer_study_id\n" +
"WHERE cs.cancer_study_identifier = " + sq(this.study) + " AND cam.attr_id IN (" + list + ")"))
.catch(() => ({ data: [] as ChRow[] }));
const kindOf = new Map<string, "cat" | "num">(
meta.data.map((r) => [r.a, String(r.dt) === "NUMBER" ? "num" as const : "cat" as const]));
// the level the study declares, for an answer with no rows to read it from
const declared = new Map<string, "patient" | "sample">(meta.data.map((r) => [r.a, ["1", "true"].includes(String(r.pa)) ? "patient" as const : "sample" as const]));
const catAttrs = attrs.filter((a) => kindOf.get(a) === "cat");
const numAttrs = attrs.filter((a) => kindOf.get(a) === "num");
const cohort = this.cohortSql(def);
Expand All @@ -1837,7 +1862,7 @@ abstract class BaseResolver implements AggregateCapable {
}
for (const a of catAttrs) {
const g = grouped.get(a);
if (!g) { out.push({ attribute: a, per: "patient", kind: "cat", values: [] }); continue; }
if (!g) { out.push({ attribute: a, per: declared.get(a) ?? "patient", kind: "cat", values: [] }); continue; }
// a caller choosing which values deserve a group of its own asks for the most frequent
// ones only; it runs no test over the table, so nothing is wrong about a partial one
const top = opts?.topValues != null ? Math.max(1, Math.min(500, Math.floor(opts.topValues))) : null;
Expand Down
2 changes: 1 addition & 1 deletion lib/views/clinical/doc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import type { KindDoc } from "../kind-doc.ts";

export const clinicalDoc: KindDoc = {
summary: "attribute distributions per cohort",
reference: `\`attributes:[\u22641-20] | allAttributes:true, cohorts:[names]\` | compares clinical attribute distributions across cohorts. \`allAttributes:true\` compares every attribute the studies declare (at most 300), as cBioPortal's Comparison page does, leaving out each survival endpoint's \`_MONTHS\`/\`_STATUS\` pair, \`AGE_LAST_FU_YEARS\` and \`BIRTH_YEAR\` as it does, and gives each row its display name (\`label\`). An attribute is tested only with two values among the groups and two groups holding any (the portal's rule); the rest are listed as not tested, with the reason, and take no part in the q-values. Categorical: Pearson chi-squared over the **full** value vocabulary, any number of cohorts. Numeric: Welch's unequal-variance t-test for exactly 2 cohorts, **Welch's ANOVA for 3+** \u2014 both from (n, \u03a3x, \u03a3x\u00b2) per cohort, additive across sites, so pooled mean/variance are exact and no individual value is transmitted, at any study count. BH q across attributes (moment-based test only). Each site types its own attributes from \`clinical_attribute_meta\`; disagreements are refused, not merged. **Single-study views only:** numeric attributes also report median/IQR, and a rank-based test alongside the moment-based one \u2014 a Mann-Whitney U for exactly 2 cohorts, **Kruskal-Wallis for 3+** \u2014 a check worth having when the mean is misleading (skew, outliers); computed from the complete value distribution, which is exact only when the whole comparison stays within one study, so it is not offered otherwise, and not part of the q-value correction above`,
reference: `\`attributes:[\u22641-20] | allAttributes:true, cohorts:[names]\` | compares clinical attribute distributions across cohorts. \`allAttributes:true\` compares every attribute the studies declare (at most 300), as cBioPortal's Comparison page does, leaving out each survival endpoint's \`_MONTHS\`/\`_STATUS\` pair, \`AGE_LAST_FU_YEARS\` and \`BIRTH_YEAR\` as it does, and gives each row its display name (\`label\`). An attribute is tested only with two values among the groups and two groups holding any (the portal's rule); the rest are listed as not tested, with the reason, and take no part in the q-values. Categorical: Pearson chi-squared over the **full** value vocabulary, any number of cohorts. Numeric: Welch's unequal-variance t-test for exactly 2 cohorts, **Welch's ANOVA for 3+** \u2014 both from (n, \u03a3x, \u03a3x\u00b2) per cohort, additive across sites, so pooled mean/variance are exact and no individual value is transmitted, at any study count. BH q across attributes (moment-based test only). Each site types its own attributes from \`clinical_attribute_meta\`; disagreements are refused, not merged, as is an attribute one study stores per patient and another per sample (its counts would mix patients with samples). **Single-study views only:** numeric attributes also report median/IQR, and a rank-based test alongside the moment-based one \u2014 a Mann-Whitney U for exactly 2 cohorts, **Kruskal-Wallis for 3+** \u2014 a check worth having when the mean is misleading (skew, outliers); computed from the complete value distribution, which is exact only when the whole comparison stays within one study, so it is not offered otherwise, and not part of the q-value correction above`,
grammar: `{"kind":"clinical","attributes":[...(1-20)],"allAttributes":true?,"cohorts":[names?]}`,
};
16 changes: 13 additions & 3 deletions lib/views/clinical/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// participant's value counts and moments.
import { benjaminiHochberg, chiSquareTest, welchT, welchAnovaTest, varianceFromMoments, mannWhitneyU, kruskalWallis, quantilesFromHistogram } from "../../stats.ts";
import type { ViewResult } from "../../types.ts";
import type { AttrStats } from "../../federation.ts";
import { attributeLevels, type AttrStats } from "../../federation.ts";
import { ATTR_NAME_RE } from "../../custom-data.ts";
import { untimed, type Untimed, type ViewRun, type DocView } from "../run.ts";
import { overLimit, answering } from "../shared.ts";
Expand Down Expand Up @@ -81,7 +81,13 @@ export async function runClinical(view: DocView, c: ViewRun): Promise<ViewResult
skipped: "the participating studies disagree on its type (" + kinds.join(" vs ") + "); comparing them would mean discarding one side's patients" });
continue;
}
const kind = kinds[0], per = all[0].per;
// patients and samples are never added in one cell
const levels = attributeLevels(vNames.flatMap((n) => cohorts[n].studies.map((st) => ({ study: st, stat: pick(n, st) }))));
if (levels.conflict) {
rows.push({ attribute, per: levels.level ?? all[0].per, kind: kinds[0], cells: [], skipped: levels.conflict });
continue;
}
const kind = kinds[0], per = levels.level ?? all[0].per;
if (kind === "cat") {
const cells = vNames.map((n) => {
const merged = new Map<string, number>();
Expand Down Expand Up @@ -165,6 +171,8 @@ export async function runClinical(view: DocView, c: ViewRun): Promise<ViewResult
const hiddenTested = tested.filter((r) => hidden.has(r.attribute)).length;
const shown = rows.filter((r) => !hidden.has(r.attribute));
const untested = shown.filter((r) => r.p == null).length;
// tested but not listed, and not tested after all: named here, as nothing else shows them
const hiddenUntested = rows.filter((r) => hidden.has(r.attribute) && r.p == null);
const siteKeys = vNames.flatMap((n) => [...cohorts[n].studies].sort().map((st) => ({ cohort: n, study: st })));
const testedAttrs = new Set(rows.filter((r) => !r.skipped).map((r) => r.attribute));
const siteStats = siteKeys.flatMap(({ cohort, study }) =>
Expand Down Expand Up @@ -203,7 +211,9 @@ export async function runClinical(view: DocView, c: ViewRun): Promise<ViewResult
"), but each survival endpoint's _MONTHS / _STATUS pair, AGE_LAST_FU_YEARS and BIRTH_YEAR are not listed, as on cBioPortal" +
(listed.unlisted.length ? "; " + listed.unlisted.join(", ") + " could not list its attributes, so only those the others declare are asked of it" : "") + "." : "") +
(untested ? " " + untested + " attribute" + (untested === 1 ? " is" : "s are") + " listed as not tested, each with its reason (a test needs two values and two groups holding any), and left out of the q-values." : "") +
(vStudies.length > 1 ? " Counts are pooled across " + vStudies.length + " studies without harmonizing vocabularies; an attribute the studies type differently is refused rather than merged." :
(hiddenUntested.length ? " Of the attributes tested but not listed, " + hiddenUntested.map((r) => r.attribute + " (" + (r.skipped || "not tested") + ")").join("; ") +
(hiddenUntested.length === 1 ? " was" : " were") + " not tested and left out of the q-values." : "") +
(vStudies.length > 1 ? " Counts are pooled across " + vStudies.length + " studies without harmonizing vocabularies; an attribute the studies type differently, or store at different levels (per patient in one, per sample in another), is refused rather than merged." :
rank ? " Numeric attributes also show median/IQR, from the same distributions." :
" Numeric attributes also show median/IQR and a rank-based test alongside the moment-based one — a" +
" Mann-Whitney U for 2 cohorts, Kruskal-Wallis for 3+ (neither itself part of the q-value correction) —" +
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"check:results-oql": "node --env-file=.env.local scripts/check-results-oql.ts",
"check:density": "node --env-file=.env.local scripts/check-density.ts",
"check:case-lists": "node --env-file=.env.local scripts/check-case-lists.ts",
"check:conflicting-levels": "node --env-file=.env.local scripts/check-conflicting-levels.ts",
"check:chart-freq": "node --env-file=.env.local scripts/check-chart-freq.ts",
"check:gene-panels": "node --env-file=.env.local scripts/check-gene-panels.ts",
"check:enrichment-events": "node --env-file=.env.local scripts/check-enrichment-events.ts",
Expand Down
Loading
Loading