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
91 changes: 47 additions & 44 deletions app/lab/explore-sections.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { barFigureSvg, pieFigureSvg, type FigureBar, type PieSlice } from "../..
import { caseFileAction, figureActions, runCaseFile } from "./chart-files.ts";
import { caseFileName } from "../../lib/study-view-case-files.ts";
import { chartOffered } from "../../lib/study-view-config.ts";
import { addChartLines, assayTabs, bulkButtons, genomicChartLines, SPECIAL_CHART_KEYS, specialChartsShown } from "../../lib/study-view-add-chart.ts";
import { addChartLines, assayTabs, bulkButtons, genomicChartLines, geneTabView, SPECIAL_CHART_KEYS, specialChartsShown } from "../../lib/study-view-add-chart.ts";
import { StudyHeader } from "./explore-study-header.tsx";
import type { CohortDef } from "../../lib/types.ts";
import { alteredHeaderTip, appliedLines, queuedQuery, defaultGeneSort, geneHeaderTips, geneSelection, geneFreqText, geneRowMatches, geneTableName, geneTableTitle, geneTableTsv, intersectionRefusal, nextGeneSort, profiledSamples, qValueIcon, sortGeneRows, type GeneSort, type GeneSortColumn } from "../../lib/study-view-gene-tables.ts";
Expand Down Expand Up @@ -299,7 +299,7 @@ export function ExploreBar({ ctx }: { ctx: ExploreCtx }) {
}

