-
Notifications
You must be signed in to change notification settings - Fork 2
/
ParallelCoordinates.js
1820 lines (1510 loc) · 72.9 KB
/
ParallelCoordinates.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
// Add spaces and a dot to the number
// '1234567.1234 -> 1 234 567.12'
function numberWithSpaces(x) {
try{
let parts = (parseFloat(x).toFixed(5))
.toString()//.replace(/\.0+$/,'')
.split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
parts[1] = (parts[1] !== undefined) ? parts[1].replace(/([0-9]+(\.[0-9]+[1-9])?)(\.?0+$)/,'$1')
.replace(/\.?0+$/,"") : '';
let result = (parts[1] !== '') ? parts.join(".") : parts[0];
return (result === "") ? '0' : result;
}
catch (e) {
console.warn('Exception in numberWithSpaces: ' + e.message);
return x;
}
}
// RGB color object to hex string
function rgbToHex(color) {
return "#" + ((1 << 24) + (color.r * 255 << 16) + (color.g * 255 << 8)
+ color.b * 255).toString(16).slice(1);
}
class ParallelCoordinates {
// ********
// Constructor
//
// Passes all arguments to updateData(...)
// ********
constructor(element_id, dimension_names, data_array, clusters_list, clusters_color_scheme, options = {}) {
// Save the time for debug purposes
this._timeStart = Date.now();
// This function allows to jump to a certain row in a DataTable
$.fn.dataTable.Api.register('row().show()', function () {
let page_info = this.table().page.info(),
// Get row index
new_row_index = this.index(),
// Row position
row_position = this.table().rows()[0].indexOf(new_row_index);
// Already on right page ?
if (row_position >= page_info.start && row_position < page_info.end) {
// Return row object
return this;
}
// Find page number
let page_to_display = Math.floor(row_position / this.table().page.len());
// Go to that page
this.table().page(page_to_display);
// Return row object
return this;
});
// This is used to manipulate d3 objects
// e.g., to move a line on a graph to the front
// https://github.com/wbkd/d3-extended
d3.selection.prototype.moveToFront = function () {
return this.each(function () {
this.parentNode.appendChild(this);
});
};
d3.selection.prototype.moveToBack = function () {
return this.each(function () {
let firstChild = this.parentNode.firstChild;
if (firstChild) {
this.parentNode.insertBefore(this, firstChild);
}
});
};
// Ability to count a number of a certain element in an array
if (!Array.prototype.hasOwnProperty('count'))
Object.defineProperties(Array.prototype, {
count: {
value: function (value) {
return this.filter(x => x == value).length;
}
}
});
// Update data and draw the graph
if (arguments.length > 0) {
this.updateData(element_id, dimension_names, data_array, clusters_list, clusters_color_scheme, options);
if (this._debug)
console.log("Parallel Coordinates creation finished in %ims", Date.now() - this._timeStart);
}
}
// ********
// Data loading function
//
// Parameters:
// element_id - DOM id where to attach the Parallel Coordinates
// feature_names - array with feature names
// data_array - array with all data about objects under consideration
// clusters_list - array with all clusters in those data
// clusters_color_scheme - array with the color scheme
// options - graph options
//
// ********
updateData(element_id, feature_names, data_array, clusters, clusters_color_scheme, options = {}) {
// Save the time for debug purposes
this._timeUpdate = Date.now();
// Store the new values
this.element_id = element_id;
// Update arrays
this._data = {
_features: feature_names,
_objects: data_array,
_color: clusters,
_color_scheme: clusters_color_scheme
};
// Debug statistics counters
this._search_quantity = 0;
this._search_time = 0;
this._search_time_min = -1;
this._search_time_max = -1;
this.updateOptions(options);
}
updateOptions(options = {}) {
// If options does not have 'draw' option, make default one
if (!options.hasOwnProperty('draw') &&
(typeof this.options === 'undefined' ||
!this.options.hasOwnProperty('draw'))) {
options.draw = {
mode: "print", // Possible values: 'print', 'cluster'
//, first_column_name: "Clusters" // Custom name for 'clusters' tab in the table
parts_visible: {
table: true,
cluster_table: true,
hint: true,
selector: true,
table_colvis: true
},
interpolation: 'monotone', // Possible values: 'monotone', 'linear'
};
this.options = options;
} else if (typeof this.options === 'undefined') this.options = options;
else if (options.hasOwnProperty('draw')) this.options.draw = options.draw;
// Throw an error if a wrong draw mode selected
if (!["print", "cluster"].includes(this.options.draw['mode']))
throw "Wrong mode value! Possible values: 'print', 'cluster', got: '" + value + "'";
////// todo: options.draw.parts_visible checks
// If options does not have 'skip' option, make default one
// Default is to show 5 first lanes
if (!options.hasOwnProperty('skip') && !this.options.hasOwnProperty('skip'))
options.skip = {
dims: {
mode: "show", // Possible values: 'hide', 'show', 'none'
values: this._data._features.slice(0,
(this._data._features.length >= 5) ? 5 : this._data._features.length),
strict_naming: true
}
};
else if (options.hasOwnProperty('skip')) this.options.skip = options.skip;
if (!options.hasOwnProperty('worker') && !this.options.hasOwnProperty('worker')) {
options.worker = {
enabled: true,
offscreen: false
}
}
if (!window.Worker) this.options.worker.enabled = false;
this._data.options = this.options;
// todo: options.skip checks
// Check debug settings
if (options.hasOwnProperty('debug')) this._debug = options.debug;
else if (!this.hasOwnProperty('_debug')) this._debug = false;
// Initiate the arrays and draw the stuff
this._prepareGraphAndTables();
// Show update time when debug enabled
if (this._debug)
console.log("Parallel Coordinates updated in %ims (%ims from creation)",
Date.now() - this._timeUpdate, Date.now() - this._timeStart);
//console.log(this);
}
_prepareGraphAndTables() {
// A link to this ParCoord object
var _PCobject = this;
// In case Web Workers are supported, use them
if (this.options.worker.enabled) {
// Surprize! First we need to create the worker!
this._worker = this._create_worker();
// Tell worker to prepare
this._call('run', '_prepare_worker', _PCobject._prepare_worker);
// Register necessary functions
this._call('register', '_prepare_d3', _PCobject._prepare_d3);
this._call('register', '_prepare_graph', _PCobject._prepare_graph);
this._call('register', '_update_canvas_size', _PCobject._update_canvas_size);
this._call('register', '_process_data', _PCobject._process_data);
this._call('register', '_draw_foreground', _PCobject._draw_foreground);
this._call('register', '_draw_background', _PCobject._draw_background);
this._call('register', '_calculate_brushes', _PCobject._calculate_brushes);
// Worker callback
this._worker.onmessage = function (e) {
let response = e.data;
//console.log(response);
// When function _process_data is registered - make it process the data
if (response.type === 'register') {
if (response.name === '_process_data')
_PCobject._call('process', '_process_data', '', _PCobject._data);
}
// 'process' callbacks
if (response.type === 'process') {
//console.log('some_process', response.name, response.result);
// When the data is processed - continue building the DOM
if (response.name === '_process_data') {
_PCobject._data = response.result;
_PCobject._prepareDOM();
}
// When the graph dimensions are calculated - remember them
if (response.name === '_prepare_graph')
{
_PCobject._data._width = response.result._width;
_PCobject._data._calculated_height = response.result._calculated_height;
_PCobject._data._features_strings_length = response.result._features_strings_length;
_PCobject._data._features_strings_params = response.result._features_strings_params;
// Arrays for x and y data, and brush dragging
_PCobject._data._dragging = {};
}
// Draw callbacks
if (response.name === '_draw_background' || response.name === '_draw_foreground') {
if (response.name === '_draw_background') _PCobject._worker._running_bg = false;
else _PCobject._worker._running_fg = false;
if (_PCobject._worker._bg_needs_redraw || _PCobject._worker._fg_needs_redraw) {
_PCobject._redraw(_PCobject._worker._bg_needs_redraw, _PCobject._worker._fg_needs_redraw);
_PCobject._worker._bg_needs_redraw = false;
_PCobject._worker._fg_needs_redraw = false;
}
_PCobject._loading.style('display', 'none');
_PCobject._worker._calculating = false;
}
// Brush calculation callback
if (response.name === '_calculate_brushes') {
_PCobject._worker._running_brushes = false;
if (_PCobject._worker._fg_needs_brushes) {
_PCobject._worker._fg_needs_brushes = false;
_PCobject._request_brushes(_PCobject._worker._brushes);
} else {
_PCobject._visible = response.result;
_PCobject._datatable.draw();
_PCobject._redraw();
}
_PCobject._loading.style('display', 'none');
_PCobject._worker._calculating = false;
}
}
// Custom callbacks
if (_PCobject._worker._callback !== undefined) {
_PCobject._worker._callback.bind(_PCobject)();
_PCobject._worker._callback = undefined;
}
}
} else {
// If Workers are unavaliable, process data in the main thread
this._process_data();
}
// Clear the whole div if something is there
$("#" + this.element_id).empty();
// 'Building graph' placeholder while everything is calculated
this._loading = d3.select("#" + this.element_id)
.append('div')
.attr('class', 'pc-loading')
.text('Building the diagram, please wait... ');
// A selectBox with chosen features
if (this.options.draw.parts_visible.selector) {
this._selector_p = d3.select("#" + this.element_id)
.append('p')
.text('Select the features displayed on the Parallel Coordinates graph:')
.style('display', 'none');
this._selector_p
.append('select')
.attr({
'class': 'select',
'id': 's' + this.element_id
});
}
// Append an SVG to draw lines on
this._container = d3.select("#" + this.element_id)
.append('div')
.attr('class', 'pc-container')
.style('display', 'none');
this._svg_container = this._container.append("div")
.attr('class', 'pc-svg-container');
// Create necessary divs
this._graph_header = this._svg_container.append("div");
this._graph_placeholder = this._svg_container.append('div').attr('class', 'pc-graph-placeholder');
// Create canvases
this._canvas_background = this._svg_container.append('canvas');
this._canvas_foreground = this._svg_container.append('canvas');
// Check if OffscreenCanvas enabled
this.options.worker.offscreen = this.options.worker.offscreen &&
typeof this._canvas_foreground.node().transferControlToOffscreen === "function";
// If so, transfer control to it
if (this.options.worker.offscreen) {
this._canvas_foreground_t = this._canvas_foreground.node().transferControlToOffscreen();
this._canvas_background_t = this._canvas_background.node().transferControlToOffscreen();
}
// else - draw in main thread
else {
if (this._d3 === undefined) this._d3 = {};
this._d3.foreground = this._canvas_foreground.node().getContext('2d');
this._d3.background = this._canvas_background.node().getContext('2d');
}
// Clear canvas variable from previous runs
delete this._canvas_loaded;
// Create the SVG
this._graph = this._svg_container.append("svg");
// Add a tooltip for long names
this._tooltip = this._svg_container.append("div")
.attr('class', 'tooltip')
.style('opacity', 0);
// A hint on how to use
if (this.options.draw.parts_visible.hint)
this._svg_hint = this._svg_container
.append('p')
.html('Use the Left Mouse Button to select a curve and the corresponding line in the table <br>' +
'Hover over the lines with mouse to see the row in the table');
// Currently selected line id
this._selected_line = -1;
// Add the table below the ParCoords
if (this.options.draw.parts_visible.table)
this._container
.append("div")
.attr({
"id": "t" + this.element_id + "_wrapper-outer",
'class': 'pc-table-wrapper'
});
// If Workers unavailable - continue preparing DOM
if (!this.options.worker.enabled) {
this._prepare_d3();
this._prepare_graph();
this._prepareDOM();
}
}
_prepareDOM() {
// A link to this ParCoord object
var _PCobject = this;
// Options for selectBox
if (this.options.draw.parts_visible.selector) {
this._selectBox = $('#s' + this.element_id).select2({
closeOnSelect: false,
data: _PCobject._data._features.map((d) => {
return {id: d, text: d, selected: _PCobject._data._graph_features.includes(d)};
}),
multiple: true,
width: 'auto'
})
// If the list changes - redraw the graph
.on("change.select2", () => {
this._data._graph_features = $('#s' + this.element_id).val();
this.options.skip.dims.values = this._data._graph_features;
this._prepare_d3();
if (this.options.worker.enabled) {
this._call('process', '_prepare_graph', '',
{ _graph_features: this._data._graph_features },
this._createGraph);
}
else {
this._createGraph();
}
});
this._selectBox.data('select2').$container.css("display", "block");
}
// Draw the graph and the table
this._createGraph();
if (this.options.draw.parts_visible.table) this._createTable();
if (this.options.draw['mode'] === 'cluster' &&
this.options.draw.parts_visible.cluster_table) {
this._ci_div = this._container.append('div')
.attr({
"class": 'pc-cluster-table-wrapper',
"id": "pc-cluster-" + this.element_id
});
this._createClusterInfo();
if (this._data._height > 1000)
$('#pc-cluster-' + this.element_id).insertAfter('#t' + this.element_id + '_wrapper');
}
// When the data is ready - remove the placeholder
this._loading.style('display', 'none');
this._container.style('display', '');
if (this.options.draw.parts_visible.selector) this._selector_p.style('display', '');
return this;
}
// Function to draw the graph
_createGraph(static_height = null) {
// A link to this ParCoord object
var _PCobject = this;
// Clear the graph div if something is there
if (this._svg !== undefined) this._svg.remove();
// Initialize a search result with all objects visible and
// 'visible' data array with lines on foreground (not filtered by a brush)
this._search_results = this._data._ids;
this._visible = this._data._ids;
if (this._graph_popup !== undefined) this._graph_popup.remove();
this._graph_popup = this._graph_header.append("div")
.attr('class', 'pc-graph-header')
.style('display', 'none');
// Shift the draw space
this._svg = this._graph.append("g")
.attr("transform", "translate(" +
this._data._margin.left + "," + this._data._margin.top + ")");
// Modify the graph height in case of ordinal values
if (typeof static_height === 'boolean') this._data._static_height = static_height;
// Create popup saying the user he can adjust the height
if (this._data._features_strings_params.overflow_count > 0) {
let popup_text = (this._data._features_strings_params.overflow_count > 1) ?
'<b>Info.</b> Multiple features have too many unique values, the graph height was ' +
'automatically increased to be human readable. ' :
'<b>Info.</b> Feature "' + this._data._features_strings_params.name + '" has too many unique ' +
'values, the graph height was automatically increased to be human readable. ',
popup_link_text = ' <u><i>Click here to return to the default height.</i></u>';
this._data._height = this._data._calculated_height;
if (this._data._static_height) {
this._data._height = this._data._default_height;
popup_text = (this._data._features_strings_params.overflow_count > 1) ?
'<b>Info.</b> Multiple features have too many unique values, the graph height can be ' +
'increased to be human readable. ' :
'<b>Info.</b> Feature "' + this._data._features_strings_params.name + '" has too many unique ' +
'values, the graph height can increased to be human readable. ',
popup_link_text = ' <u><i>Click here to increase the height.</i></u>';
}
$('#pc-cluster-' + this.element_id).insertAfter('#t' + this.element_id + '_wrapper' +
((this._data._height > 1000) ? '' : '-outer'));
this._graph_popup
.style('display', '')
.append('p')
.attr('class', 'pc-closebtn')
.on('click', () => {
this._graph_popup.style('display', 'none')
})
.html('×');
this._graph_popup
.append('span')
.attr('class', 'pc-graph-header-text')
.html(popup_text);
this._graph_popup
.append('span')
.attr('class', 'pc-graph-header-text')
.on('click', () => this._createGraph(!this._data._static_height))
.html(popup_link_text);
} else this._data._height = this._data._default_height;
this._prepare_d3();
if (this.options.worker.enabled && this.options.worker.offscreen) {
if (this._canvas_loaded === true)
this._call('process', '_update_canvas_size', '',
{_height: this._data._height,
_width: this._data._width,
options: this.options});
this._call('process', '_prepare_d3', '',
{_graph_features: this._data._graph_features,
_height: this._data._height,
_margin: this._data._margin,
options: this.options});
}
else{
this._update_canvas_size();
}
// Change the SVG size to draw lines on
this._graph_placeholder.style({
'width': this._data._width + this._data._margin.left + this._data._margin.right + 'px',
'height': this._data._height + this._data._margin.top + this._data._margin.bottom + 'px'
});
this._graph
.attr({
"width": this._data._width + this._data._margin.left + this._data._margin.right,
"height": this._data._height + this._data._margin.top + this._data._margin.bottom
});
this._canvas_foreground
.style({'margin-left': this._data._margin.left + 'px', "margin-top": this._data._margin.top + 'px'});
this._canvas_background
.style({'margin-left': this._data._margin.left + 'px', "margin-top": this._data._margin.top + 'px'});
this._load_canvas();
let time = performance.now();
if (this.options.worker.offscreen)
_PCobject._redraw(true);
else{
// Grey background lines for context
this._background = this._svg.append("g")
.attr("class", "background")
.selectAll("path")
.data(this._data._line_data)
.enter().append("path")
.attr("d", this._path.bind(this));
// Foreground lines
this._foreground = this._svg.append("g")
.attr("class", "foreground")
.selectAll("path")
.data(this._data._line_data)
.enter().append("path")
.attr("d", this._path.bind(this))
// Cluster color scheme is applied to the stroke color
.attr("stroke", (d, i) => (
(this.options.draw['mode'] === "cluster")?
this._data._color_scheme[this._data._color[i]].color:
"#0082C8")
)
.attr("stroke-opacity", "0.4")
// When mouse is over the line, make it bold and colorful, move to the front
// and select a correspoding line in the table below
.on("mouseover", function (d, i) {
if (_PCobject._selected_line !== -1) return;
if (_PCobject._isSafari) return;
let time = Date.now();
$(this).addClass("bold");
d3.select(this).moveToFront();
if (_PCobject.options.draw.parts_visible.table) {
let row = _PCobject._datatable.row((idx, data) => data === _PCobject._parcoordsToTable(i));
row.show().draw(false);
_PCobject._datatable.rows(row).nodes().to$().addClass('table-selected-line');
}
// In case of debug enabled
// Write time to complete the search, average time, minimum and maximum
if (_PCobject._debug)
{
time = Date.now() - time;
_PCobject._search_time += time;
_PCobject._search_quantity += 1;
if (_PCobject._search_time_min === -1)
{
_PCobject._search_time_min = time;
_PCobject._search_time_max = time;
}
if (_PCobject._search_time_min > time) _PCobject._search_time_min = time;
else if (_PCobject._search_time_max < time) _PCobject._search_time_max = time;
console.log("Search completed for %ims, average: %sms [%i; %i].",
time, (_PCobject._search_time/_PCobject._search_quantity).toFixed(2),
_PCobject._search_time_min, _PCobject._search_time_max);
}
})
// When mouse is away, clear the effect
.on("mouseout", function (d, i) {
if (_PCobject._selected_line !== -1) return;
if (_PCobject._isSafari) return;
$(this).removeClass("bold");
if (_PCobject.options.draw.parts_visible.table) {
let row = _PCobject._datatable.row((idx, data) => data === _PCobject._parcoordsToTable(i));
_PCobject._datatable.rows(row).nodes().to$().removeClass('table-selected-line');
}
})
// Mouse click selects and deselects the line
.on("click", function (d, i) {
if (_PCobject._isSafari) return;
if (_PCobject._selected_line === -1) {
_PCobject._selected_line = i;
$(this).addClass("bold");
d3.select(this).moveToFront();
if (_PCobject.options.draw.parts_visible.table) {
let row = _PCobject._datatable.row((idx, data) => data === _PCobject._parcoordsToTable(i));
row.show().draw(false);
_PCobject._datatable.rows(row).nodes().to$().addClass('table-selected-line');
}
}
else if (_PCobject._selected_line === i) _PCobject._selected_line = -1;
});
}
// Add a group element for each dimension
this._g = this._svg.selectAll(".dimension")
.data(this._data._graph_features)
.enter().append("g")
.attr("class", "dimension")
.attr("transform", function (d) { return "translate(" + _PCobject._d3._x(d) + ")"; })
.call(d3.behavior.drag()
.origin(function (d) { return {x: this._d3._x(d)}; }.bind(this))
.on("dragstart", function (d) {
this._data._dragging[d] = this._d3._x(d);
if (!this.options.worker.offscreen) this._background.attr("visibility", "hidden");
}.bind(this))
.on("drag", function (d) {
this._data._dragging[d] = Math.min(this._data._width, Math.max(0, d3.event.x));
this._data._graph_features.sort(function (a, b) {
return this._position(a) - this._position(b);
}.bind(this));
this._d3._x.domain(this._data._graph_features);
this._g.attr("transform", function (d) {
return "translate(" + this._position(d) + ")";
}.bind(this));
if (this.options.worker.offscreen) this._redraw(true);
else this._foreground.attr("d", this._path.bind(this));
}.bind(this))
.on("dragend", function (d, i) {
_PCobject._transition(d3.select(this))
.attr("transform", "translate(" + _PCobject._d3._x(d) + ")")
.each("end", () => {
if (_PCobject.options.worker.offscreen) {
_PCobject._observer.disconnect();
delete _PCobject._data._dragging[_PCobject._observer._feature];
_PCobject._redraw(false);
}
});
if (!_PCobject.options.worker.offscreen){
delete _PCobject._data._dragging[d];
_PCobject._transition(_PCobject._foreground).attr("d", _PCobject._path.bind(_PCobject));
_PCobject._background
.attr("d", _PCobject._path.bind(_PCobject))
.transition()
.delay(500)
.duration(0)
.attr("visibility", null);
}
else{
const config = {attributes: true, childList: false, subtree: false};
const callback = function (mutationsList, observer) {
// Use traditional 'for loops' for IE 11
for (let mutation of mutationsList) {
if (mutation.type === 'attributes') {
_PCobject._data._dragging[observer._feature] =
d3.transform(d3.select(mutation.target).attr('transform')).translate[0];
_PCobject._redraw(true);
}
}
};
// Create an observer instance linked to the callback function
_PCobject._observer = new MutationObserver(callback);
_PCobject._observer._feature = d;
// Start observing the target node for configured mutations
_PCobject._observer.observe(this, config);
}
}));
// Function to limit the length of the strings
let format = (x) => {
if (x instanceof Date) return Intl.DateTimeFormat('en-GB', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric'
//minute: 'numeric'
}).format(x) + 'h';
return isNaN(x) ? x : numberWithSpaces(x);
},
limit = ((x, width, font) => {
let sliced = false;
while (_PCobject._getTextWidth((sliced) ? x + '...' : x, font) > width) {
x = x.slice(0, -1);
sliced = true;
}
return x + ((sliced) ? '...' : '');
});
var show_tooltip = (d, width) => {
if (!limit(d, width, _PCobject._data._font).endsWith('...')) return;
//on mouse hover show the tooltip
_PCobject._tooltip.transition()
.duration(200)
.style("opacity", .9);
_PCobject._tooltip.html(d)
.style("left", (d3.event.clientX + 20) + "px")
.style("top", (d3.event.clientY) + "px");
};
// Add an axis and titles
this._g.append("g")
.attr("class", "axis")
.each(function (d) {
d3.select(this).call(_PCobject._d3._axis.scale(_PCobject._d3._y[d]));
})
.append("text")
.attr({
"y": -9,
"class": "pc-titles-text"
})
.text((text) => limit(text, _PCobject._data._column_width - 15, _PCobject._data._font))
.on("mouseover", (d) => show_tooltip(d, _PCobject._data._column_width - 15))
.on("mouseout", () => _PCobject._tooltip.transition().duration(500).style("opacity", 0));
// Limit the tick length and show a tooltip on mouse hover
d3.selectAll('.tick')
.on("mouseover", (obj) => show_tooltip(format(obj), _PCobject._data._column_width - 24))
.on("mouseout", () => _PCobject._tooltip.transition().duration(500).style("opacity", 0))
.select('text')
.text(obj => limit(format(obj), _PCobject._data._column_width - 24, _PCobject._data._font));
// Add and store a brush for each axis
this._g.append("g")
.attr("class", "brush")
.each(function (d) {
d3.select(this).call(
_PCobject._d3._y[d].brush = d3.svg.brush()
.y(_PCobject._d3._y[d])
.on("brushstart", _PCobject._brushstart)
.on("brush", _PCobject._brush.bind(_PCobject)));
})
.selectAll("rect")
.attr("x", -8)
.attr("width", 16);
}
// Creates a table below the ParallelCoordinates graph
_createTable() {
// A link to this ParCoord object
var _PCobject = this;
// Clear the table div if something is there
$('#t' + this.element_id + "_wrapper-outer").empty();
// Add table to wrapper
d3.select("#t" + this.element_id + "_wrapper-outer")
.append("table")
.attr({
"id": "t" + this.element_id,
"class": "table hover"
});
// Array with the list of columns to hide
let hide = (this.options.skip.hasOwnProperty('table_hide_columns')) ?
this.options.skip.table_hide_columns : [];
// Map headers for the tables
this._theader = this._data._features.map(row => {
return {
title: row,
visible: !hide.includes(row),
// Add spaces and remove too much numbers after the comma
"render": function (data, type, full, config) {
if (type === 'display' && !isNaN(data))
return numberWithSpaces(parseFloat(Number(data).toFixed(2)));
if (_PCobject._isDate(_PCobject._data._features[config.col])){
let date = new Date(data.replace(/-/g, "/").split(/\.(?=[^\.]+$)/)[0]);
return Intl.DateTimeFormat('en-GB', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
}).format(date);
}
return data;
}
};
});
// Vars for table and its datatable
this._table = $('#t' + this.element_id);
this._datatable = this._table.DataTable({
data: this._data._cells,
columns: this._theader,
mark: true,
dom: 'Blfrtip',
colReorder: true,
buttons: ((this.options.draw.parts_visible.table_colvis) ? ['colvis'] : []).concat(['copy', 'csv']),
"search": {"regex": true},
//fixedColumns: true,
// Make colors lighter for readability
"rowCallback": (row, data) => {
$(row).children().each((i, el) => {
el.style.minWidth =
Math.min(this._getTextWidth(el.textContent, "'Lato' 14px sans-serif") * 1.5, 500) + 'px';
});
if (this.options.draw['mode'] === "cluster")
$(row).children().css('background', data[data.length - 1] + "33");
},
// Redraw lines on ParCoords when table is ready
"fnDrawCallback": () => {
_PCobject._on_table_ready(_PCobject);
}
});
this._fix_css_in_table('t' + this.element_id);
// Add bold effect to lines when a line is hovered over in the table
if (!this.options.worker.offscreen)
$(this._datatable.table().body())
.on("mouseover", 'tr', function (d, i) {
if (_PCobject._selected_line !== -1) return;
let line = _PCobject._foreground[0][_PCobject._tableToParcoords(
_PCobject._datatable.row(this).data())];
$(line).addClass("bold");
d3.select(line).moveToFront();
$(_PCobject._datatable.rows().nodes()).removeClass('table-selected-line');
$(_PCobject._datatable.row(this).nodes()).addClass('table-selected-line');
})
.on("mouseout", 'tr', function (d) {
if (_PCobject._selected_line !== -1) return;
$(_PCobject._datatable.rows().nodes()).removeClass('table-selected-line');
$(_PCobject._foreground[0][
_PCobject._tableToParcoords(_PCobject._datatable.row(this).data())
]).removeClass("bold");
})
// If the line is clicked, make it 'selected'. Remove this status on one more click.
.on("click", 'tr', function (d, i) {
if (_PCobject._selected_line === -1) {
_PCobject._selected_line = _PCobject._tableToParcoords(_PCobject._datatable.row(this).data());
let line = _PCobject._foreground[0][_PCobject._selected_line];
$(line).addClass("bold");
d3.select(line).moveToFront();
_PCobject._datatable.rows(this).nodes().to$().addClass('table-selected-line');
}
else if (_PCobject._selected_line === _PCobject._tableToParcoords(
_PCobject._datatable.row(this).data())) {
let line = _PCobject._foreground[0][_PCobject._selected_line];
$(line).removeClass("bold");
_PCobject._selected_line = -1;
_PCobject._datatable.rows(this).nodes().to$().removeClass('table-selected-line');
}
});
// Add footer elements
this._table.append(
$('<tfoot/>').append($('#t' + this.element_id + ' thead tr').clone())
);
// Add inputs to those elements
$('#t' + this.element_id + ' tfoot th').each(function (i, x) {
$(this).html('<input type="text" placeholder="Search" id="t' +
_PCobject.element_id + 'Input' + i + '"/>');
});
// Apply the search
this._datatable.columns().every(function (i, x) {
$('#t' + _PCobject.element_id + 'Input' + i).on('keyup change', function () {
_PCobject._datatable
.columns(i)
.search(this.value, true)
.draw();
});
});
// Callback for _search_results filling
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex, rowData, counter) {
if (settings.sTableId !== "t" + _PCobject.element_id) return true;
if (counter === 0) _PCobject._search_results = [];
if (_PCobject._visible.some(x => Object.values(x).every(y => rowData.includes(y)))) {
_PCobject._search_results.push(rowData.filter((x,i)=>(i !== rowData.length-1)));
return true;
}
return false;
}
);
}
// Create cluster info buttons (which call the table creation)
_createClusterInfo() {
// Add a div to hold a label and buttons
this._ci_buttons_div = this._ci_div
.append('div')
.attr('class', 'ci-buttons-wrapper');
// Add 'Choose Cluster' text to it
this._ci_buttons_div
.append('label')
.text("Choose Cluster");
// Add a div for the table
this._ci_table_div = this._ci_div.append('div');
//Add a div to hold the buttons after the label
this._ci_buttons = this._ci_buttons_div
.append('div')
.attr({
'class': 'ci-button-group',
'id': 'ci_buttons_' + this.element_id
});
let scheme = this._data._color_scheme,
scale = d3.scale.sqrt()
.domain([scheme.min_count, scheme.max_count])
.range([100, 0]);
// Add corresponding buttons to every color
this._ci_buttons
.selectAll("a")
.data(scheme.order)
.enter().append('a')
.attr({