Skip to content

Study View: the clinical violin table, a categorical attribute against a numeric one (STS-VI-1…7) - #470

Merged
alisman merged 4 commits into
masterfrom
studyview-violin-table
Nov 19, 2026
Merged

alisman merged 4 commits into
masterfrom
studyview-violin-table

Conversation

@alisman

@alisman alisman commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add chart › X vs Y now adds the portal's violin/box plot table for a numeric × categorical pair (STS-VI-1…7). Before, the button for that pair was disabled.

  • The card: "[ (log)] vs " (e.g. "Diagnosis Age vs Cancer Type Detailed"). One row per category:
    • the category;
    • a mirrored grey curve and a #dddddd box across the numeric attribute's range, on a dashed grid;
    • # with a checkbox that filters on the category (the categorical chart's own clause);
    • Median, Quartile 1, Quartile 3, at most two decimals without trailing zeros, as the portal's toFixedWithoutTrailingZeros.
  • Footer: "Hide # <" defaults to 10. Columns sort, # descending by default. An empty table reads "No data."
  • Menu: Log Scale (Mutation Count only, ln(1 + v)), Show Violin Plot, Show Box Plot, Remove chart. Remove chart takes the table's filters on both attributes with it, as the portal's and as Study View: Add chart's X vs Y tab, a density chart for any two numeric attributes (STV-AC-7, STS-SC-1) #462's density charts (violinChartRemoval).
  • Numbers, as cBioPortal's ViolinPlotServiceImpl (lib/study-view-violin.ts):
    • quartiles by Apache Commons' Percentile, position p(n + 1);
    • whiskers at the 1.5 × IQR fences when any value lies past them, else the data's ends, kept on the axis;
    • outliers past 3 × IQR left out of the curve and drawn as points;
    • a row of seven values or fewer drawn as points alone;
    • the curve a sum of Gaussians at 100 points with sigma 4 steps, each row scaled by min(1, 12 / its peak).
  • Counting (buildViolinFacets, lib/explore.ts): Explore returns, per category, each numeric value with the samples holding it. These are values and counts, never ids, and the browser computes the table from them.
    • A patient's value stands for each of its samples.
    • The curve and box are drawn without the numeric attribute's own filter, and # counts with it, as the portal's controller does.
    • A peer's studies are named on the card, not counted.
    • More than 50,000 distinct (category, value) pairs is refused, naming the limit.
  • Colours: PORTAL_VIOLIN in lib/chart/style.ts.

Size: 23 files, +834 / −17. About 450 lines are code: the rules (lib/study-view-violin.ts), the server counts (buildViolinFacets), the card (app/lab/explore-violin.tsx) and the wiring. The rest are tests, the fixture check (scripts/check-violin.ts) and planted bugs. Kept as one PR with the Merger's agreement.