export function AddChartDialog({ ctx }: { ctx: ExploreCtx }) {
const { addChartOpen, setAddChartOpen, addSeqFilter, clearAttributeFilters, attrCoverage, attrKey, chartGene, chartTab, clinFilter, exStudies, exploreBusy, fetchExplore, geneChartInput, openCustomManager, geneCharts, mutationTypeCharts, chartChecked, setChartsChecked, seq, seqReady, setAttrCoverage, setChartTab, setClinFilter, setGeneChartInput, setSeq, treatmentEventType, unchartGene } = ctx;
const { addChartOpen, setAddChartOpen, addSeqFilter, clearAttributeFilters, attrCoverage, attrKey, chartTab, clinFilter, exStudies, exploreBusy, fetchExplore, openCustomManager, chartChecked, setChartsChecked, seq, seqReady, setAttrCoverage, setChartTab, setClinFilter, setSeq, treatmentEventType } = ctx;
const explore = ctx.explore!;
return <>
{explore && (
Expand Down Expand Up @@ -442,47 +442,7 @@ export function AddChartDialog({ ctx }: { ctx: ExploreCtx }) {
</div>
);
})()}
{chartTab === "gene" && (
<div>
<div className="row baseline g5">
<Input type="search" className={SEARCH} placeholder="chart a gene (e.g. EGFR)" autoFocus
value={geneChartInput} disabled={exploreBusy}
onChange={e => setGeneChartInput(e.target.value)}
onKeyDown={e => { if (e.key === "Enter") chartGene(geneChartInput); }} />
<Button variant="outline" size="sm" disabled={!geneChartInput.trim() || exploreBusy} onClick={() => chartGene(geneChartInput)}
data-tip="its mutation and copy-number status">Add</Button>
<Button variant="outline" size="sm" disabled={!geneChartInput.trim() || exploreBusy} onClick={() => chartGene(geneChartInput, true)}
data-tip="a table of its mutations by type: mutations, samples, and their share of the selected samples">Add mutation types</Button>
</div>
{!geneCharts.length && !mutationTypeCharts.length && (
<p className="note flush mt-1.5">
Name a gene to see how many patients are altered, unaltered, or <strong>never tested</strong> for
it. The third is the one a frequency cannot show: in GENIE public, 86,353 patients are on no panel
covering EGFR copy number.
</p>
)}
{geneCharts.map(g => (
<span key={g} className="qchip mr-1">
{g}
<Button variant="ghost" size="icon-xs" className={CHIP_X} data-tip={"stop charting " + g} aria-label={"stop charting " + g}
onClick={() => unchartGene(g)}><X /></Button>
</span>
))}
{mutationTypeCharts.map(g => (
<span key={"types|" + g} className="qchip mr-1">
{g}<span className="meta"> · mutation types</span>
<Button variant="ghost" size="icon-xs" className={CHIP_X} data-tip={"stop charting " + g + "'s mutation types"} aria-label={"stop charting " + g + "'s mutation types"}
onClick={() => unchartGene(g, true)}><X /></Button>
</span>
))}
{geneCharts.length + mutationTypeCharts.length > 0 && (
<p className="note flush mt-1.5">
Each chart is drawn as its own tile in the facet grid, alongside the clinical
attributes — close this dialog to see them.
</p>
)}
</div>
)}
{chartTab === "gene" && <GeneChartPicker ctx={ctx} />}
{chartTab === "genomic" && <GenomicCharts ctx={ctx} />}
{chartTab.startsWith("assay:") && <AssayChartPicker ctx={ctx} assayType={chartTab.slice("assay:".length)} />}
{chartTab === "derived" && (explore.events.length === 0 ? (
Expand Down Expand Up @@ -1064,6 +1024,49 @@ function ClinicalFacet({ c, ctx }: { c: NonNullable<ExploreCtx["explore"]>["clin
);
}

/**
* The Add chart dialog's gene tab, as the portal's (STV-AC-5): a profile, "<name> (N samples)"; for
* mutations, Mutated vs Wild Type or Mutation Type; a gene; one chart per gene and profile.
*/
function GeneChartPicker({ ctx }: { ctx: ExploreCtx }) {
const { chartGene, unchartGene, geneChartInput, setGeneChartInput, exploreBusy, geneCharts, geneKinds, mutationTypeCharts } = ctx;
const [profile, setProfile] = useState<"mutation" | "cna">("mutation");
const [byType, setByType] = useState(false);
const { profiles, current, kind, note, chips } = geneTabView(ctx.explore!.dataTypes || [], { genes: geneCharts, kinds: geneKinds, types: mutationTypeCharts }, profile, byType);
const add = () => chartGene(geneChartInput, kind);
return (
<div>
{/* the charted genes' chips stay, so a chart can be removed whatever the selection holds */}
{!current ? <p className="note mt-0 mb-3">{note}</p> : <div className="row baseline g5 flex-wrap">
<Choice className="w-80" value={current.kind} onChange={(v) => setProfile(v as "mutation" | "cna")} title="the profile the chart reads"
options={profiles.map((p) => [p.kind, p.label] as const)} />
{current.kind === "mutation" && <Choice className="w-48" value={byType ? "types" : "mutated"} onChange={(v) => setByType(v === "types")}
title="a gene's mutated and wild-type samples, or its mutations by type" options={[["mutated", "Mutated vs Wild Type"], ["types", "Mutation Type"]] as const} />}
<Input type="search" className={SEARCH} placeholder="chart a gene (e.g. EGFR)" autoFocus aria-label="gene to chart"
value={geneChartInput} disabled={exploreBusy}
onChange={(e) => setGeneChartInput(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") add(); }} />
<Button variant="outline" size="sm" disabled={!geneChartInput.trim() || exploreBusy} onClick={add}>Add Chart</Button>
</div>}
{current && !chips.length && (
<p className="note flush mt-1.5">
Name a gene to see how many patients are altered, unaltered, or <strong>never tested</strong> for
it. The third is the one a frequency cannot show: in GENIE public, 86,353 patients are on no panel
covering EGFR copy number.
</p>
)}
{chips.map((c) => (
<span key={c.gene + "|" + c.kind} className="qchip mr-1">
{c.gene}<span className="meta"> · {c.text}</span>
<Button variant="ghost" size="icon-xs" className={CHIP_X} data-tip={"stop charting " + c.gene + "'s " + c.text} aria-label={"stop charting " + c.gene + "'s " + c.text}
onClick={() => unchartGene(c.gene, c.kind)}><X /></Button>
</span>
))}
{chips.length > 0 && <p className="note flush mt-1.5">Each chart is drawn as its own tile in the facet grid, alongside the clinical attributes — close this dialog to see them.</p>}
</div>
);
}

/** the Add chart dialog's Genomic tab (STV-AC-2): the gene tables, Data Types and the density, each shown unless unchecked */
/** the Genomic tab's rows for this selection (STV-AC-2, STV-AC-4); none hides the tab, as the portal's */
function genomicLines(explore: NonNullable<ExploreCtx["explore"]>, attrKey: ExploreCtx["attrKey"]) {
Expand Down Expand Up @@ -1220,7 +1223,7 @@ export function GeneFacets({ ctx }: { ctx: ExploreCtx }) {
const { addClauses, geneStatesClauses } = ctx;
const explore = ctx.explore!;
return <>
{(explore.geneFacets || []).map(f => {
{(explore.geneFacets || []).filter((f) => (ctx.geneKinds[f.gene] || []).includes(f.type)).map(f => {

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.

nit: Per-kind charting is done by hiding facets client-side; the server still computes both the mutation and CNA facets for every charted gene.

Charting only mutations for six genes still runs six CNA facet queries per study on every Explore request (federated: per study, per connection) whose results are discarded. Sending the kinds with geneCharts and having geneStateFacets compute only the asked-for type removes the waste and the client filter.

const apply = (states: string[]) => geneStatesClauses(f.gene, f.type, states);
// the copy-number levels the portal draws: none at 0 (the drivers-only chart keeps its fixed rows)
const states = f.type === "CNA" && !explore.drivers ? f.states.filter((st) => st.n > 0) : f.states;
Expand Down
6 changes: 5 additions & 1 deletion app/lab/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { currentLinkUrlMax, linkParams, writeSearch } from "../_links/link-state
import { TAB_PARAM, readFilters, readTab, writeTab, type StudyViewTab } from "../../lib/study-view-url.ts";
import { useLinkParams } from "../_links/use-link.ts";
import { ExploreCharts } from "./explore-charts";
import { geneChartCount } from "../../lib/study-view-add-chart.ts";
import type { UnpackedContract } from "../../lib/oncoprint-binary.ts";
import type { AnalysisDoc, CohortDef } from "../../lib/types.ts";
import { storeCohortLists, storeDocLists } from "./id-sets-client.ts";
Expand Down Expand Up @@ -630,7 +631,10 @@ export default function AnalysisPage() {
return shown < all && <span className="meta" data-charted={shown + "/" + all}>
{shown} of {all.toLocaleString()} clinical attributes charted — the rest are in Add chart</span>;
})()}
{geneCharts.length + mutationTypeCharts.length > 0 && <span className="meta">{geneCharts.length + mutationTypeCharts.length} gene chart{geneCharts.length + mutationTypeCharts.length === 1 ? "" : "s"}</span>}
{(() => {
const n = geneChartCount({ genes: geneCharts, kinds: exploreState.geneKinds, types: mutationTypeCharts });
return n > 0 && <span className="meta">{n} gene chart{n === 1 ? "" : "s"}</span>;
})()}
{(() => {
// drivers only where every selected study has OncoKB calls here; the server refuses the rest too
const without = exStudies.filter((id) => studies.find((x) => x.id === id)?.oncokb === false);
Expand Down
34 changes: 19 additions & 15 deletions app/lab/use-explore-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { useSaved } from "../_saved/saved-context.tsx";
import { useEffect, useRef, useState } from "react";
import { normalizeDef } from "./pills";
import type { AnalysisDoc, Clause, CohortDef, DerivedRequest, NumericBin, PartitionArm, PartitionDef } from "../../lib/types.ts";
import { GENOMIC_CHARTS, withoutAttribute } from "../../lib/study-view-add-chart.ts";
import { GENOMIC_CHARTS, geneChartsAsked, geneChartsChanged, withoutAttribute, type GeneChartKind } from "../../lib/study-view-add-chart.ts";
import { foldEventNames, treatmentEventOf } from "../../lib/event-names.ts";
import { type SplitSpec } from "./partitions.tsx";
import { armsFromSelection, withoutChart, comparisonCohorts, type ChartKey } from "../../lib/partition-arms.ts";
Expand Down Expand Up @@ -626,23 +626,27 @@ export function useExploreState(page: ExplorePage) {
const geneStatesClauses = (gene: string, type: "MUTATION" | "CNA", states: string[]): { clauses: any[] } | { why: string } =>
geneStatesClausesFor(gene, type, states, !!explore?.drivers);

/** chart a gene: its mutation and copy-number status, or (`types`) its mutations by type, as the portal's Add chart offers */
const chartGene = (raw: string, types = false) => {
/** which of a charted gene's two status charts are shown (STV-AC-5: one chart per gene and profile) */
const [geneKinds, setGeneKinds] = useState<Record<string, ("MUTATION" | "CNA")[]>>({});
const geneKindsRef = useRef<Record<string, ("MUTATION" | "CNA")[]>>({});
const changeGeneChart = (g: string, kind: GeneChartKind, on: boolean) => {
// read from the refs, so two changes before a render both count
const before = { genes: geneChartsRef.current, kinds: geneKindsRef.current, types: mutationTypeChartsRef.current };
const next = geneChartsChanged(before, g, kind, on);
geneChartsRef.current = next.genes; setGeneCharts(next.genes);

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.

nit: (app/lab/page.tsx:633) The 'N gene charts' count still adds geneCharts.length, which counts genes, not charts, now that one gene can hold a mutation and a copy-number chart.

Add KRAS mutations and KRAS copy number: two tiles are drawn but the header reads '1 gene chart'.

mutationTypeChartsRef.current = next.types; setMutationTypeCharts(next.types);
geneKindsRef.current = next.kinds; setGeneKinds(next.kinds);
// another kind of a gene already counted is drawn from the answer in hand
if (geneChartsAsked(before, next)) fetchExplore();
};
/** chart a gene for one profile, as the portal's Add chart does: its mutation status, its mutations by type, or its copy number */
const chartGene = (raw: string, kind: GeneChartKind) => {
const g = String(raw || "").toUpperCase().trim();
if (!/^[A-Z0-9][A-Z0-9.-]{0,19}$/.test(g)) return;
const held = types ? mutationTypeCharts : geneCharts;
const next = held.includes(g) ? held : [...held, g].slice(-6);
if (types) { mutationTypeChartsRef.current = next; setMutationTypeCharts(next); }
else { geneChartsRef.current = next; setGeneCharts(next); }
setGeneChartInput("");
fetchExplore();
};
const unchartGene = (g: string, types = false) => {
const next = (types ? mutationTypeCharts : geneCharts).filter((x) => x !== g);
if (types) { mutationTypeChartsRef.current = next; setMutationTypeCharts(next); }
else { geneChartsRef.current = next; setGeneCharts(next); }
fetchExplore();
changeGeneChart(g, kind, true);
};
const unchartGene = (g: string, kind: GeneChartKind) => changeGeneChart(g, kind, false);

const chartAssay = (profileType: string, entity: string) => {
if (assayCharts.some((c) => c.profileType === profileType && c.entity === entity)) return;
Expand Down Expand Up @@ -875,7 +879,7 @@ export function useExploreState(page: ExplorePage) {
if (target) addCohortToView(target, n, def, studyHint);
};

return { chartBins, setChartBins, applyOrSay, urlRead, openEditCohort, saveEditedCohort, exMsg, setExMsg, splittingBy, setSplittingBy, addMode, setAddMode, customTab, setCustomTab, saving, setSaving, savingFeature, setSavingFeature, addChartOpen, setAddChartOpen, chartTab, setChartTab, cName, setCName, cDefText, setCDefText, exploring, explore, exploreBusy, sQuery, setSQuery, sCaps, setSCaps, exStudies, setExStudies, exPanelOpen, setExPanelOpen, exSel, exFetchTimer, exDraftStudies, setExDraftStudies, geneCharts, setGeneCharts, geneChartsRef, drivers, setDrivers, callOql, exDerived, setExDerived, exDerivedRef, geneChartInput, setGeneChartInput, studyChipsOpen, setStudyChipsOpen, geneFilter, setGeneFilter, queuedGenes, setQueuedGenes, toggleQueuedGene, clinFilter, setClinFilter, chartChecked, setChartsChecked, attrCoverage, setAttrCoverage, seq, setSeq, barDef, barDefaultName, analyzeDraft, viewPatients, compareQuantiles, selectionArmCount, compareSelection, compareItems, openSaveDialog, confirmSave, openCustomManager, saveDraftAsFeature, confirmSaveFeature, parseDraft, attrKey, visibleClinical, attrsForBar, fetchExplore, addClause, addClauses, toggleBar, togglePieValue, toggleNaValue, selectBars, geneStatesClauses, toggleLogScale, addBinEdges, addDensitySelection, chartGene, unchartGene, mutationTypeCharts, assayCharts, chartAssay, unchartAssay, exploreEventTypes, treatmentEventType, TREATMENT_DERIVED_KINDS, derivedOn, toggleDerived, seqSelector, seqReady, addSeqFilter, removeDraftClause, clearAttributeFilters, clearGeneTableFilter, draftScaffold, clearDraft, setExploreStudies, exploreStudy, analyzeStudy, addDataToStudy, openAddCohort, closeAddCohort, addDraftToAnalysis };
return { chartBins, setChartBins, applyOrSay, urlRead, openEditCohort, saveEditedCohort, exMsg, setExMsg, splittingBy, setSplittingBy, addMode, setAddMode, customTab, setCustomTab, saving, setSaving, savingFeature, setSavingFeature, addChartOpen, setAddChartOpen, chartTab, setChartTab, cName, setCName, cDefText, setCDefText, exploring, explore, exploreBusy, sQuery, setSQuery, sCaps, setSCaps, exStudies, setExStudies, exPanelOpen, setExPanelOpen, exSel, exFetchTimer, exDraftStudies, setExDraftStudies, geneCharts, setGeneCharts, geneChartsRef, drivers, setDrivers, callOql, exDerived, setExDerived, exDerivedRef, geneChartInput, setGeneChartInput, studyChipsOpen, setStudyChipsOpen, geneFilter, setGeneFilter, queuedGenes, setQueuedGenes, toggleQueuedGene, clinFilter, setClinFilter, chartChecked, setChartsChecked, attrCoverage, setAttrCoverage, seq, setSeq, barDef, barDefaultName, analyzeDraft, viewPatients, compareQuantiles, selectionArmCount, compareSelection, compareItems, openSaveDialog, confirmSave, openCustomManager, saveDraftAsFeature, confirmSaveFeature, parseDraft, attrKey, visibleClinical, attrsForBar, fetchExplore, addClause, addClauses, toggleBar, togglePieValue, toggleNaValue, selectBars, geneStatesClauses, toggleLogScale, addBinEdges, addDensitySelection, chartGene, unchartGene, geneKinds, mutationTypeCharts, assayCharts, chartAssay, unchartAssay, exploreEventTypes, treatmentEventType, TREATMENT_DERIVED_KINDS, derivedOn, toggleDerived, seqSelector, seqReady, addSeqFilter, removeDraftClause, clearAttributeFilters, clearGeneTableFilter, draftScaffold, clearDraft, setExploreStudies, exploreStudy, analyzeStudy, addDataToStudy, openAddCohort, closeAddCohort, addDraftToAnalysis };
}

export type ExploreState = ReturnType<typeof useExploreState>;
Loading
Loading