-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcharts.js
More file actions
609 lines (567 loc) · 18.6 KB
/
Copy pathcharts.js
File metadata and controls
609 lines (567 loc) · 18.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
import { getCompInit } from '#rx'
import { Menu, getAncestorWithComputedStyle } from '#dom'
import { getNormalRoot } from '#filter/filter'
import { NumericModes, TermTypes } from '#shared/terms.js'
import { importPlot } from '#plots/importPlot.js'
class MassCharts {
static type = 'charts'
constructor(opts = {}) {
this.type = MassCharts.type
// stickyAncestor will attached to button data, to be used by menu.stickyPosition()
// when showing the menu tip near a clicked chart button
this.stickyAncestor = getAncestorWithComputedStyle(opts.holder.node(), 'position', new Set(['sticky', 'fixed']))
setRenderers(this)
}
async init(appState) {
this.dom = {
holder: this.opts.holder,
tip: new Menu({ padding: '0px', testid: 'sjpp-mass-nav-chartBtnMenu' }),
tooltip: new Menu({ padding: '4px' })
}
this.makeButtons(appState)
}
// TODO later add reactsTo() to react to filter change
getState(appState) {
const state = {
vocab: appState.vocab, // TODO delete it as vocabApi should be used instead
activeCohort: appState.activeCohort,
termfilter: appState.termfilter,
currentCohortChartTypes: getCurrentCohortChartTypes(appState),
termdbConfig: appState.termdbConfig
}
if (appState?.termfilter?.filter) {
state.filter = getNormalRoot(appState.termfilter.filter)
}
return state
}
main() {
this.dom.btns.style('display', d => (this.state.currentCohortChartTypes.includes(d.chartType) ? '' : 'none'))
}
getBtnLabel_dict(state) {
// has "queries" meaning presence of non-dictionary data types, use "Variables" to broaden scope and not limited to just "Dictionary"
return state.termdbConfig.queries ? 'Data Variables' : 'Data Dictionary'
}
getBtnLabel_regression(state) {
/* define button label based on conditions:
if ds allows multiple regression methods, use generic name, click btn will display menu of options
if ds allows just one method, directly show method name on button, click btn will show sandbox
*/
const lst = getCurrentCohortChartTypes(state)
if (!lst.includes('regression')) return '' // plot not supported. label doesn't matter as button will be hidden
const ms = []
if (lst.includes('linear')) ms.push('linear')
if (lst.includes('logistic')) ms.push('logistic')
if (lst.includes('cox')) ms.push('cox')
if (ms.length > 1) return 'Regression Analysis' // more than 1 methods. return general name
// only 1 method
return `${ms[0] == 'linear' ? 'Linear' : ms[0] == 'cox' ? 'Cox' : 'Logistic'} Regression`
}
getBtnLabel_sampleScatter(state) {
// define button label
const lst = getCurrentCohortChartTypes(state)
if (state.termdbConfig.scatterplots?.length == 1 && !lst.includes('dynamicScatter')) {
// has 1 premade plot and no dynamic scatter. just show premade plot name as button name
return state.termdbConfig.scatterplots[0].name
}
// either has >1 premade plots or dynamic scatter. show generic name
return 'Sample Scatter'
}
getBtnLabel_report(state) {
return state.termdbConfig.plotConfigByCohort?.default?.report?.name || 'Report'
}
getBtnLabel_summarizeMutationTerm(state, phrase) {
if (!state.termdbConfig.queries) return 'Not supported!' // the function always runs for all ds, thus must detect and guard against it; in such case the btn should not be shown
const t = []
if (state.termdbConfig.queries.snvindel) t.push('Mutation')
if (state.termdbConfig.queries.cnv) t.push('CNV')
if (state.termdbConfig.queries.svfusion) t.push('Fusion')
// todo customize Diagnosis
return `${t.length > 2 ? 'Alterations' : t.join('/')} vs ${phrase}`
}
}
export const chartsInit = getCompInit(MassCharts)
export function getActiveCohortStr(appState) {
if (appState?.termdbConfig?.selectCohort?.values) {
// dataset allows subcohort selection
if (!Number.isInteger(appState.activeCohort)) throw 'appState.activeCohort is not integer array index'
const activeCohortObject = appState.termdbConfig.selectCohort.values[appState.activeCohort]
if (!activeCohortObject) throw 'appState.activeCohort array index out of bound'
// get a valid cohort obj
return [...activeCohortObject.keys].sort().join(',')
}
// if not, is undefined
return ''
}
export function getCurrentCohortChartTypes(appState) {
const activeCohortStr = getActiveCohortStr(appState)
const chartTypesByCohort = structuredClone(appState.termdbConfig?.supportedChartTypes || {})
// {}, key is cohortstr, value is list of supported chart types under this cohort
return chartTypesByCohort[activeCohortStr] || ['summary']
}
function getChartTypeList(self, state) {
/* returns a list all possible chart types supported in mass
each char type will generate a button under the nav bar
a dataset can support a subset of these charts
allow some chart button objects to be dynamically generated based on state
design goal is that chart specific logic should not leak into mass UI
design idea is that a button click will trigger a callback to do one of following things
in which chart-type specific logic is not included
1. show dictionary tree
by calling showTree_select1term() or showTree_selectlst()
2. prep chart
by calling prepPlot()
3. display chart-specific menu by importing plot code using importPlot()
and call the imported function loadChartSpecificMenu()
.label:
text to show in the button
.chartType:
values are controlled
must include for deciding if to display a chart button for a dataset
e.g. cumulative incidence plot will require "condition" term to be present in a dataset
see main()
.clickTo:
callback to handle the button click event, may use any of the following renderer methods:
- self.tree_select1term()
will show a term tree to select a term
- self.prepPlot()
dispatch "plot_prep" action to produce a 'initiating' UI of this plot,
for user to fill in additional details to launch the plot
example: regression, table, scatterplot which requires user to select two terms
- self.plotCreate()
when using prepPlot this error was raised: No plot with id='${this.id}' found. Did you set this.id before this.api = getComponentApi(this). TODO consolidate
.usecase:{}
required for clickTo=tree_select1term
provide to termdb app
.config:{}
required for clickTo=prepPlot
describe private details for creating a chart of a particular type
to be attached to action and used by store
.updateActionBySelectedTerms:
optional callback. used for geneExpression and metabolicIntensity "intermediary" chart types which do not correspond to actual chart, but will route to an actual chart (summary/scatter/hierclust) based on number of selected terms. this callback will update the action based on selected terms to do the routing
TODO order of buttons is hardcoded, may allow to customize order
*/
const buttons = [
////////////////////// PROFILE PLOTS START //////////////////////
{
label: 'Polar',
chartType: 'profilePolar2',
clickTo: self.prepPlot,
config: { chartType: 'profilePolar2' }
},
{
label: 'Barchart',
clickTo: self.prepPlot,
chartType: 'profileBarchart2',
config: { chartType: 'profileBarchart2' }
},
{
label: 'Facility Radar',
chartType: 'profileRadarFacility2',
clickTo: self.loadChartSpecificMenu
},
{
label: 'Radar',
chartType: 'profileRadar2',
clickTo: self.loadChartSpecificMenu
},
{
label: 'Templates',
chartType: 'profileForms',
clickTo: self.showTree_select1term,
usecase: { target: 'profileForms', detail: 'tw' },
config: { chartType: 'profileForms' }
},
{
label: 'Templates 2',
chartType: 'profileForms2',
clickTo: self.loadChartSpecificMenu,
usecase: { target: 'profileForms2', detail: 'tw' },
config: { chartType: 'profileForms2' }
},
{
// Picker only — its menu renders a Module → Domain → chart-type matrix/list and creates the chosen plot.
label: 'Templates 3',
chartType: 'profileForms3',
clickTo: self.loadChartSpecificMenu
},
////////////////////// PROFILE PLOTS END //////////////////////
// rest are general plots applicable to all ds
{
label: self.getBtnLabel_dict(state),
clickTo: self.prepPlot,
chartType: 'dictionary',
config: {
chartType: 'dictionary'
}
},
{
// currently only used by gdc, so hardcoding correlation input label
// may allow for other labels if used by other datasets
label: 'Correlation Input',
clickTo: self.prepPlot,
chartType: 'summaryInput',
config: {
chartType: 'summaryInput'
}
},
{
label: self.getBtnLabel_report(state),
chartType: 'report',
clickTo: self.plotCreate,
config: { chartType: 'report' }
},
{
label: 'Sample View',
clickTo: self.prepPlot,
chartType: 'sampleView',
config: {
chartType: 'sampleView'
}
},
{
label: self.getBtnLabel_sampleScatter(state),
chartType: 'sampleScatter',
clickTo: self.loadChartSpecificMenu
},
{
label: 'Run Chart',
chartType: 'runChart2',
clickTo: self.loadChartSpecificMenu
},
{
label: 'Frequency Chart',
chartType: 'runChart2',
clickTo: self.showTree_select1term,
usecase: { target: 'runChart2', detail: 'xtw' }
},
{
label: 'Cumulative Incidence',
chartType: 'cuminc',
clickTo: self.showTree_select1term,
usecase: { target: 'cuminc', detail: 'term' }
},
{
label: 'Survival',
chartType: 'survival',
clickTo: self.showTree_select1term,
usecase: { target: 'survival', detail: 'term' }
},
{
label: self.getBtnLabel_regression(state),
chartType: 'regression',
clickTo: self.loadChartSpecificMenu
},
{
label: 'Sample Matrix',
chartType: 'matrix',
clickTo: self.loadChartSpecificMenu
},
{
label: 'Genome Browser',
chartType: 'genomeBrowser',
clickTo: self.loadChartSpecificMenu
},
// Commenting out this button since DE does not work without specifying two groups
//{
// label: 'Differential Expression',
// chartType: 'DEanalysis',
// clickTo: self.loadChartSpecificMenu
//},
{
label: 'Data Download',
clickTo: self.prepPlot,
chartType: 'dataDownload',
config: {
chartType: 'dataDownload',
terms: []
}
},
{
label: 'Facet Table',
clickTo: self.loadChartSpecificMenu,
chartType: 'facet',
config: {
chartType: 'facet'
}
},
{
label: 'Brain Imaging',
clickTo: self.loadChartSpecificMenu,
chartType: 'brainImaging',
config: {
chartType: 'brainImaging'
}
},
{
label: 'Single Cell Plot',
clickTo: self.prepPlot,
chartType: 'singleCellPlot',
config: {
chartType: 'singleCellPlot'
}
},
{
//This chart may be later on extended to support other gene expression data types
label: 'Gene Expression',
chartType: 'GeneExpInput',
clickTo: self.prepPlot,
config: {
chartType: 'GeneExpInput',
termType: TermTypes.GENE_EXPRESSION
}
},
{
label: 'Metabolite Intensity',
chartType: 'metaboliteIntensity',
clickTo: self.showTree_selectlst,
usecase: { target: 'metaboliteIntensity', detail: 'term' },
updateActionBySelectedTerms: (action, termlst) => {
const twlst = termlst.map(term => ({
term: structuredClone(term),
q: { mode: NumericModes.continuous }
}))
if (twlst.length == 1) {
// violin
action.config.chartType = 'summary'
action.config.term = twlst[0]
return
}
if (twlst.length == 2) {
// scatter
action.config.chartType = 'summary'
action.config.term = twlst[0]
action.config.term2 = twlst[1]
return
}
// 3 or more terms, launch clustering
action.config.chartType = 'hierCluster'
action.config.dataType = TermTypes.METABOLITE_INTENSITY
action.config.termgroups = [{ name: 'Metabolite Intensity Cluster', lst: twlst, type: 'hierCluster' }]
}
},
{
label: 'Protein Selection',
chartType: 'proteinView',
clickTo: self.loadChartSpecificMenu
},
{
label: 'Sample Selection',
chartType: 'proteomeAbundance',
clickTo: self.loadChartSpecificMenu
},
{
label: 'Bubble Chart',
chartType: 'animatedBubbleChart',
clickTo: self.plotCreate,
config: { chartType: 'animatedBubbleChart' }
},
{
label: 'Bubble Heatmap',
chartType: 'bubbleHeatmap',
clickTo: self.loadChartSpecificMenu
},
{
label: 'Brain Regional Proteome',
chartType: 'brainRegions',
clickTo: self.loadChartSpecificMenu
},
{
label: state.termdbConfig.queries?.geneRanking?.appName || 'Gene Ranking',
chartType: 'geneRanking',
clickTo: self.loadChartSpecificMenu
},
{
label: state.termdbConfig.numericDictTermCluster?.appName || 'Numeric Dictionary Term cluster',
chartType: 'numericDictTermCluster',
clickTo: self.loadChartSpecificMenu
},
{
label: 'Correlation Volcano',
chartType: 'correlationVolcano',
usecase: { target: 'correlationVolcano', detail: 'numeric' },
clickTo: self.showTree_select1term
},
{
label: 'GRIN2',
chartType: 'grin2',
config: { chartType: 'grin2' },
clickTo: self.prepPlot
},
{
label: self.getBtnLabel_summarizeMutationTerm(state, 'Disease Type'),
chartType: 'summarizeMutationDiagnosis', // type names of other similar charts should all begin with `summarize` to indcate they are based on summary plot
usecase: { target: 'summarizeMutationDiagnosis' },
clickTo: self.loadChartSpecificMenu
},
{
label: self.getBtnLabel_summarizeMutationTerm(state, 'Survival'),
chartType: 'summarizeMutationSurvival',
usecase: { target: 'summarizeMutationSurvival' },
clickTo: self.loadChartSpecificMenu
},
{
label: 'CNV vs Mutation',
chartType: 'summarizeMutationCnv',
usecase: { target: 'summarizeMutationCnv' },
clickTo: self.loadChartSpecificMenu
},
{
label: 'CNV vs GeneExp', // this is limited to cnv, and could be generalized to include snvindel/fusion
chartType: 'summarizeCnvGeneexp',
usecase: { target: 'summarizeCnvGeneexp' },
clickTo: self.loadChartSpecificMenu
},
{
label: 'GeneExp vs Survival',
chartType: 'summarizeGeneexpSurvival',
usecase: { target: 'summarizeGeneexpSurvival' },
clickTo: self.loadChartSpecificMenu
}
]
const renamedChartTypes = state?.termdbConfig.renamedChartTypes || {}
for (const btn of buttons) {
btn.stickyAncestor = self.stickyAncestor
if (renamedChartTypes[btn.chartType]) btn.label = renamedChartTypes[btn.chartType]
}
return buttons
}
function setRenderers(self) {
self.makeButtons = function (state) {
const chartTypeList = getChartTypeList(self, state)
self.dom.btns = self.dom.holder
.selectAll('button')
.data(chartTypeList)
.enter()
.append('button')
.attr('class', 'sjpp-chart-btn')
.attr('data-testid', d => `sjpp-chart-btn-${d.label.toLowerCase().replace(/\s/g, '-')}`)
.style('margin', '10px')
.style('padding', '10px 15px')
.style('border-radius', '20px')
.style('border-color', '#ededed')
.html(d => d.label)
.on('click', function (event, chart) {
self.dom.tip.clear().showunder(this)
chart.clickTo(chart, this)
})
.on('mouseover', (e, d) => {
if (d.tooltip) self.dom.tooltip.clear().showunder(e.target).d.text(d.tooltip)
})
.on('mouseleave', (e, d) => {
if (d.tooltip) self.dom.tooltip.hide()
})
}
/*
show termdb tree to select a term
once selected, dispatch "plot_create" action (with the selected term) to produce the plot
example: summary
*/
self.showTree_select1term = async chart => {
if (chart.usecase.label) {
self.dom.tip.d
.append('div')
.style('margin', '3px 5px')
.style('padding', '3px 5px')
.style('font-weight', 600)
.html(chart.usecase.label)
}
const action = {
type: 'plot_create',
id: getId(),
config: { chartType: chart.chartType, activeCohort: self.state.activeCohort }
}
if (chart.parentId) action.parentId = chart.parentId
const termdb = await import('../termdb/app')
termdb.appInit({
vocabApi: self.app.vocabApi,
holder: self.dom.tip.d.append('div'),
state: {
activeCohort: self.state.activeCohort,
nav: {
header_mode: 'search_only'
},
tree: { usecase: chart.usecase }
},
tree: {
click_term: term => {
// summary/survival/cuminc all expect config.term{} to be a termsetting object, but not term (which is confusing)
// thus convert term into a termwrapper (termsetting obj)
// tw.q{} is missing and will be fill in with default settings
const tw = term.term ? term : { term }
action.config[chart.usecase.detail] = tw
self.dom.tip.hide()
self.app.dispatch(action)
}
}
})
}
self.showTree_selectlst = async chart => {
if (chart.usecase?.label) {
self.dom.tip.d
.append('div')
.style('margin', '3px 5px')
.style('padding', '3px 5px')
.style('font-weight', 600)
.html(chart.usecase.label)
}
const action = {
type: 'plot_create',
id: getId(),
config: { chartType: chart.chartType } // NOTE if chartType is intermediary, action will be updated on term selection
}
const termdb = await import('../termdb/app')
self.dom.submenu = self.dom.tip.d.append('div')
termdb.appInit({
holder: self.dom.submenu,
vocabApi: self.app.vocabApi,
state: {
activeCohort: self.state.activeCohort,
nav: {
header_mode: 'search_only'
},
tree: { usecase: chart.usecase }
},
tree: {
submit_lst: termlst => {
const data = chart.processSelection ? chart.processSelection(termlst) : termlst
action.config[chart.usecase.detail] = data
if (chart.updateActionBySelectedTerms) chart.updateActionBySelectedTerms(action, termlst)
self.dom.tip.hide()
self.app.dispatch(action)
}
}
})
}
self.loadChartSpecificMenu = async chart => {
self.dom.tip.clear()
const _ = await importPlot(chart.chartType)
_.makeChartBtnMenu(self.dom.tip.d, self, chart.chartType)
}
self.prepPlot = async function (chart, btnNode) {
self.dom.tip.hide()
/* disable the clicked button while its chart loads so rapid clicks don't stack up plots.
app.dispatch() resolves only after the plot has fully rendered (incl. its data fetch); the
button is re-enabled once the load settles, on success or error. */
if (btnNode) btnNode.disabled = true
const action = { type: 'plot_prep', config: chart.config, id: getId() }
try {
await self.app.dispatch(action)
} finally {
if (btnNode) btnNode.disabled = false
}
}
self.plotCreate = function (chart) {
self.dom.tip.hide()
const action = { type: 'plot_create', config: chart.config, id: getId() }
self.app.dispatch(action)
}
}
// idPrefix to assign chart ID to distinguish between chart instances,
// will not be used if there is a user-assigned or recovered session chart ID;
// the random string is in case this code is bundled as independent code in
// different chunks
const idPrefix = '_CHART_AUTOID_' + Math.random().toString().slice(-6) + '_'
let id = Date.now().toString().slice(-6)
function getId() {
return idPrefix + id++
}