-
Notifications
You must be signed in to change notification settings - Fork 1
/
plco.js
2516 lines (2323 loc) · 93.1 KB
/
plco.js
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file JS SDK for NCI DCEG's PLCO API. 〜( ̄▽ ̄〜)
*
* @version 1.0
* @author Eric Ruan, Erika Nemeth, Lorena Sandoval, Jonas Almeida
* @copyright 2021
*/
console.log('plco.js loaded')
/* plco = {
date: new Date()
}
*/
/**
* Main global portable module.
* @namespace plco
* @property {Function} defineProperties - {@link plco.defineProperties}
* @property {Function} explorePhenotypes - {@link plco.explorePhenotypes}
* @property {Function} loadScript - {@link plco.loadScript}
* @property {Function} saveFile - {@link plco.saveFile}
*/
plco = async () => {
// plco.loadScript("https://cdn.plot.ly/plotly-latest.min.js")
// console.log("plotly.js loaded")
plco.loadScript("https://episphere.github.io/plotly/epiPlotly.js")
plco.addStyle()
}
/**
* TEMP work-around for the CORS issue, do NOT use in the final SDK.
*
* Instead, fetch the blob from the API and use a blob link just like in jmat.
*
* Modified from https://github.com/jonasalmeida/jmat.
* @param {string} url The download link.
* @returns {HTMLAnchorElement} HTMLAnchorElement.
*/
plco.saveFile = (url) => {
// TODO downloadgwas is not up yet, so i will make change later once its fixed
url = url || 'https://downloadgwas.cancer.gov/j_breast_cancer.tsv.gz'
let a = document.createElement('a')
a.href = url
a.target = '_blank'
a.click()
return a
}
/**
* Saves a JSON as a .json file.
* @param {object} contents A JS object.
* @param {string} fileName The name of the file without extensions.
* @returns {HTMLAnchorElement} HTMLAnchorElement.
*/
plco.downloadJSON = (contents, fileName = 'plot') => {
const a = document.createElement('a')
//a.href = URL.createObjectURL(new Blob([JSON.stringify(JSON.parse(contents))], {
a.href = URL.createObjectURL(new Blob([JSON.stringify(contents)], {
type: 'text/plain'
}))
a.setAttribute('download', fileName + '.json')
a.click()
return a
}
/**
* Adds a style tag containing css for some plot elements.
*/
plco.addStyle = () => {
const style = document.createElement('style')
style.innerHTML = `
.loader {
border: 16px solid #f3f3f3; /* Light grey */
border-top: 16px solid #3498db; /* Blue */
border-radius: 50%;
width: 120px;
height: 120px;
animation: spin 2s linear infinite;
position: absolute;
z-index: 10;
top: 50%;
left: 40%;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`
window.onload = (_) => {
document.head.appendChild(style)
}
}
plco.addDownloadLink = (id, f) => {
if (document.getElementById(id + 'download-json')) {
document.getElementById(id + 'download-json').remove()
}
const div = document.createElement('div')
div.id = id + 'download-json'
const button = document.createElement('button')
button.innerHTML = 'download json'
button.onclick = (async (_) => {
let data = await (f())
plco.downloadJSON(data)
})
const supElement = document.createElement('sup')
supElement.innerHTML = `<a target='_blank' href='https://episphere.github.io/plot/'>plot</a>`
div.appendChild(button)
div.appendChild(supElement)
document.getElementById(id).appendChild(div)
}
/**
* Adds a key-value pair as specified in `m_fields` and `o_fields` to `obj` if the key does not already exist.
* @param {object} obj An object.
* @param {object} m_fields Mandatory fields.
* @param {object} [o_fields={}] Optional fields. Same as `m_fields`, but will not add in the key-value pair if value is undefined.
*/
plco.defineProperties = (obj, m_fields, o_fields = {}) => {
Object.keys(m_fields).forEach((key) => {
if (typeof obj[key] === 'undefined') {
obj[key] = m_fields[key]
}
})
Object.keys(o_fields).forEach((key) => {
if (
typeof obj[key] === 'undefined' &&
typeof o_fields[key] !== 'undefined'
) {
obj[key] = o_fields[key]
}
})
}
/**
* Creates and attaches a new script tag to head with script src pointing at `url`.
* @param {string} url
* @param {string} host
* @returns {HTMLScriptElement} HTMLScriptElement
*/
plco.loadScript = async (url, host) => {
let s = document.createElement('script')
s.src = url
return document.head.appendChild(s)
}
// plco.plotTest = async (
// chr = 1,
// div,
// url = 'https://exploregwas-dev.cancer.gov/plco-atlas/api/\
// summary?phenotype_id=3080&sex=female&ancestry=east_asian&p_value_nlog_min=2&raw=true'
// ) => {
// let xx = await (await fetch(url)).json()
// div = div || document.createElement('div')
// let dt = xx.data.filter(x => x[4] == chr)
// trace = {
// x: dt.map(d => d[5]),
// y: dt.map(d => d[6]),
// mode: 'markers',
// type: 'scatter'
// }
// let layout = {
// title: `Chromosoome ${chr}`,
// xaxis: {
// title: 'position'
// },
// yaxis: {
// title: '-log(p)'
// }
// }
// plco.Plotly.newPlot(div, [trace], layout)
// return div
// }
// plco.typeCheckAttributes = (obj = {}) => {
// const typeKey = {
// phenotype_id: 'integer',
// raw: 'string'
// }
// Object.keys(obj).forEach((key) => {
// if (typeKey[key] === 'string' && typeof obj[key] !== 'string') {
// throw new TypeError(`${key} is not of type ${typeKey[key]}`)
// } else if (typeKey[key] === 'integer' && !Number.isInteger(obj[key])) {
// throw new TypeError(`${key} is not of type ${typeKey[key]}`)
// }
// })
// }
/**
* Provides a way to explore all the available phenotypes.
* @param {boolean} [flatten=false] If 'true', returns an array of objects instead of a tree.
* @param {boolean} [mini=false] If 'true', removes keys from the objects to provide a condensed view.
* @param {boolean} [graph=false] If 'true', returns a Plotly chart instead of an array of objects.
* @param {string} div_id Used when graph is 'true', plots a Plotly chart at that container.
* @param {object} [customLayout={}] _Optional_. Contains Plotly supported layout key-values pair that will overwrite the default layout. Commonly overwritten values may include height and width of the graph. See: https://plotly.com/javascript/reference/layout/ for more details. Also, set `to_json` to true to see what the default layout is.
* @param {object} [customConfig={}] _Optional_. Contains Plotly supported config key-values pair that will overwrite the default config. See: https://github.com/plotly/plotly.js/blob/master/src/plot_api/plot_config.js#L22-L86 for full details.
* @returns An array of objects.
*/
plco.explorePhenotypes = async (
flatten = false,
mini = false,
graph = false,
div_id,
customLayout = {},
customConfig = {},
) => {
let phenotypes_json = await plco.api.phenotypes()
if (flatten) {
let queue = []
let r = []
for (let i = 0; i < phenotypes_json.length; i++) {
let root = phenotypes_json[i]
queue.push(root)
while (true) {
let removed = queue.splice(0, 1)[0]
if (removed === undefined) break
r.push(removed)
if (removed.children === undefined) continue
else {
if (Array.isArray(removed.children)) {
for (let j = 0; j < removed.children.length; j++) {
queue.push(removed.children[j])
}
} else {
queue.push(removed.children)
}
}
}
}
phenotypes_json = r
for (let i = 0; i < phenotypes_json.length; i++) {
let obj = phenotypes_json[i]
delete obj.children
}
}
if (mini) {
let queue = []
for (let i = 0; i < phenotypes_json.length; i++) {
let root = phenotypes_json[i]
queue.push(root)
while (true) {
let removed = queue.splice(0, 1)[0]
if (removed === undefined) break
delete removed.color
delete removed.import_date
delete removed.type
delete removed.age_name
delete removed.import_count
delete removed.parent_id
if (removed.children === undefined) continue
else {
if (Array.isArray(removed.children)) {
for (let j = 0; j < removed.children.length; j++) {
queue.push(removed.children[j])
}
} else {
queue.push(removed.children)
}
}
}
}
}
if (graph) {
// https://plotly.com/javascript/sunburst-charts/
let div = document.getElementById(div_id)
if (!div) {
div = document.createElement('div')
div.id = div_id
document.body.appendChild(div)
}
phenotypes_json = await plco.explorePhenotypes(true, false, false)
const data = [{
type: "sunburst",
ids: phenotypes_json.map(phenotype => phenotype.id),
labels: phenotypes_json.map(phenotype => phenotype.display_name),
parents: phenotypes_json.map(phenotype => phenotype.parent_id ? phenotype.parent_id : ''),
values: phenotypes_json.map(phenotype => phenotype.participant_count ? phenotype.participant_count : 0),
outsidetextfont: { size: 20, color: "#377eb8" },
leaf: { opacity: 0.6 },
marker: { line: { width: 2 } },
hovertext: phenotypes_json.map(phenotype => 'phenotype_id: ' + phenotype.id),
hoverinfo: 'label+text+value',
textposition: 'inside',
insidetextorientation: 'radial',
}]
const layout = {
margin: { l: 0, r: 0, b: 0, t: 0 },
width: 800,
height: 800,
sunburstcolorway: phenotypes_json.map(phenotype => phenotype.color).filter(Boolean),
...customLayout,
}
plco.Plotly.newPlot(div, data, layout, customConfig)
div.on('plotly_click', async ({ event, points }) => {
if (event.altKey) {
const part = await plco.api.participants({}, points[0].id, 'value,ancestry,sex', 0)
function helper(totalObject, cur, property) {
if (!totalObject['count_' + cur[property]] && cur[property] != null) {
const num = Number.parseInt(cur.counts)
if (isNaN(num))
totalObject['count_' + cur[property]] = 4
else
totalObject['count_' + cur[property]] = num
} else if (cur[property] != null) {
const num = Number.parseInt(cur.counts)
if (isNaN(num))
totalObject['count_' + cur[property]] = totalObject['count_' + cur[property]] + 4
else
totalObject['count_' + cur[property]] = totalObject['count_' + cur[property]] + num
}
}
function convertRowMajortoColMajor(numOfRows, numOfCols, arrays) {
let matrix = []
for (let i = 0; i < numOfCols; i++) {
matrix.push([])
for (let j = 0; j < numOfRows; j++) {
matrix[i].push(arrays[j][i])
}
}
return matrix
}
const data =
part.data.reduce((prev, cur) => {
const found = prev.find(obj => obj.value === cur.value)
if (!found) {
let addToArray = {
value: cur.value,
count: isNaN(Number.parseInt(cur.counts)) ? 4 : Number.parseInt(cur.counts),
}
helper(addToArray, cur, 'sex')
helper(addToArray, cur, 'ancestry')
prev.push(addToArray)
} else {
found.count = found.count +
(isNaN(Number.parseInt(cur.counts)) ? 4 : Number.parseInt(cur.counts))
helper(found, cur, 'sex')
helper(found, cur, 'ancestry')
}
return prev
}, [])
console.table(data)
const cellsVal = data.map(obj => Object.values(obj))
const cellsValPercent = data.map(obj => {
const newObj = {}
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
let k = keys[i]
if (k === 'count') {
const totalCount = data.reduce((total, cur) => total + cur.count, 0)
newObj[k] = Math.round(Number.parseInt(obj[k]) / Number.parseInt(totalCount) * 100) + '%'
} else if (k === 'value')
newObj[k] = obj[k]
else
newObj[k] = Math.round(Number.parseInt(obj[k]) / Number.parseInt(obj.count) * 100) + '%'
}
return Object.values(newObj)
})
const headerVal = Object.keys(data[0])
const trace = [{
type: 'table',
columnwidth: headerVal.map((_) => 150),
header: {
values: headerVal,
fill: { color: "#d3d3d3" },
}, cells: {
values: convertRowMajortoColMajor(
cellsVal.length, cellsVal[0].length || 0, cellsVal)
}
}]
const layout = {
updatemenus: [{
y: 1.0,
yanchor: 'top',
buttons: [{
method: 'restyle',
args: [{
cells: {
values: convertRowMajortoColMajor(
cellsVal.length, cellsVal[0].length || 0, cellsVal)
}
}],
label: 'Normal',
}, {
method: 'restyle',
args: [{
cells: {
values: convertRowMajortoColMajor(
cellsVal.length, cellsVal[0].length || 0, cellsValPercent)
}
}],
label: 'Percentage',
}],
}]
}
let div2 = document.getElementById(div_id + 'table')
if (!div2) {
div2 = document.createElement('div')
div2.id = div_id + 'table'
document.body.appendChild(div2)
}
div2.innerHTML = ''
plco.Plotly.newPlot(div2, trace, layout)
}
})
return phenotypes_json
}
return phenotypes_json
}
/**
* Fetches the result of the `url` from localForage if it exists else calls a HTTP request to the `url` and stores it into
* localForage.
* @param {string} url The url will be used as the key when storing its response into IndexedDB.
* @returns Url HTTP response.
*/
plco.fetch = async (url) => {
try {
const value = await plco.localForage.getItem(url)
if (!value || (value && !value.data)) {
const apiResult = await (await fetch(url)).json()
await plco.localForage.setItem(url, { data: apiResult, date: Math.floor(new Date().getTime() / 1000.0) })
return apiResult
} else if (value && value.date) {
if (Math.floor(new Date().getTime() / 1000.0) - value.date > 604800) {
const apiResult = await (await fetch(url)).json()
await plco.localForage.setItem(url, { data: apiResult, date: Math.floor(new Date().getTime() / 1000.0) })
return apiResult
} else {
return value.data
}
}
return value.data
} catch (error) {
console.error(error)
}
}
/**
* Sub-module grouping API methods.
* @memberof plco
* @namespace plco.api
* @property {Function} download - {@link plco.api.download}
* @property {Function} metadata - {@link plco.api.metadata}
* @property {Function} participants - {@link plco.api.participants}
* @property {Function} pca - {@link plco.api.pca}
* @property {Function} phenotypes - {@link plco.api.phenotypes}
* @property {Function} points - {@link plco.api.points}
* @property {Function} summary - {@link plco.api.summary}
* @property {Function} variants - {@link plco.api.variants}
* @property {Function} ping - {@link plco.api.ping}
*/
plco.api = {}
plco.api.url = 'https://exploregwas.cancer.gov/plco-atlas/api/'
/**
* Returns the status of the PLCO API.
*/
plco.api.ping = async () => {
return (await fetch(plco.api.url + 'ping')).text()
}
plco.api.get = async (cmd = "ping", parms = {}) => {
// res = await fetch(...)
// content-type = await res.blob().type
if (cmd === "ping") {
return await (await fetch(plco.api.url + 'ping')).text() === "true"
} else if (cmd === 'download') {
if (parms['get_link_only'] === 'true') {
return (
await fetch(
plco.api.url + cmd + '?' + plco.api.parms2string(parms)
)
).text()
} else {
plco.saveFile(
plco.api.url + cmd + '?' + plco.api.parms2string(parms)
)
return await new Promise((resolve) => resolve({}))
}
} else {
return await plco.fetch(plco.api.url + cmd + '?' + plco.api.parms2string(parms))
}
}
plco.api.string2parms = (
str = "phenotype_id=3080&sex=all&ancestry=east_asian&p_value_nlog_min=4"
) => {
let prm = {}
str.split('&').forEach(s => {
s = s.split('=')
prm[s[0]] = s[1]
})
return prm
}
plco.api.parms2string = (
prm = { phenotype_id: 3080, sex: "all", ancestry: "east_asian", p_value_nlog_min: 4 }
) => {
return Object.keys(prm).map(p => `${p}=${prm[p]}`).join('&')
}
/**
* Downloads the original association results in tsv.gz format.
* @param {object | string | Array<Array>} parms A JSON object, query string, or 2-d array containing the query parameters.
* @param {integer} [phenotype_id=3080] A numeric phenotype id.
* @param {string} [get_link_only] _Optional_. If set to 'true', returns the download link instead of redirecting automatically to the file.
* @returns Results of the API call.
*/
plco.api.download = async (
parms,
phenotype_id = 3080,
get_link_only = undefined
) => {
parms =
typeof parms === 'string'
? plco.api.string2parms(parms)
: Array.isArray(parms)
? Object.fromEntries(parms)
: parms
parms = parms || {
phenotype_id,
}
plco.defineProperties(parms, { phenotype_id }, { get_link_only })
return await plco.api.get((cmd = 'download'), parms)
}
/**
* Retrieves metadata for phenotypes specified
* @param {object | string | Array<Array>} parms A JSON object, query string, or 2-d array containing the query parameters.
* @param {number} [phenotype_id=3080] A phenotype id.
* @param {string} [sex=female] A sex, which may be "all", "female", or "male".
* @param {string} [ancestry=european] A character vector specifying ancestries to retrieve data for.
* @param {string} [raw] _Optional_. If true, returns data in an array of arrays instead of an array of objects.
* @return A dataframe containing phenotype metadata
* @example
* plco.api.metadata()
* plco.api.metadata({ phenotype_id: 3080, sex: "female", ancestry: "european" })
* plco.api.metadata("phenotype_id=3080&sex=female&ancestry=european")
* plco.api.metadata([["phenotype_id",3080], ["sex","female"], ["ancestry","european"]])
* plco.api.metadata({}, 3080, "female", "european")
*/
plco.api.metadata = async (
parms,
phenotype_id = 3080,
sex = "female",
ancestry = "european",
raw = undefined
) => {
parms =
typeof parms === 'string'
? plco.api.string2parms(parms)
: Array.isArray(parms)
? Object.fromEntries(parms)
: parms
parms = parms || {
phenotype_id,
sex,
ancestry
}
plco.defineProperties(parms, { phenotype_id, sex, ancestry }, { raw })
return await plco.api.get((cmd = 'metadata'), parms)
}
/**
* Retrieves aggregate counts for participants. Aggregate counts under 10 are returned as "< 10".
* @param {object | string | Array<Array>} parms A JSON object, query string, or 2-d array containing the query parameters.
* @param {integer} [phenotype_id=2250] A numeric phenotype id.
* @param {string} [columns] _Optional_. A character vector specifying properties for which to retrieve counts for.
* Valid properties are: value, ancestry, genetic_ancestry, sex, and age.
* @param {integer} [precision] _Optional_. For continuous phenotypes, a numeric value specifying the -log10(precision)
* to which values should be rounded to.
* @param {string} [raw] _Optional_. If true, returns data in an array of arrays instead of an array of objects.
* @returns Results of the API call.
*/
plco.api.participants = async (
parms,
phenotype_id = 2250,
columns = undefined,
precision = undefined,
raw = undefined
) => {
parms =
typeof parms === 'string'
? plco.api.string2parms(parms)
: Array.isArray(parms)
? Object.fromEntries(parms)
: parms
parms = parms || {
phenotype_id,
columns: 'value',
precision: 0,
}
plco.defineProperties(parms, { phenotype_id }, { columns, precision, raw })
return await plco.api.get((cmd = 'participants'), parms)
}
/**
* Retrieve PCA coordinates for the specified phenotype and platform.
* @param {object | string | Array<Array>} parms A JSON object, query string, or 2-d array containing the query parameters.
* @param {integer} [phenotype_id=3080] A numeric phenotype id.
* @param {string} [platform=PLCO_GSA] A character vector specifying the platform to retrieve data for.
* @param {integer} [pc_x=1] A numeric value (1-20) specifying the x axis's principal component.
* @param {integer} [pc_y=2] A numeric value (1-20) specifying the y axis's principal component.
* @param {integer} [limit] _Optional_. A numeric value to limit the number of variants returned (used for pagination).
* Capped at 1 million.
* @param {string} [raw] _Optional_. If true, returns data in an array of arrays instead of an array of objects.
* @returns A dataframe containing pca coordinates.
* @example
* plco.api.pca()
* plco.api.pca({}, 3080, 'PLCO_GSA', 1, 1, 1000)
* plco.api.pca({phenotype_id: 3080, platform: 'PLCO_GSA', pc_x: 1, pc_y: 1, limit: 1000 })
* plco.api.pca("phenotype_id=3080&platform=PLCO_GSA&pc_x=1&pc_y=1&limit=1000")
* plco.api.pca([["phenotype_id",3080], ["platform","PLCO_GSA"], ["pc_x",1], ["pc_y",1], ["limit",1000]])
*/
plco.api.pca = async (
parms,
phenotype_id = 3080,
platform = 'PLCO_GSA',
pc_x = 1,
pc_y = 2,
limit = undefined,
raw = undefined
) => {
parms =
typeof parms === 'string'
? plco.api.string2parms(parms)
: Array.isArray(parms)
? Object.fromEntries(parms)
: parms
parms = parms || {
phenotype_id,
platform,
pc_x,
pc_y,
limit: 10,
}
plco.defineProperties(parms, { phenotype_id, platform, pc_x, pc_y }, { limit, raw })
if (!Number.isInteger(parms['pc_x']) || parms['pc_x'] < 1 || parms['pc_x'] > 20) {
throw new RangeError('pc_x must be an integer between 1 and 20 inclusive.')
}
if (!Number.isInteger(parms['pc_y']) || parms['pc_y'] < 1 || parms['pc_y'] > 20) {
throw new RangeError('pc_y must be an integer between 1 and 20 inclusive.')
}
return await plco.api.get((cmd = 'pca'), parms)
}
/**
* Retrieves phenotypes
* @param {object | string | Array<Array>} parms A JSON object, query string, or 2-d array containing the query parameters.
* @param {string} [q] _Optional_. A query term
* @param {string} [raw] _Optional_. If true, returns data in an array of arrays instead of an array of objects.
* @return If query is specified, a list of phenotypes that contain the query term is returned. Otherwise, a tree of all phenotypes is returned.
* @example
* plco.api.phenotypes()
* plco.api.phenotypes({ q: "first_ca125_level" })
* plco.api.phenotypes("q=first_ca125_level")
* plco.api.phenotypes([["q","first_ca125_level"]])
* plco.api.phenotypes({}, "first_ca125_level")
*/
plco.api.phenotypes = async (
parms,
q = undefined,
raw = undefined
) => {
parms =
typeof parms === 'string'
? plco.api.string2parms(parms)
: Array.isArray(parms)
? Object.fromEntries(parms)
: parms
parms = parms || {
}
plco.defineProperties(parms, {}, { q, raw })
return await plco.api.get(cmd = "phenotypes", parms)
}
/**
* Retrieves sampled variants suitable for visualizing a QQ plot for the specified phenotype, sex, and ancestry.
* @param {object | string | Array<Array>} parms A JSON object, query string, or 2-d array containing the query parameters.
* @param {integer} [phenotype_id=3080] A numeric phenotype id.
* @param {string} [sex=female] A character vector specifying a sex to retrieve data for.
* @param {string} [ancestry=european] A character vector specifying ancestries to retrieve data for.
* @param {string} [raw] _Optional_. If true, returns data in an array of arrays instead of an array of objects.
* @returns A dataframe containing variants.
*/
plco.api.points = async (
parms,
phenotype_id = 3080,
sex = 'female',
ancestry = 'european',
raw = undefined
) => {
parms =
typeof parms === 'string'
? plco.api.string2parms(parms)
: Array.isArray(parms)
? Object.fromEntries(parms)
: parms
parms = parms || {
phenotype_id,
sex,
ancestry,
}
plco.defineProperties(parms, { phenotype_id, sex, ancestry }, { raw })
return await plco.api.get((cmd = 'points'), parms)
}
/**
* Retrieve variants for all chromosomes at a resolution of 400x800 bins across the whole genome and specified -log10(p) range
* @param {object | string | Array<Array>} parms A JSON object, query string, or 2-d array containing the query parameters.
* @param {number} [phenotype_id=3080] A phenotype id.
* @param {string} [sex=female] A sex, which may be "all", "female", or "male".
* @param {string} [ancestry=european] A character vector specifying ancestries to retrieve data for.
* @param {number} [p_value_nlog_min=4] A numeric value >= 0 specifying the minimum -log10(p) for variants.
* @param {string} [raw] _Optional_. If true, returns data in an array of arrays instead of an array of objects.
* @return A dataframe with aggregated variants.
* @example
* plco.api.summary()
* plco.api.summary({ phenotype_id: 3080, sex: "female", ancestry: "european", p_value_nlog_min: 4 })
* plco.api.summary("phenotype_id=3080&sex=female&ancestry=european&p_value_nlog_min=4")
* plco.api.summary([["phenotype_id",3080], ["sex","female"], ["ancestry","european"], ["p_value_nlog_min",4]])
* plco.api.summary({}, 3080, "female", "european", 4)
*/
plco.api.summary = async (
parms,
phenotype_id = 3080,
sex = "female",
ancestry = "european",
p_value_nlog_min = 4,
raw = undefined
) => {
parms =
typeof parms === 'string'
? plco.api.string2parms(parms)
: Array.isArray(parms)
? Object.fromEntries(parms)
: parms
parms = parms || {
phenotype_id,
sex,
ancestry,
p_value_nlog_min
}
plco.defineProperties(parms, { phenotype_id, sex, ancestry, p_value_nlog_min }, { raw })
return await plco.api.get(cmd = "summary", parms)
}
/**
* Retrieve variants for specified phenotype, sex, ancestry, chromosome, and other optional fields.
* @param {object | string | Array<Array>} parms A JSON object, query string, or 2-d array containing the query parameters.
* @param {number} [phenotype_id=3080] Phenotype id(s)
* @param {string} [sex=female] A sex, which may be "all", "female", or "male".
* @param {string} [ancestry=european] An ancestry, which may be "african_american", "east_asian", or "european".
* @param {number} [chromosome=8] A chromosome number.
* @param {string} [columns] _Optional_ Properties for each variant. Default: all properties.
* @param {string} [snp] _Optional_ Snps.
* @param {number} [position] _Optional_ The exact position of the variant within a chromosome.
* @param {number} [position_min] _Optional_ The minimum chromosome position for variants.
* @param {number} [position_max] _Optional_ The maximum chromosome position for variants.
* @param {number} [p_value_nlog_min] _Optional_ The minimum -log10(p) of variants in the chromosome.
* @param {number} [p_value_nlog_max] _Optional_ The maximum -log10(p) of variants in the chromosome.
* @param {number} [p_value_min] _Optional_ The minimum p-value of variants in the chromosome.
* @param {number} [p_value_max] _Optional_ The maximum p-value of variants in the chromosome.
* @param {string} [orderBy] _Optional_ A property to order variants by. May be "id", "snp", "chromosome", "position", "p_value", or "p_value_nlog".
* @param {string} [order] _Optional_ An order in which to sort variants. May be "asc" or "desc".
* @param {number} [offset] _Optional_ The number of records by which to offset the variants (for pagination)
* @param {number} [limit] _Optional_ The maximum number of variants to return (for pagination). Highest allowed value is 1 million.
* @param {string} [raw] _Optional_. If true, returns data in an array of arrays instead of an array of objects.
* @return A dataframe with variants.
* @example
* plco.api.variants()
* plco.api.variants({ phenotype_id: 3080, sex: "female", ancestry: "european", chromosome: 8, limit: 10 })
* plco.api.variants("phenotype_id=3080&sex=female&ancestry=european&chromosome=8&limit=10")
* plco.api.variants([["phenotype_id",3080], ["sex","female"], ["ancestry","european"], ["chromosome",8], ["limit",10]])
* plco.api.variants({}, 3080, "female", "european", 8)
*/
plco.api.variants = async (
parms,
phenotype_id = 3080,
sex = "female",
ancestry = "european",
chromosome = 8,
columns = undefined,
snp = undefined,
position = undefined,
position_min = undefined,
position_max = undefined,
p_value_nlog_min = undefined,
p_value_nlog_max = undefined,
p_value_min = undefined,
p_value_max = undefined,
orderBy = undefined,
order = undefined,
offset = undefined,
limit = undefined,
raw = undefined
) => {
parms =
typeof parms === 'string'
? plco.api.string2parms(parms)
: Array.isArray(parms)
? Object.fromEntries(parms)
: parms
parms = parms || {
phenotype_id,
sex,
ancestry,
chromosome,
limit: 10
}
plco.defineProperties(
parms,
{ phenotype_id, sex, ancestry, chromosome },
{ columns, snp, position, position_min, position_max, p_value_nlog_min, p_value_nlog_max, p_value_min, p_value_max, orderBy, order, offset, limit, raw }
)
return await plco.api.get(cmd = "variants", parms)
}
/*
if(location.href.match('localhost')||location.href.match('127.0.0.1')){
let scriptHost=location.href.replace(/\/[^\/]*$/,'/')
plco.loadScript(`${scriptHost}plcoJonas.js`)
plco.loadScript(`${scriptHost}plcoLorena.js`)
}else{
plco.loadScript('https://episphere.github.io/plco/plcoJonas.js')
plco.loadScript('https://episphere.github.io/plco/plcoLorena.js')
}
*/
/*
if(typeof(define)!='undefined'){
define([
'https://cdn.plot.ly/plotly-latest.min.js',
//'https://episphere.github.io/plco/plco',
//'https://episphere.github.io/plco/plcoJonas.js',
//'https://episphere.github.io/plco/plcoLorena.js',
'https://cdnjs.cloudflare.com/ajax/libs/localforage/1.9.0/localforage.min.js'
],function(Plotly,localforage){
plco.localforage=localforage
plco.Plotly=Plotly
return plco
})
}
*/
/**
* Sub-module grouping plotting methods.
* @memberof plco
* @namespace plco.plot
* @prop {Function} manhattan - {@link plco.plot.manhattan}
* @prop {Function} manhattan2 - {@link plco.plot.manhattan2}
* @prop {Function} qq - {@link plco.plot.qq}
* @prop {Function} qq2 - {@link plco.plot.qq2}
* @prop {Function} pca - {@link plco.plot.pca}
* @prop {Function} pca2 - {@link plco.plot.pca2}
* @prop {Function} barchart - {@link plco.plot.barchart}
*/
plco.plot = async () => {
}
/**
* Generates a Plotly manhattan plot at the given div element with support for a single input.
* @param {string} div_id The id of the div element. If it does not exist, a new div will be created.
* @param {number} [phenotype_id=3080] A phenotype id.
* @param {string} [sex=female] A sex, which may be "all, "female", or "male".
* @param {string} [ancestry=european] An ancestry, which may be "african_american", "east_asian" or "european".
* @param {number} [p_value_nlog_min=2] A numeric value >= 0 specifying the minimum -log10(p) for variants.
* @param {integer} [chromosome] _Optional_ A single chromosome. If no chromosome argument is passed, then assume all chromosomes.
* @param {boolean} [to_json=false] _Optional_ If true, returns a stringified JSON object containing traces and layout.
* If false, returns a div element containing the Plotly graph.
* @param {object} [customLayout={}] _Optional_. Contains Plotly supported layout key-values pair that will overwrite the default layout. Commonly overwritten values may include height and width of the graph. See: https://plotly.com/javascript/reference/layout/ for more details. Also, set `to_json` to true to see what the default layout is.
* @param {object} [customConfig={}] _Optional_. Contains Plotly supported config key-values pair that will overwrite the default config. See: https://github.com/plotly/plotly.js/blob/master/src/plot_api/plot_config.js#L22-L86 for full details.
* @returns A div element or a string if 'to_json' is true.
* @example
* plco.plot.manhattan()
* plco.plot.manhattan('plot', 3080, "female", "european", 2, 18)
*/
plco.plot.manhattan = async (
div_id,
phenotype_id = 3080,
sex = 'female',
ancestry = 'european',
p_value_nlog_min = 2,
chromosome,
to_json = false,
customLayout = {},
customConfig = {},
) => {
const isValid = await plco.plot.helpers.validateInputs([{ phenotype_id, sex, ancestry }])
if (isValid.length <= 0) throw new Error('Invalid inputs, check the phenotype_id/sex/ancestry provided.')
// Set up div, in which Plotly graph may be inserted.
let div = document.getElementById(div_id)
if (div === null && !to_json) {
div = document.createElement('div')
div.id = div_id
document.body.appendChild(div)
}
// Retrieve all summary data.
let inputData = await plco.api.summary({ phenotype_id, sex, ancestry, p_value_nlog_min })
// Filter summary data if chromosome number was specified, and set associated variables for later.
let chromosomeName
let numberOfChromosomes
if (chromosome) {
inputData = inputData.data.filter(x => x.chromosome == "" + chromosome)
chromosomeName = 'Chromosome ' + chromosome
numberOfChromosomes = 1
} else {
inputData = inputData.data
chromosomeName = 'All Chromosomes'
numberOfChromosomes = 22
}
// Retrieve rs number for all SNPs if a chromosome number was passed as an argument.
let rsNumbers = []
if (numberOfChromosomes == 1) {
let rsNumbers_allData = await plco.api.variants(
{ p_value_nlog_min, orderBy: 'id', order: 'asc' }, phenotype_id, sex, ancestry, chromosome)
rsNumbers_allData.data.map(x => rsNumbers.push({
snp: x.snp, position_abs: x.position, p_value_nlog: x.p_value_nlog
}))
}
// Set up traces
let traces = []
let chromosomeTraces = []
let currentChromosome
let largestY = p_value_nlog_min
for (i = 1; i <= numberOfChromosomes; i++) {
if (numberOfChromosomes == 1) {
currentChromosome = chromosome
} else {
currentChromosome = i
}
if (numberOfChromosomes == 1) {
currentChromosomeData = rsNumbers
} else {
currentChromosomeData = inputData.filter(x => x.chromosome == "" + currentChromosome)
}
const traceInfo = {
x: currentChromosomeData.map(x => parseInt(x.position_abs)),
y: currentChromosomeData.map(x => parseFloat(x.p_value_nlog)),
mode: 'markers',
type: 'scattergl',
marker: {
opacity: 0.65,
size: 5
},
name: 'Chromosome ' + currentChromosome, // appears as legend item
hovertemplate: currentChromosomeData.map(x =>
'absolute position: ' + parseInt(x.position_abs) +
'<br>p-value: ' + Math.pow(10, -x.p_value_nlog)
)
}
traces.push(traceInfo)
largestY = traceInfo.y.reduce((largest, cur) => largest > cur ? largest : cur, largestY)
chromosomeTraces.push({
x: [traceInfo.x.reduce((smallest, cur) => cur > smallest ? smallest : cur, Number.MAX_SAFE_INTEGER)],
y: [p_value_nlog_min],
mode: 'markers',
type: 'scattergl',
marker: {
size: 0,
opacity: 0,
color: '#FFFFFF',