-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathlocuszoom.app.js
2593 lines (2300 loc) · 102 KB
/
locuszoom.app.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
!function() {
try {
// Verify that the two third-party dependencies are met: d3 and Q
var minimum_d3_version = "3.5.6";
if (typeof d3 != "object"){
throw("LocusZoom unable to load: d3 dependency not met. Library missing.");
} else if (d3.version < minimum_d3_version){
throw("LocusZoom unable to load: d3 dependency not met. Outdated version detected.\nRequired d3 version: " + minimum_d3_version + " or higher (found: " + d3.version + ").");
}
if (typeof Q != "function"){
throw("LocusZoom unable to load: Q dependency not met. Library missing.");
}
/* global d3,Q */
/* eslint-env browser */
/* eslint-disable no-console */
var LocusZoom = {
version: "0.3.6"
};
// Populate a single element with a LocusZoom instance.
// selector can be a string for a DOM Query or a d3 selector.
LocusZoom.populate = function(selector, datasource, layout, state) {
if (typeof selector == "undefined"){
throw ("LocusZoom.populate selector not defined");
}
var instance;
d3.select(selector).call(function(container){
// Require each containing element have an ID. If one isn't present, create one.
if (typeof this.node().id == "undefined"){
var iterator = 0;
while (!d3.select("#lz-" + iterator).empty()){ iterator++; }
this.attr("id", "#lz-" + iterator);
}
// Create the instance
instance = new LocusZoom.Instance(this.node().id, datasource, layout, state);
// Add an SVG to the div and set its dimensions
instance.svg = d3.select("div#" + instance.id)
.append("svg")
.attr("version", "1.1")
.attr("xmlns", "http://www.w3.org/2000/svg")
.attr("id", instance.id + "_svg").attr("class", "lz-locuszoom");
instance.setDimensions();
// Initialize the instance
instance.initialize();
// Detect data-region and fill in state values if present
if (typeof this.node().dataset !== "undefined" && typeof this.node().dataset.region !== "undefined"){
instance.state = LocusZoom.mergeLayouts(LocusZoom.parsePositionQuery(this.node().dataset.region), instance.state);
}
// If the instance has defined data sources then trigger its first mapping based on state values
if (typeof datasource == "object" && Object.keys(datasource).length){
instance.refresh();
}
});
return instance;
};
// Populate arbitrarily many elements each with a LocusZoom instance
// using a common datasource, layout, and/or state
LocusZoom.populateAll = function(selector, datasource, layout, state) {
var instances = [];
d3.selectAll(selector).each(function(d,i) {
instances[i] = LocusZoom.populate(this, datasource, layout, state);
});
return instances;
};
// Convert an integer position to a string (e.g. 23423456 => "23.42" (Mb))
LocusZoom.positionIntToString = function(p){
var places = Math.min(Math.max(6 - Math.floor((Math.log(p) / Math.LN10).toFixed(9)), 2), 12);
return "" + (p / Math.pow(10, 6)).toFixed(places);
};
// Convert a string position to an integer (e.g. "5.8 Mb" => 58000000)
LocusZoom.positionStringToInt = function(p) {
var val = p.toUpperCase();
val = val.replace(/,/g, "");
var suffixre = /([KMG])[B]*$/;
var suffix = suffixre.exec(val);
var mult = 1;
if (suffix) {
if (suffix[1]=="M") {
mult = 1e6;
} else if (suffix[1]=="G") {
mult = 1e9;
} else {
mult = 1e3; //K
}
val = val.replace(suffixre,"");
}
val = Number(val) * mult;
return val;
};
// Parse region queries that look like
// chr:start-end
// chr:center+offset
// chr:pos
// TODO: handle genes (or send off to API)
LocusZoom.parsePositionQuery = function(x) {
var chrposoff = /^(\w+):([\d,.]+[kmgbKMGB]*)([-+])([\d,.]+[kmgbKMGB]*)$/;
var chrpos = /^(\w+):([\d,.]+[kmgbKMGB]*)$/;
var match = chrposoff.exec(x);
if (match) {
if (match[3] == "+") {
var center = LocusZoom.positionStringToInt(match[2]);
var offset = LocusZoom.positionStringToInt(match[4]);
return {
chr:match[1],
start: center - offset,
end: center + offset
};
} else {
return {
chr: match[1],
start: LocusZoom.positionStringToInt(match[2]),
end: LocusZoom.positionStringToInt(match[4])
};
}
}
match = chrpos.exec(x);
if (match) {
return {
chr:match[1],
position: LocusZoom.positionStringToInt(match[2])
};
}
return null;
};
// Generate a "pretty" set of ticks (multiples of 1, 2, or 5 on the same order of magnitude for the range)
// Based on R's "pretty" function: https://github.com/wch/r-source/blob/b156e3a711967f58131e23c1b1dc1ea90e2f0c43/src/appl/pretty.c
//
// clip_range - string, optional - default "neither"
// First and last generated ticks may extend beyond the range. Set this to "low", "high", "both", or
// "neither" to clip the first (low) or last (high) tick to be inside the range or allow them to extend beyond.
// e.g. "low" will clip the first (low) tick if it extends beyond the low end of the range but allow the
// last (high) tick to extend beyond the range. "both" clips both ends, "neither" allows both to extend beyond.
//
// target_tick_count - integer, optional - default 5
// Specify a "target" number of ticks. Will not necessarily be the number of ticks you get, but should be
// pretty close. Defaults to 5.
LocusZoom.prettyTicks = function(range, clip_range, target_tick_count){
if (typeof target_tick_count == "undefined" || isNaN(parseInt(target_tick_count))){
target_tick_count = 5;
}
target_tick_count = parseInt(target_tick_count);
var min_n = target_tick_count / 3;
var shrink_sml = 0.75;
var high_u_bias = 1.5;
var u5_bias = 0.5 + 1.5 * high_u_bias;
var d = Math.abs(range[0] - range[1]);
var c = d / target_tick_count;
if ((Math.log(d) / Math.LN10) < -2){
c = (Math.max(Math.abs(d)) * shrink_sml) / min_n;
}
var base = Math.pow(10, Math.floor(Math.log(c)/Math.LN10));
var base_toFixed = 0;
if (base < 1 && base != 0){
base_toFixed = Math.abs(Math.round(Math.log(base)/Math.LN10));
}
var unit = base;
if ( ((2 * base) - c) < (high_u_bias * (c - unit)) ){
unit = 2 * base;
if ( ((5 * base) - c) < (u5_bias * (c - unit)) ){
unit = 5 * base;
if ( ((10 * base) - c) < (high_u_bias * (c - unit)) ){
unit = 10 * base;
}
}
}
var ticks = [];
var i = parseFloat( (Math.floor(range[0]/unit)*unit).toFixed(base_toFixed) );
while (i < range[1]){
ticks.push(i);
i += unit;
if (base_toFixed > 0){
i = parseFloat(i.toFixed(base_toFixed));
}
}
ticks.push(i);
if (typeof clip_range == "undefined" || ["low", "high", "both", "neither"].indexOf(clip_range) == -1){
clip_range = "neither";
}
if (clip_range == "low" || clip_range == "both"){
if (ticks[0] < range[0]){ ticks = ticks.slice(1); }
}
if (clip_range == "high" || clip_range == "both"){
if (ticks[ticks.length-1] > range[1]){ ticks.pop(); }
}
return ticks;
};
// From http://www.html5rocks.com/en/tutorials/cors/
// and with promises from https://gist.github.com/kriskowal/593076
LocusZoom.createCORSPromise = function (method, url, body, timeout) {
var response = Q.defer();
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
if (xhr) {
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 0 ) {
response.resolve(JSON.parse(xhr.responseText));
} else {
response.reject("HTTP " + xhr.status + " for " + url);
}
}
};
timeout && setTimeout(response.reject, timeout);
body = typeof body !== "undefined" ? body : "";
xhr.send(body);
}
return response.promise;
};
// Merge two layout objects
// Primarily used to merge values from the second argument (the "default" layout) into the first (the "custom" layout)
// Ensures that all values defined in the second layout are at least present in the first
// Favors values defined in the first layout if values are defined in both but different
LocusZoom.mergeLayouts = function (custom_layout, default_layout) {
if (typeof custom_layout != "object" || typeof default_layout != "object"){
throw("LocusZoom.mergeLayouts only accepts two layout objects; " + (typeof custom_layout) + ", " + (typeof default_layout) + " given");
}
for (var property in default_layout) {
if (!default_layout.hasOwnProperty(property)){ continue; }
// Get types for comparison. Treat nulls in the custom layout as undefined for simplicity
// (javascript treats nulls as "object" when we just want to overwrite them as if they're undefined)
var custom_type = custom_layout[property] == null ? "undefined" : typeof custom_layout[property];
var default_type = typeof default_layout[property];
// Unsupported property types: throw an exception
if (custom_type == "function" || default_type == "function"){
throw("LocusZoom.mergeLayouts encountered an unsupported property type");
}
// Undefined custom value: pull the default value
if (custom_type == "undefined"){
custom_layout[property] = JSON.parse(JSON.stringify(default_layout[property]));
continue;
}
// Both values are objects: merge recursively
if (custom_type == "object" && default_type == "object"){
custom_layout[property] = LocusZoom.mergeLayouts(custom_layout[property], default_layout[property]);
continue;
}
}
return custom_layout;
};
// Replace placeholders in an html string with field values defined in a data object
// Only works on scalar values! Will ignore non-scalars.
LocusZoom.parseFields = function (data, html) {
if (typeof data != "object"){
throw ("LocusZoom.parseFields invalid arguments: data is not an object");
}
if (typeof html != "string"){
throw ("LocusZoom.parseFields invalid arguments: html is not a string");
}
var re;
for (var field in data) {
if (!data.hasOwnProperty(field)){ continue; }
if (typeof data[field] != "string" && typeof data[field] != "number" && typeof data[field] != "boolean"){ continue; }
re = new RegExp("\\{\\{" + field.replace("|","\\|").replace(":","\\:") + "\\}\\}","g");
html = html.replace(re, data[field]);
}
return html;
};
// Default State
LocusZoom.DefaultState = {
chr: 0,
start: 0,
end: 0,
panels: {}
};
// Default Layout
LocusZoom.DefaultLayout = {
width: 800,
height: 450,
min_width: 400,
min_height: 225,
resizable: "responsive",
aspect_ratio: (16/9),
panels: {
positions: {
width: 800,
height: 225,
origin: { x: 0, y: 0 },
min_width: 400,
min_height: 112.5,
proportional_width: 1,
proportional_height: 0.5,
proportional_origin: { x: 0, y: 0 },
margin: { top: 20, right: 20, bottom: 35, left: 50 },
inner_border: "rgba(210, 210, 210, 0.85)",
axes: {
x: {
label_function: "chromosome"
},
y1: {
label: "-log10 p-value"
}
},
data_layers: {
positions: {
type: "scatter",
point_shape: "circle",
point_size: 40,
point_label_field: "id",
fields: ["id", "position", "pvalue|scinotation", "pvalue|neglog10", "refAllele", "ld:state"],
x_axis: {
field: "position"
},
y_axis: {
axis: 1,
field: "pvalue|neglog10",
floor: 0,
upper_buffer: 0.05
},
color: {
field: "ld:state",
scale_function: "numerical_bin",
parameters: {
breaks: [0, 0.2, 0.4, 0.6, 0.8],
values: ["#357ebd","#46b8da","#5cb85c","#eea236","#d43f3a"],
null_value: "#B8B8B8"
}
},
tooltip: {
divs: [
{ html: "<strong>{{id}}</strong>" },
{ html: "P Value: <strong>{{pvalue|scinotation}}</strong>" },
{ html: "Ref. Allele: <strong>{{refAllele}}</strong>" }
]
}
}
}
},
genes: {
width: 800,
height: 225,
origin: { x: 0, y: 350 },
min_width: 400,
min_height: 112.5,
proportional_width: 1,
proportional_height: 0.5,
proportional_origin: { x: 0, y: 0.5 },
margin: { top: 20, right: 20, bottom: 20, left: 50 },
data_layers: {
genes: {
type: "genes",
fields: ["gene:gene"],
tooltip: {
divs: [
{ html: "<strong><i>{{gene_name}}</i></strong>" },
{ html: "Gene ID: <strong>{{gene_id}}</strong>" },
{ html: "Transcript ID: <strong>{{transcript_id}}</strong>" },
{ html: "<a href=\"http://exac.broadinstitute.org/gene/{{gene_id}}\" target=\"_new\">ExAC Page</a>" }
]
}
}
}
}
}
};
/* global LocusZoom,Q */
/* eslint-env browser */
/* eslint-disable no-unused-vars */
"use strict";
/* A named collection of data sources used to draw a plot*/
LocusZoom.DataSources = function() {
this.sources = {};
};
LocusZoom.DataSources.prototype.addSource = function(ns, x) {
function findKnownSource(x) {
if (!LocusZoom.KnownDataSources) {return null;}
for(var i=0; i<LocusZoom.KnownDataSources.length; i++) {
if (!LocusZoom.KnownDataSources[i].SOURCE_NAME) {
throw("KnownDataSource at position " + i + " does not have a 'SOURCE_NAME' static property");
}
if (LocusZoom.KnownDataSources[i].SOURCE_NAME == x) {
return LocusZoom.KnownDataSources[i];
}
}
return null;
}
if (Array.isArray(x)) {
var dsclass = findKnownSource(x[0]);
if (dsclass) {
this.sources[ns] = new dsclass(x[1]);
} else {
throw("Unable to resolve " + x[0] + " data source");
}
} else {
this.sources[ns] = x;
}
return this;
};
LocusZoom.DataSources.prototype.getSource = function(ns) {
return this.sources[ns];
};
LocusZoom.DataSources.prototype.setSources = function(x) {
if (typeof x === "string") {
x = JSON.parse(x);
}
var ds = this;
Object.keys(x).forEach(function(ns) {
ds.addSource(ns, x[ns]);
});
return ds;
};
LocusZoom.DataSources.prototype.keys = function() {
return Object.keys(this.sources);
};
LocusZoom.DataSources.prototype.toJSON = function() {
return this.sources;
};
LocusZoom.Data = LocusZoom.Data || {};
LocusZoom.Data.Requester = function(sources) {
function split_requests(fields) {
var requests = {};
// Regular expressopn finds namespace:field|trans
var re = /^(?:([^:]+):)?([^:\|]*)(\|.+)*$/;
fields.forEach(function(raw) {
var parts = re.exec(raw);
var ns = parts[1] || "base";
var field = parts[2];
var trans = LocusZoom.TransformationFunctions.get(parts[3]);
if (typeof requests[ns] =="undefined") {
requests[ns] = {outnames:[], fields:[], trans:[]};
}
requests[ns].outnames.push(raw);
requests[ns].fields.push(field);
requests[ns].trans.push(trans);
});
return requests;
}
this.getData = function(state, fields) {
var requests = split_requests(fields);
var promises = Object.keys(requests).map(function(key) {
if (!sources.getSource(key)) {
throw("Datasource for namespace " + key + " not found");
}
return sources.getSource(key).getData(state, requests[key].fields,
requests[key].outnames, requests[key].trans);
});
//assume the fields are requested in dependent order
//TODO: better manage dependencies
var ret = Q.when({header:{}, body:{}});
for(var i=0; i < promises.length; i++) {
ret = ret.then(promises[i]);
}
return ret;
};
};
LocusZoom.Data.Source = function() {};
LocusZoom.Data.Source.prototype.parseInit = function(init) {
if (typeof init === "string") {
this.url = init;
this.params = {};
} else {
this.url = init.url;
this.params = init.params || {};
}
if (!this.url) {
throw("Source not initialized with required URL");
}
};
LocusZoom.Data.Source.prototype.getRequest = function(state, chain, fields) {
return LocusZoom.createCORSPromise("GET", this.getURL(state, chain, fields));
};
LocusZoom.Data.Source.prototype.getData = function(state, fields, outnames, trans) {
return function (chain) {
return this.getRequest(state, chain, fields).then(function(resp) {
return this.parseResponse(resp, chain, fields, outnames, trans);
}.bind(this));
}.bind(this);
};
LocusZoom.Data.Source.prototype.toJSON = function() {
return [Object.getPrototypeOf(this).constructor.SOURCE_NAME,
{url:this.url, params:this.params}];
};
LocusZoom.Data.AssociationSource = function(init) {
this.parseInit(init);
this.getData = function(state, fields, outnames, trans) {
["id","position"].forEach(function(x) {
if (fields.indexOf(x)==-1) {
fields.unshift(x);
outnames.unshift(x);
trans.unshift(null);
}
});
return function (chain) {
return this.getRequest(state, chain).then(function(resp) {
return this.parseResponse(resp, chain, fields, outnames, trans);
}.bind(this));
}.bind(this);
};
};
LocusZoom.Data.AssociationSource.prototype = Object.create(LocusZoom.Data.Source.prototype);
LocusZoom.Data.AssociationSource.prototype.constructor = LocusZoom.Data.AssociationSource;
LocusZoom.Data.AssociationSource.prototype.getURL = function(state, chain, fields) {
var analysis = state.analysis || chain.header.analysis || this.params.analysis || 3;
return this.url + "results/?filter=analysis in " + analysis +
" and chromosome in '" + state.chr + "'" +
" and position ge " + state.start +
" and position le " + state.end;
};
LocusZoom.Data.AssociationSource.prototype.parseResponse = function(resp, chain, fields, outnames, trans) {
var x = resp.data;
var records = [];
fields.forEach(function(f) {
if (!(f in x)) {throw "field " + f + " not found in response";}
});
for(var i = 0; i < x.position.length; i++) {
var record = {};
for(var j=0; j<fields.length; j++) {
var val = x[fields[j]][i];
if (trans && trans[j]) {
val = trans[j](val);
}
record[outnames[j]] = val;
}
records.push(record);
}
var res = {header: chain.header || {}, body: records};
return res;
};
LocusZoom.Data.AssociationSource.SOURCE_NAME = "AssociationLZ";
LocusZoom.Data.LDSource = function(init) {
this.parseInit(init);
if (!this.params.pvaluefield) {
this.params.pvaluefield = "pvalue|neglog10";
}
this.getData = function(state, fields, outnames, trans) {
if (fields.length>1) {
throw("LD currently only supports one field");
}
return function (chain) {
return this.getRequest(state, chain, fields).then(function(resp) {
return this.parseResponse(resp, chain, fields, outnames, trans);
}.bind(this));
}.bind(this);
};
};
LocusZoom.Data.LDSource.prototype = Object.create(LocusZoom.Data.Source.prototype);
LocusZoom.Data.LDSource.prototype.constructor = LocusZoom.Data.LDSource;
LocusZoom.Data.LDSource.prototype.getURL = function(state, chain, fields) {
var findExtremeValue = function(x, pval, sign) {
pval = pval || "pvalue";
sign = sign || 1;
var extremeVal = x[0][pval], extremeIdx=0;
for(var i=1; i<x.length; i++) {
if (x[i][pval] * sign > extremeVal) {
extremeVal = x[i][pval] * sign;
extremeIdx = i;
}
}
return extremeIdx;
};
var refSource = state.ldrefsource || chain.header.ldrefsource || 1;
var refVar = fields[0];
if ( refVar == "state" ) {
refVar = state.ldrefvar || chain.header.ldrefvar || "best";
}
if ( refVar=="best" ) {
if ( !chain.body ) {
throw("No association data found to find best pvalue");
}
refVar = chain.body[findExtremeValue(chain.body, this.params.pvaluefield)].id;
}
if (!chain.header) {chain.header = {};}
chain.header.ldrefvar = refVar;
return this.url + "results/?filter=reference eq " + refSource +
" and chromosome2 eq '" + state.chr + "'" +
" and position2 ge " + state.start +
" and position2 le " + state.end +
" and variant1 eq '" + refVar + "'" +
"&fields=chr,pos,rsquare";
};
LocusZoom.Data.LDSource.prototype.parseResponse = function(resp, chain, fields, outnames) {
var leftJoin = function(left, right, lfield, rfield) {
var i=0, j=0;
while (i < left.length && j < right.position2.length) {
if (left[i].position == right.position2[j]) {
left[i][lfield] = right[rfield][j];
i++;
j++;
} else if (left[i].position < right.position2[j]) {
i++;
} else {
j++;
}
}
};
leftJoin(chain.body, resp.data, outnames[0], "rsquare");
return chain;
};
LocusZoom.Data.LDSource.SOURCE_NAME = "LDLZ";
LocusZoom.Data.GeneSource = function(init) {
this.parseInit(init);
this.getData = function(state, fields, outnames, trans) {
return function (chain) {
return this.getRequest(state, chain, fields).then(function(resp) {
return this.parseResponse(resp, chain, fields, outnames, trans);
}.bind(this));
}.bind(this);
};
};
LocusZoom.Data.GeneSource.prototype = Object.create(LocusZoom.Data.Source.prototype);
LocusZoom.Data.GeneSource.prototype.constructor = LocusZoom.Data.GeneSource;
LocusZoom.Data.GeneSource.prototype.getURL = function(state, chain, fields) {
var source = state.source || chain.header.source || this.params.source || 2;
return this.url + "?filter=source in " + source +
" and chrom eq '" + state.chr + "'" +
" and start le " + state.end +
" and end ge " + state.start;
};
LocusZoom.Data.GeneSource.prototype.findTranscriptPositions = function(data, transName) {
var transData;
for(var g=0; g < data.length && !transData; g++) {
for (var t=0; t < data[g].transcripts.length; t++) {
if (data[g].transcripts[t].transcript_id==transName) {
transData = {
start: data[g].transcripts[t].start,
end: data[g].transcripts[t].end,
exonStarts: [],
exonEnds: []
};
data[g].transcripts[t].exons.forEach(function(ex) {
transData.exonStarts.push(ex.start);
transData.exonEnds.push(ex.end);
});
break;
}
}
}
return transData;
};
LocusZoom.Data.GeneSource.prototype.annotateOverlap = function(data, positions, outname) {
var between = function(x, a, b) {return x>=a && x<=b;};
//assuming exon positions are sorted and non-overlaping
var exid = 0;
for(var i=0; i < data.length; i++) {
var pos = data[i].position;
if (positions && between(pos, positions.start, positions.end)) {
//jump to "next" exon
while(exid < positions.exonEnds.length && pos > positions.exonEnds[exid]) {exid++;}
if( between(pos, positions.exonStarts[exid], positions.exonEnds[exid])) {
data[i][outname] = 2;
} else {
data[i][outname] = 1;
}
} else {
//trans not found or not in transcript
data[i][outname] = 0;
}
}
};
LocusZoom.Data.GeneSource.prototype.parseResponse = function(resp, chain, fields, outnames) {
if (fields.length==1 & fields[0]=="gene") {
//raw dump of gene info for genes panel
return {header: chain.header, body: resp.data};
} else {
//should match "type(parameter)" where parameters are optional
var fregex = /([^()]+)(?:\(([^()]+)\))?/;
for (var f=0; f < fields.length; f++) {
var field = fields[f];
var outname = outnames[f];
var matches = fregex.exec(field);
if ( matches[1] == "transanno" ) {
var transName = matches[2];
if (!transName) {throw("missing required transcript for transanno: " + field);}
if (!chain.body.length) {return chain;}
var transData = this.findTranscriptPositions(resp.data, transName);
//merge info into chain
this.annotateOverlap(chain.body, transData, outname);
} else {
throw("unrecognized gene field: " + field);
}
}
return chain;
}
};
LocusZoom.Data.GeneSource.SOURCE_NAME = "GeneLZ";
LocusZoom.createResolvedPromise = function() {
var response = Q.defer();
response.resolve(Array.prototype.slice.call(arguments));
return response.promise;
};
LocusZoom.KnownDataSources = [
LocusZoom.Data.AssociationSource,
LocusZoom.Data.LDSource,
LocusZoom.Data.GeneSource
];
/* global d3,Q,LocusZoom */
/* eslint-env browser */
/* eslint-disable no-console */
"use strict";
/**
LocusZoom.Instance Class
An Instance is an independent LocusZoom object. Many such LocusZoom objects can exist simultaneously
on a single page, each having its own layout, data sources, and state.
*/
LocusZoom.Instance = function(id, datasource, layout, state) {
this.initialized = false;
this.id = id;
this.svg = null;
// The panels property stores child panel instances
this.panels = {};
this.remap_promises = [];
// The layout is a serializable object used to describe the composition of the instance
this.layout = LocusZoom.mergeLayouts(layout || {}, LocusZoom.DefaultLayout);
// The state property stores any parameters subject to change via user input
this.state = LocusZoom.mergeLayouts(state || {}, LocusZoom.DefaultState);
// LocusZoom.Data.Requester
this.lzd = new LocusZoom.Data.Requester(datasource);
// Window.onresize listener (responsive layouts only)
this.window_onresize = null;
// Initialize the layout
this.initializeLayout();
return this;
};
LocusZoom.Instance.prototype.initializeLayout = function(){
// Sanity check layout values
// TODO: Find a way to generally abstract this, maybe into an object that models allowed layout values?
if (isNaN(this.layout.width) || this.layout.width <= 0){
throw ("Instance layout parameter `width` must be a positive number");
}
if (isNaN(this.layout.height) || this.layout.height <= 0){
throw ("Instance layout parameter `width` must be a positive number");
}
if (isNaN(this.layout.aspect_ratio) || this.layout.aspect_ratio <= 0){
throw ("Instance layout parameter `aspect_ratio` must be a positive number");
}
// If this is a responsive layout then set a namespaced/unique onresize event listener on the window
if (this.layout.resizable == "responsive"){
this.window_onresize = d3.select(window).on("resize.lz-"+this.id, function(){
var clientRect = this.svg.node().parentNode.getBoundingClientRect();
this.setDimensions(clientRect.width, clientRect.height);
}.bind(this));
// Forcing one additional setDimensions() call after the page is loaded clears up
// any disagreements between the initial layout and the loaded responsive container's size
d3.select(window).on("load.lz-"+this.id, function(){ this.setDimensions(); }.bind(this));
}
// Set instance dimensions
this.setDimensions();
// Add panels
var panel_id;
for (panel_id in this.layout.panels){
this.addPanel(panel_id, this.layout.panels[panel_id], this.state.panels[panel_id]);
}
};
// Set the layout dimensions for this instance. If an SVG exists, update its dimensions.
// If any arguments are missing, use values stored in the layout. Keep everything in agreement.
LocusZoom.Instance.prototype.setDimensions = function(width, height){
// Set discrete layout dimensions based on arguments
if (!isNaN(width) && width >= 0){
this.layout.width = Math.max(Math.round(+width), this.layout.min_width);
}
if (!isNaN(height) && height >= 0){
this.layout.height = Math.max(Math.round(+height), this.layout.min_height);
}
// Override discrete values if resizing responsively
if (this.layout.resizable == "responsive"){
if (this.svg){
this.layout.width = Math.max(this.svg.node().parentNode.getBoundingClientRect().width, this.layout.min_width);
}
this.layout.height = this.layout.width / this.layout.aspect_ratio;
if (this.layout.height < this.layout.min_height){
this.layout.height = this.layout.min_height;
this.layout.width = this.layout.height * this.layout.aspect_ratio;
}
}
// Keep aspect ratio in agreement with dimensions
this.layout.aspect_ratio = this.layout.width / this.layout.height;
// Apply layout width and height as discrete values or viewbox values
if (this.svg != null){
if (this.layout.resizable == "responsive"){
this.svg
.attr("viewBox", "0 0 " + this.layout.width + " " + this.layout.height)
.attr("preserveAspectRatio", "xMinYMin meet");
} else {
this.svg.attr("width", this.layout.width).attr("height", this.layout.height);
}
}
// Reposition all panels
this.positionPanels();
// If the instance has been initialized then trigger some necessary render functions
if (this.initialized){
this.ui.render();
}
return this;
};
// Create a new panel by id and panel class
LocusZoom.Instance.prototype.addPanel = function(id, layout, state){
if (typeof id !== "string"){
throw "Invalid panel id passed to LocusZoom.Instance.prototype.addPanel()";
}
if (typeof this.panels[id] !== "undefined"){
throw "Cannot create panel with id [" + id + "]; panel with that id already exists";
}
if (typeof layout !== "object"){
throw "Invalid panel layout passed to LocusZoom.Instance.prototype.addPanel()";
}
// Create the Panel and set its parent
var panel = new LocusZoom.Panel(id, layout, state);
panel.parent = this;
// Apply the Panel's state to the parent's state
panel.parent.state.panels[panel.id] = panel.state;
// Store the Panel on the Instance
this.panels[panel.id] = panel;
// Update minimum instance dimensions based on the minimum dimensions of all panels
// TODO: This logic assumes panels are always stacked vertically. More sophisticated
// logic to handle arbitrary panel geometries needs to be supported.
var panel_min_widths = [];
var panel_min_heights = [];
for (id in this.panels){
panel_min_widths.push(this.panels[id].layout.min_width);
panel_min_heights.push(this.panels[id].layout.min_height);
}
this.layout.min_width = Math.max.apply(null, panel_min_widths);
this.layout.min_height = panel_min_heights.reduce(function(a,b){ return a+b; });
// Call setDimensions() in case updated minimums need to be applied, which also calls positionPanels()
this.setDimensions();
return this.panels[panel.id];
};
// Automatically position panels based on panel positioning rules and values
// If the plot is resizable then recalculate dimensions and position from proportional values
LocusZoom.Instance.prototype.positionPanels = function(){
var id;
for (id in this.panels){
if (this.layout.resizable){
this.panels[id].layout.width = this.panels[id].layout.proportional_width * this.layout.width;
this.panels[id].layout.height = this.panels[id].layout.proportional_height * this.layout.height;
this.panels[id].layout.origin.x = this.panels[id].layout.proportional_origin.x * this.layout.width;
this.panels[id].layout.origin.y = this.panels[id].layout.proportional_origin.y * this.layout.height;
}
this.panels[id].setOrigin();
this.panels[id].setDimensions();
}
};
// Create all instance-level objects, initialize all child panels
LocusZoom.Instance.prototype.initialize = function(){
// Create an element/layer for containing mouse guides
var mouse_guide_svg = this.svg.append("g")
.attr("class", "lz-mouse_guide").attr("id", this.id + ".mouse_guide");
var mouse_guide_vertical_svg = mouse_guide_svg.append("rect")
.attr("class", "lz-mouse_guide-vertical").attr("x",-1);
var mouse_guide_horizontal_svg = mouse_guide_svg.append("rect")
.attr("class", "lz-mouse_guide-horizontal").attr("y",-1);
this.mouse_guide = {
svg: mouse_guide_svg,
vertical: mouse_guide_vertical_svg,
horizontal: mouse_guide_horizontal_svg
};
// Create an element/layer for containing various UI items
var ui_svg = this.svg.append("g")
.attr("class", "lz-ui").attr("id", this.id + ".ui")
.style("display", "none");
this.ui = {
svg: ui_svg,
parent: this,
is_resize_dragging: false,
show: function(){
this.svg.style("display", null);
},
hide: function(){
this.svg.style("display", "none");
},
initialize: function(){
// Resize handle
if (this.parent.layout.resizable == "manual"){
this.resize_handle = this.svg.append("g")
.attr("id", this.parent.id + ".ui.resize_handle");
this.resize_handle.append("path")
.attr("class", "lz-ui-resize_handle")
.attr("d", "M 0,16, L 16,0, L 16,16 Z");
var resize_drag = d3.behavior.drag();
//resize_drag.origin(function() { return this; });
resize_drag.on("dragstart", function(){
this.resize_handle.select("path").attr("class", "lz-ui-resize_handle_dragging");
this.is_resize_dragging = true;
}.bind(this));
resize_drag.on("dragend", function(){
this.resize_handle.select("path").attr("class", "lz-ui-resize_handle");
this.is_resize_dragging = false;
}.bind(this));
resize_drag.on("drag", function(){
this.setDimensions(this.layout.width + d3.event.dx, this.layout.height + d3.event.dy);
}.bind(this.parent));
this.resize_handle.call(resize_drag);
}
// Render all UI elements
this.render();
},
render: function(){
if (this.parent.layout.resizable == "manual"){
this.resize_handle
.attr("transform", "translate(" + (this.parent.layout.width - 17) + ", " + (this.parent.layout.height - 17) + ")");
}
}
};
this.ui.initialize();
// Create the curtain object with svg element and drop/raise methods
var curtain_svg = this.svg.append("g")
.attr("class", "lz-curtain").style("display", "none")
.attr("id", this.id + ".curtain");
this.curtain = {
svg: curtain_svg,
drop: function(message){
this.svg.style("display", null);
if (typeof message != "undefined"){
try {
this.svg.select("text").selectAll("tspan").remove();