Spec IDs

  • Covered: STS-VI-1 (title, settings), STS-VI-2 (columns, sort, number format), STS-VI-3 (Hide # <, "No data."), STS-VI-4 (rendering), STS-VI-6 (a category's checkbox), STS-VI-7 (menu); STV-AC-7's numeric × categorical button.
  • Left out:
    • the drag across the numeric column to pick a range (STS-VI-6);
    • point tooltips with sample links (STS-VI-5): the server sends values, not ids;
    • the resizable category column;
    • the gene-specific violin (STS-VI-8).
  • Differs: on Log Scale the quartile columns show counts, as the tooltip does. The portal's columns show log-space values there, a bug the legacy spec records.

Verification

  • Against cbioportal.org's /api/clinical-data-violin-plots/fetch, from our /api/explore through violinTable: every row's #, Q1, median, Q3, both whiskers, the 100 curve points (to 1e-9) and the point count are equal in each case:

    • coadread Cancer Type Detailed × Age (Colon Adenocarcinoma 376: 58.25 / 69 / 77);
    • Sex × Mutation Count, linear and log (outliers drawn as points);
    • AJCC Pathologic Tumor Stage × FGA (13 rows);
    • Sex × Age under an Age 50–60 filter (its own) and under a Rectal filter (another).
  • Fixture check: scripts/check-violin.ts, a new gate phase "violin tables", which scripts/gate.sh runs directly (no npm script, so package.json stays out of the diff). On the fixture study (patient-level SEX × sample-level FGA; a numeric attribute holding "12abc") and on coadread, undrafted and under drafts, it checks:

    • each row's values are the samples' own, read by a separate join;
    • its # is what its click selects among samples with a value;
    • the attribute's own filter narrows # and not the values drawn;
    • coadread's rows equal the portal's.
  • Browser, dev server, coadread: Cancer Type Detailed × Diagnosis Age reads Colon Adenocarcinoma 376 · 69 · 58.25 · 77, Rectal 155 · 65 · 57 · 72, Mucinous 61 · 67 · 52.5 · 79.5. The box tip reads "Median: 69 / Quartile 1: 58.25 / Quartile 3: 77". Checking Rectal adds the "Cancer Type Detailed : Rectal Adenocarcinoma" filter (155 match). No page errors.

  • e2e: a new step in test/e2e/explore.cjs on luad, Sex × Diagnosis Age: Female 265 · 66 · 58.5 · 73 and Male 230 · 66 · 59 · 72 as the portal's, two curves; Female's checkbox filters to Female, and Remove chart takes the table and that filter. Run on its own against my dev server: pass.

  • Unit tests:

    • test/study-view-violin-spec.test.ts: a case per legacy branch (percentile, fences, outliers, points-only rows, the curve, #, log, rows, format, title, the drawn path);
    • test/explore-facets.test.ts: the query, two connections, own filter versus another, the limit;
    • test/study-view-add-chart-spec.test.ts: the button adds a violin either way round, and an existing one is refused;
    • Remove chart's pair and the two attributes it clears (violinChartRemoval).

    npm test 7,013 pass, 0 fail (with master merged in); tsc --noEmit and eslint clean.

  • Coverage: passes.

  • Planted bugs: 4 in scripts/mutants/study-view/violin-table.ts (guard unit).

Tracker

Under "Study View → summary charts", this line (docs/PORTAL-PARITY.md:404), with #462's density sub-item:

  • Chart kinds: treatment tables, the GA frequency table (arm-level CNA by default), variant annotations, X-vs-Y density and violin, gene-specific violin, continuous gene bar (STS-OT-4…6, STS-VI-1…8, STS-GS-4, STS-SC-1, STS-STM-16, STS-STM-17)

gains:

Scorecard 30-study-summary.md, rows STS-VI-1…7 (each was ❌):

| STS-VI-1 | ✅ | C | Add chart › X vs Y with a numeric × categorical pair; "[ (log)] vs "; violin and box on, log off (ViolinCard) |
| STS-VI-2 | ✅ | C | category · curve and box · # with checkbox · Median / Quartile 1 / Quartile 3 (violinNumber); sortable, # descending; category column not resizable |
| STS-VI-3 | ✅ | C | "Hide # <" 10 (violinRows); "No data." |
| STS-VI-4 | ✅ | C | the portal's curve (Gaussians, 100 points, sigma 4 steps), min(1, 12 / peak), ≤ 7 values as points, 3 × IQR outliers as points, #dddddd box 10 px (violinTable, violinPath); equal to /api/clinical-data-violin-plots/fetch on 6 cases |
| STS-VI-5 | 🟡 | C | Box tooltip Median / Quartile 1 / Quartile 3; points carry no sample tooltip (values only reach the browser) |
| STS-VI-6 | 🟡 | C | A category's checkbox toggles the categorical filter; no range drag |
| STS-VI-7 | ✅ | C | Log Scale (Mutation Count only), Show Violin Plot, Show Box Plot; quartile columns in counts on log (the portal shows log-space, a bug) |

Under "Study View → filters, actions and tabs", the line #462 leaves (docs/PORTAL-PARITY.md:479):

  • The X vs Y tab's violin table for a numeric × categorical pair (STV-AC-7)

is ticked:

31-study-view-shell.md, row STV-AC-7 (as #462 leaves it):

| STV-AC-7 | ✅ | B | The X vs Y tab: two attribute selects (survival but OS_STATUS left out) and the portal's button for each pair (xVsYButton); two numeric add a density chart, numeric × categorical a violin table (ViolinCard) |

Preview

/lab?tab=explore&study=coadread_tcga_pan_can_atlas_2018: Add chart → X vs Y → Cancer Type Detailed and Diagnosis Age → Add violin/box plot table.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht

…t a numeric one (STS-VI-1…7)

Add chart › X vs Y now adds the portal's violin/box plot table for a numeric × categorical pair.
A row per category: the mirrored curve and box across the numeric attribute's range, # with a
checkbox that filters on the category, Median / Quartile 1 / Quartile 3; Hide # < 10; sortable
columns; Log Scale (Mutation Count), Show Violin Plot, Show Box Plot, Remove chart.

The numbers are cBioPortal's ViolinPlotServiceImpl's: quartiles by Apache Commons' Percentile
(position p(n + 1)), whiskers at the 1.5 × IQR fences when a value lies past them, outliers past
3 × IQR out of the curve and drawn as points, rows of seven values or fewer as points alone, the
curve a sum of Gaussians at 100 points with sigma 4 steps. They are computed in the browser
(lib/study-view-violin.ts) from per-category value counts Explore returns (buildViolinFacets:
values and counts, never ids), drawn without the numeric attribute's own filter and counted (#)
with it, as the portal's controller does. A peer's studies are named, not counted.

Verified: against cbioportal.org's /api/clinical-data-violin-plots/fetch, coadread Cancer Type
Detailed × Age, Sex × Mutation Count (linear and log), AJCC stage × FGA (13 rows), Sex × Age under
an Age range and under another filter: every row's #, quartiles, whiskers, curve (to 1e-9) and
point count equal. scripts/check-violin.ts (gate phase "violin tables") runs the SQL against the
fixture study and coadread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht
@vercel

vercel Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
cbiolab-genie Ready Ready Preview Nov 19, 2026 8:16pm UTC
cbiolab-new Ready Ready Preview Nov 19, 2026 8:16pm UTC
cohort-lab Ready Ready Preview Nov 19, 2026 8:16pm UTC

Request Review

<svg width={width} height={VIOLIN_HEIGHT} role="img" aria-label={r.category + ": median " + shown(r.box.median)}>
{ticks.map((t) => <line key={t.at} x1={x(t.at)} x2={x(t.at)} y1={0} y2={VIOLIN_HEIGHT} stroke={PORTAL_VIOLIN.grid} strokeDasharray="3,2" />)}
{showViolin && r.curve.length > 0 && <path d={violinPath(r.curve, width - 2 * PAD)} transform={"translate(" + PAD + ",0)"} fill={PORTAL_VIOLIN.curve} />}
{showBox && r.curve.length > 0 && <ViolinBox box={r.box} x={x} />}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A row whose curve is empty because sigma is 0 (every counted value across the table is the same, >7 samples) draws nothing at all: the box is gated on r.curve.length > 0 and points holds only outliers, which are none. violinTable's own comment says that case is "the box alone". Gate the box on the points-only rule (count <= POINTS_ONLY_MAX, e.g. a pointsOnly flag on the row) rather than on the curve's length.

Comment thread lib/study-view-violin.ts
const suspectLo = q1 - 1.5 * iqr, suspectHi = q3 + 1.5 * iqr, farLo = q1 - 3 * iqr, farHi = q3 + 3 * iqr;
const suspected = values.some((x) => x.v <= suspectLo || x.v >= suspectHi);
axisStart = Math.min(axisStart, min); axisEnd = Math.max(axisEnd, max);
const outlier = (v: number) => (v <= suspectLo && v <= farLo) || (v >= suspectHi && v >= farHi);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With IQR = 0 (q1 == q3, common for a mode-heavy attribute such as Mutation Count or a small integer), farLo == suspectLo == q1 and the <= / >= comparisons make every value equal to q1/q3 a far outlier. Those values are left out of the curve and expand (line 114) emits one <circle> per sample at the same x, so a category with 500 samples at the mode renders a near-empty curve plus 500 stacked dots. Please confirm the legacy comparison is inclusive at IQR 0; either way, draw outlier points once per distinct value. (v <= suspectLo && v <= farLo also reduces to v <= farLo.)

{ label: "Show Box Plot", checked: showBox, title: "draw each category's quartiles and whiskers", onClick: () => setShowBox(!showBox) },
{ label: "Remove chart", title: "stop drawing " + title, onClick: onRemove }]} />
</div>
<div className="xc-body">

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CLAUDE.md (UI conventions): "a change that waits on the server covers the figure with "updating…"" and "loading, empty and failed are three states". ViolinCard has no stale/busy state: checking a category refetches Explore while the table keeps showing the old # and quartiles, and a newly added table renders nothing until the answer arrives (page.tsx only maps facets already returned). The density cards in explore-charts.tsx show .xc-wait with "updating…"/"loading…"; this card needs the same.

const setViolins = (next: ViolinPair[]) => { violinChartsRef.current = next; setViolinCharts(next); fetchExplore(); };
const addViolinChart = (pair: ViolinPair) => {
if (violinCharts.some((p) => violinPairKey(p) === violinPairKey(pair))) return;
setViolins([...violinCharts, pair].slice(-VIOLIN_CHART_LIMIT));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding a 7th violin table silently drops the oldest (slice(-VIOLIN_CHART_LIMIT)), while the picker says "<title> added.", and the dropped table's filters stay in the draft, unlike Remove chart which clears them. CLAUDE.md: "nothing is dropped without saying so; a request past a limit is refused with the limit named". Refuse the add (disable the X vs Y button naming the limit of 6) instead of evicting.

Comment thread app/api/explore/route.ts
: undefined;
const mt = mutationTypeFacets ? { mutationTypeFacets } : {};
// a peer's studies are not counted in the violin tables either: its federation API has no such counts
const violinFacets = Array.isArray(body.violinCharts) && body.violinCharts.length

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

buildViolinFacets is awaited before buildExplore/buildExploreFederated even starts, so every Explore request carrying a violin table pays the violin query's latency serially in front of the main facets. It depends on nothing they produce: start it as a promise (like treatmentsP, with a .catch(() => undefined) mark) and await it at the end.

Comment thread lib/types.ts
* (`mutations`, the portal's # Mut) and the samples holding one (`samples`, its #), over the
* selection without this table's own filter. Freq is `samples` ÷ `total`, the selected samples.
*/
/**

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new ViolinFacet JSDoc was inserted between MutationTypeFacet's doc block and export interface MutationTypeFacet, so the Mutation Type Counts comment now sits orphaned above ViolinFacet's and MutationTypeFacet loses its doc. Move ViolinFacet (with its comment) above the MutationTypeFacet comment. Same pattern in lib/explore-selection.ts:150: the old chartValues doc line was kept above the new one, leaving two stacked JSDoc blocks.

const x = (v: number) => violinX(v, table.axis, width - 2 * PAD, PAD);
// a value as the reader reads it: Log Scale's ln(1 + v) turned back into a count
const shown = (v: number) => violinNumber(useLog ? Math.exp(v) - 1 : v);
const fold = (v: string) => v.trim().toLowerCase();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fold re-implements clinicalValueFold from lib/event-names.ts (already imported client-side by use-explore-state.ts). Use it so the checkbox's folding stays in step with the server's clinicalValueFoldSql if that rule ever changes.

const PAD = 5;

/** the column's grid: round values of the data's range, or on Log Scale round counts placed at ln(1 + count) */
function gridTicks(axis: [number, number], log: boolean): { at: number; label: string }[] {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CLAUDE.md (UI conventions): figures are drawn "with lib/chart/ — never a colour, size or tick rule of their own". gridTicks defines its own log tick rule (powers of 10 placed at ln(1+t)) and the svg hard-codes font size 9, point radius 3 and width 200 here. Put the log tick rule and these sizes in lib/chart (scale.ts / style.ts) beside PORTAL_VIOLIN.

const kept = violinRows(table.rows, Number.isFinite(minN) ? minN : 0);
if (sort.key === "n" && sort.desc) return kept;
const val = (r: ViolinRow): number | string => sort.key === "category" ? r.category : sort.key === "n" ? r.n : r.box[sort.key];
return [...kept].sort((a, b) => { const x = val(a), y = val(b); const c = x < y ? -1 : x > y ? 1 : 0; return sort.desc ? -c : c; });

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorting by category uses < on raw strings (case-sensitive, code-unit order), while the default order in violinRows uses localeCompare; e.g. lower-case categories sort after every capitalised one and ties in # aren't broken. Use localeCompare for the category key.

@alisman

alisman commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Review: pass. No blocking findings at edeae0ee.

Checked against legacy and the invariants:

  • Quartiles: Apache Percentile default (position p(n + 1), clamped), as ViolinPlotServiceImpl.
  • Whiskers and outliers: the same <= / >= 1.5 × IQR and 3 × IQR tests as ViolinPlotServiceImpl (lines 114–157). That includes the IQR = 0 case flagged inline, so that comment is not blocking: legacy draws such a row the same way.
  • Curve: 100 points, sigma 4 steps, ≤ 7 values as points only.
  • Unit: a patient's value is lifted to each sample via withSampleLevel. # counts the whole selection. The curve and box are drawn without the numeric attribute's own filter, as the portal's controller does.
  • Counts are aggregated in SQL by (category, value) with no ids, refused past 50,000 with the limit named.
  • Remove chart clears both attributes (violinChartRemoval, pinned by a planted bug).
  • check:violin runs the numbers against the fixture and coadread.

Inline comments, none blocking:

  • A row with no curve because every value is identical (sigma 0) draws nothing. Legacy can't build a Gaussian there either.
  • No "updating…" over the card. It rides the main Explore fetch like the clinical pies.
  • The 7th table silently drops the oldest (same pattern as assayCharts).
  • The violin query is awaited before buildExplore starts. It could be a promise like treatmentsP.
  • Detached MutationTypeFacet doc comment, a local fold() copy, the tick rule in the component, and a case-sensitive category sort.

Calling scripts/check-violin.ts from gate.sh with node --env-file=.env.local, as the npm script
did, keeps package.json out of the diff, which otherwise makes CI plant every bug.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q3ezTaCo6wHFVsML6Qd4ht
@alisman

alisman commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Re-review: pass. 56cd7e7 drops the check:violin npm script and has scripts/gate.sh run node --env-file=.env.local scripts/check-violin.ts directly, the same command the script ran; docs/TESTING.md follows. The PR no longer touches package.json, so planted-bugs runs the changed-files subset rather than all 714 mutants, which had hit the 50-minute timeout. No other changes. The earlier pass on the violin table stands.

# Conflicts:
#	app/globals.css
#	app/lab/page.tsx
#	app/lab/use-explore-state.ts
@alisman
alisman added this pull request to the merge queue Nov 19, 2026
Merged via the queue into master with commit 6758b00 Nov 19, 2026
19 of 20 checks passed
@alisman
alisman deleted the studyview-violin-table branch November 19, 2026 21:18
alisman added a commit that referenced this pull request Nov 19, 2026
- package.json: no check:evolution-annotation script. A new npm script makes
  the planted-bugs job plant every bug, past its timeout. scripts/gate.sh
  runs the check with node directly, as #470's does.
- lib/views/evolution/doc.ts: the DSL reference lists the table's
  `annotation` column and the result's `oncokbPin` (rule 4).
- lib/views/evolution/run.ts: a later page of the mutation table, a column's
  value list, and a page of the patient list name the OncoKB version
  (`oncokbPin`), as the first page does (rule 2). Tested, with a planted bug.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q3ezTVY3MHJRLp4DsZ9c7C

This branch was successfully deployed

1 active deployment
Preview – cohort-lab — e9921131 Deployed Nov 19, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant