-
Notifications
You must be signed in to change notification settings - Fork 0
/
borrar.py
4468 lines (3317 loc) · 203 KB
/
borrar.py
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
/* Original code taken from https://github.com/cpsievert/LDAvis */
/* Copyright 2013, AT&T Intellectual Property */
/* MIT Licence */
'use strict';
var global_terms_1;
var global_lamData;
var merged_topic_to_delete = [];
var name_merged_topic_to_delete = [];
var old_topic_model_states = []; //here we are going to save previous topic models. This should be a array of dictionaries
var current_relevant_documents_topic_splitting;
var global_topic_splitting_data;
var list_terms_for_topic_splitting = [];
var slider_topic_splitting_values = {};
var is_human_in_the_loop;
var scenario_2_is_baseline_metric;
var is_first_time_sankey_diagram = true;
var actions_across_time = [];
var global_sankey_links_filtered;
var sankey_topics_automatic_match;
var name_topics_sankey = {};
var inverted_links_filtered;
var is_tutorial = 'undefined';
var testing;
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
function isTutorial(){
//var curren_url = window.location.href;
var queryString = window.location.search;
var urlParams = new URLSearchParams(queryString);
var scenario = urlParams.get('scenario')
if(scenario == null || scenario == 'single_demo' || scenario == 'multi_demo_baseline' || scenario == 'multi_demo'){
is_tutorial = true;
}
else{
is_tutorial = false;
}
}
isTutorial()
function save_users_actions_across_time(action, timestamp){
//console.log(action, timestamp);
actions_across_time.push({
"timestamp": timestamp,
"action": action
});
}
var userId = new Date() || null; // Replace your_user_id with your own if available.
window.hj('identify', userId, {
actions_across_time: actions_across_time
// Add your own custom attributes here. Some EXAMPLES:
// 'Signed up': '2019—06-20Z', // Signup date in ISO-8601 format.
// 'Last purchase category': 'Electronics', // Send strings with quotes around them.
// 'Total purchases': 15, // Send numbers without quotes.
// 'Last purchase date': '2019-06-20Z', // Send dates in ISO-8601 format.
// 'Last refund date': null, // Send null when no value exists for a user.
});
//this function allow to access some values on the matrix_sankey
function get_new_omega(old_omega){
if(type_vis==2 && scenario_2_is_baseline_metric == true){
return old_omega;
}
var values_omega_temp = [0.10, 0.20, 0.30, 0.40, 0.50, 0.60,0.70, 0.80, 0.90];
var new_omega = (1.0-old_omega).toFixed(2);
if(old_omega == 1.00 || old_omega == 0.00){
new_omega = Number(new_omega).toFixed(1);
}
else if ( values_omega_temp.includes(Number(new_omega)) ){
//console.log('la raja')
new_omega = Number(new_omega).toFixed(1);
}
else{
new_omega = Number(new_omega).toFixed(2);
}
return new_omega;
}
save_users_actions_across_time('session_start', new Date());
var testing;
if(type_vis== 2){
if( Object.keys(matrix_sankey).length == 1){
scenario_2_is_baseline_metric = true;
}
else{
scenario_2_is_baseline_metric = false;
}
}
var LDAvis = function(to_select, data_or_file_name) {
// This section sets up the logic for event handling
var vis_state = {
lambda: 0.6,
min_value_filtering:-1.0,
max_value_filtering: 1.0,
lambda_lambda_topic_similarity:0.2, //que tanta info tiene vector top keywords y que tanta info tiene vector top relevant documents
lambda_topic_similarity:-1.0, //este filtra las lineas (el ancho que de similitud). If this value is very low, it is going to show all the paths.
topic: 1,
term: ""
};
//for the user study. The omega value will be random
// Set up a few 'global' variables to hold the data:
var K, // number of topics
mdsData, // (x,y) locations and topic proportions
//mdsData3, // topic proportions for all terms in the viz
lamData, // all terms that are among the top-R most relevant for all topics, lambda values
lambda = {
old: 0.6,
current: 0.6
},
lambda_lambda_topic_similarity = { //pondera la importancia de vector documento y vector top relevant keywords
old: 0.8,
current: 0.8
},
lambda_topic_similarity = { //mide la similitud de los paths en el sankey diagram
old: 0.9,
current: 0.9
},
color1_1 = "#BE7CF0", //violeta
color1_2 = "#57009E", //morado
color2_1 = "#29F0B6", //"red", //"#6BF0A7", //verde claro
color2_2 = "#00A385"; //"blue"; //"00A385"; //"13A383"; //verde oscuro
// Set the duration of each half of the transition:
var duration = 750;
// Set global margins used for everything
var margin = {
top: 30,
right: 30,
bottom: 70,
left: 30
},
mdswidth = 530, //530 //LA IDEA ES ELIMINAR MDSWIFTH Y MEDSHEIGHT. ESTO DEBE SER RESPONSIVE!!
mdsheight = 530,
barwidth = 530, //LA IDEA ES ELIMINAR TODO ESTO QUE ES BAR WIDTH, BARHEIGHT, ETC.
barheight = 530,
termwidth = 90; // width to add between two panels to display terms
// controls how big the maximum circle can be
// doesn't depend on data, only on mds width and height:
var rMax = 60;
// proportion of area of MDS plot to which the sum of default topic circle areas is set
var circle_prop = 0.20;
// opacity of topic circles:
var base_opacity = 0.2,
highlight_opacity = 0.5;
// lambda selection names are specific to *this* vis
var lambda_select = to_select + "-lambda";
// get rid of the # in the to_select (useful) for setting ID values
var visID = to_select.replace("#", "");
var topicID = visID + "-topic";
var lambdaID = visID + "-lambda";
var lambdaIDRightPanel = lambdaID+"RightPanel";
var termID = "barplotterm-";
var topicReverse = topicID+"-reverse";
var topicEdit = topicID+"-edit";
var topicEdit2 = topicID+"-edit_2";
var topicSplit = topicID+"-split";
var topicMerge = topicID+"-merge";
var leftPanelID = visID + "-leftpanel";
var barFreqsID = "barplot_1";
var barFreqsID_2 = "barplot_2";
var barFreqsIDTopicSplitting = "barplot_1_TopicSplitting";
var sliderDivID = "RelevanceSliderContenedor";
var lambdaLabelID = "RelevanceSliderLabel";
var min_target_node_value = Infinity;
var number_terms_sankey = 20
//esto se ocupa en la comparación de un corpus
var topic_id_model_1 = -1
var topic_id_model_2 = -1
/////////////////////////
////topic mergin
var merging_topic_1 = -1
var splitting_topic = -1
var last_clicked_model_1 = -1
var last_clicked_model_2 = -1
//rename topic variables
var name_topics_circles = {}
var isSettingInitial = true
var number_top_keywords_name = 3
var real_last_clicked_sankey_model_1
var real_last_clicked_sankey_model_2
var BarPlotPanelDivId = 'BarPlotPanelDiv'
var sliderDivIDLambdaTopicSimilarity = "sliderDivLambdaTopicSimilarity"
//to_select = BarPlotPanelDivId
//Get relevant documents from ajax
if(type_vis==1){
save_users_actions_across_time('omega_start_value', (1.0 - lambda_lambda_topic_similarity.current).toFixed(2));
}
if(type_vis === 1){
var relevantDocumentsDict;
$.ajax({
url: "/SingleCorpus_documents",
dataType: 'json',
async: false,
success: function(data) {
relevantDocumentsDict = data
}
});
}
if(type_vis === 2){
var relevantDocumentsDict;
var relevantDocumentsDict_2;
$.ajax({
url: "/MultiCorpora_documents_1",
dataType: 'json',
async: false,
success: function(data) {
relevantDocumentsDict = data
}
});
$.ajax({
url: "/MultiCorpora_documents_2",
dataType: 'json',
async: false,
success: function(data) {
relevantDocumentsDict_2 = data
}
});
}
// sort array according to a specified object key name
// Note that default is decreasing sort, set decreasing = -1 for increasing
// adpated from http://stackoverflow.com/questions/16648076/sort-array-on-key-value
function fancysort(key_name, decreasing) {
decreasing = (typeof decreasing === "undefined") ? 1 : decreasing;
return function(a, b) {
if (a[key_name] < b[key_name])
return 1 * decreasing;
if (a[key_name] > b[key_name])
return -1 * decreasing;
return 0;
};
}
function updateTopicNamesCircles(data, id_topic_splitted){
// set the number of topics to global variable K:
////console.log("este data yo recibi", data)
//console.log('estoy en la funcion update topic names circles')
K = data['mdsDat'].x.length;
// R is the number of top relevant (or salient) words whose bars we display
var R = Math.min(data['R'], 20);
// a (K x 5) matrix with columns x, y, topics, Freq, cluster (where x and y are locations for left panel)
//console.log('Before MDS ', mdsData);
mdsData = [];
for (var i = 0; i < K; i++) {
var obj = {};
for (var key in data['mdsDat']) {
obj[key] = data['mdsDat'][key][i];
}
mdsData.push(obj);
}
//console.log('Step 1: mds data updated', mdsData);
//console.log('step 3, lamdata BEFORE', lamData);
var length_tinfo = Object.keys(data['tinfo']['Term']).length;
//console.log('este es el largo', length_tinfo);
lamData = [];
for (var i = 0; i < length_tinfo ; i++) { // data['tinfo'].Term.length
var obj = {};
for (var key in data['tinfo']) {
obj[key] = data['tinfo'][key][i];
}
if(obj['Freq']==0){
obj['loglift'] = -Infinity;
obj['logprob'] = -Infinity;
}
lamData.push(obj);
}
//console.log('step 3, updated lamdata', lamData);
var dat3 = lamData.slice(0, R);
//console.log('step 4, updated dat3', dat3);
//console.log(data);
//console.log('estos datos a mirar , se debieron actualizar ojala lamdata', lamData,'r',R,'k',K);
//assign name to array
d3.select("#name_topics")
.data(mdsData)
.enter()
.each(
function(d) {
var dat2 = lamData.filter(function(e) {
return e.Category == "Topic"+d.topics;s
});
// define relevance:
for (var i = 0; i < dat2.length; i++) {
dat2[i].relevance = lambda.current * dat2[i].logprob +
(1 - lambda.current) * dat2[i].loglift;
if(isNaN(dat2[i].relevance)){
dat2[i].relevance = -Infinity;
}
}
// sort by relevance:
dat2.sort(fancysort("relevance"));
// truncate to the top R tokens:
var top_terms = dat2.slice(0, number_top_keywords_name);
//console.log('cuales son los nombres de esto', top_terms, 'number top keywords', number_top_keywords_name, 'dat2', dat2);
var name_string = '';
for (var i=0; i < top_terms.length; i++){
name_string += top_terms[i].Term+" "
}
//name_topics_circles[topicID + d.topics] = 'New subtopic '+name_string;
if(d.topics == id_topic_splitted || name_topics_circles[topicID + d.topics] == undefined){
name_topics_circles[topicID + d.topics] = 'New subtopic '+name_string;
}
//name_topics_circles[topicID + d.topics] = name_string
return (topicID + d.topics);
});
}
function visualize(data) {
//console.log('esto es data dentro de la funcion visualize', data);
// set the number of topics to global variable K:
////console.log("este data yo recibi", data)
is_human_in_the_loop = data['human_in_the_loop'];
K = data['mdsDat'].x.length;
// R is the number of top relevant (or salient) words whose bars we display
var R = Math.min(data['R'], 20);
// a (K x 5) matrix with columns x, y, topics, Freq, cluster (where x and y are locations for left panel)
mdsData = [];
for (var i = 0; i < K; i++) {
var obj = {};
for (var key in data['mdsDat']) {
obj[key] = data['mdsDat'][key][i];
}
mdsData.push(obj);
}
// a huge matrix with 3 columns: Term, Topic, Freq, where Freq is all non-zero probabilities of topics given terms
// for the terms that appear in the barcharts for this data
/*
mdsData3 = [];
for (var i = 0; i < data['token.table'].Term.length; i++) {
var obj = {};
for (var key in data['token.table']) {
obj[key] = data['token.table'][key][i];
}
mdsData3.push(obj);
}
*/
// large data for the widths of bars in bar-charts. 6 columns: Term, logprob, loglift, Freq, Total, Category
// Contains all possible terms for topics in (1, 2, ..., k) and lambda in the user-supplied grid of lambda values
// which defaults to (0, 0.01, 0.02, ..., 0.99, 1).
lamData = [];
for (var i = 0; i < data['tinfo'].Term.length; i++) {
var obj = {};
for (var key in data['tinfo']) {
obj[key] = data['tinfo'][key][i];
}
lamData.push(obj);
}
var dat3 = lamData.slice(0, R);
//assign name to array
d3.select("#name_topics")
.data(mdsData)
.enter()
.each(
function(d) {
var dat2 = lamData.filter(function(e) {
return e.Category == "Topic"+d.topics;s
});
// define relevance:
for (var i = 0; i < dat2.length; i++) {
dat2[i].relevance = lambda.current * dat2[i].logprob +
(1 - lambda.current) * dat2[i].loglift;
if(isNaN(dat2[i].relevance)){
dat2[i].relevance = -Infinity;
}
}
// sort by relevance:
dat2.sort(fancysort("relevance"));
// truncate to the top R tokens:
var top_terms = dat2.slice(0, number_top_keywords_name);
var name_string = '';
for (var i=0; i < top_terms.length; i++){
name_string += top_terms[i].Term+" "
}
name_topics_circles[topicID + d.topics] = name_string
return (topicID + d.topics);
});
// Create the topic input & lambda slider forms. Inspired from:
// http://bl.ocks.org/d3noob/10632804
// http://bl.ocks.org/d3noob/10633704
init_forms(topicID, lambdaID);
// When the value of lambda changes, update the visualization
d3.select("#"+lambdaID)
.on("mouseup", function() {
save_users_actions_across_time('change_lambda_left_panel', new Date());
save_users_actions_across_time('change_lambda_left_panel_value', document.getElementById(lambdaID).value);
lambda.old = lambda.current;
lambda.current = document.getElementById(lambdaID).value;
vis_state.lambda = +this.value;
// adjust the text on the range slider
d3.select("#"+lambdaID).property("value", vis_state.lambda);
d3.select("#"+lambdaID + "-value").text(vis_state.lambda);
// transition the order of the bars
var increased = lambda.old < vis_state.lambda;
if (vis_state.topic > 0){
reorder_bars_new(increased, "left");
}
// store the current lambda value
//state_save(true);
document.getElementById(lambdaID).value = vis_state.lambda;
});
d3.select("#"+lambdaIDRightPanel)
.on("mouseup", function() {
save_users_actions_across_time('change_lambda_right_panel', new Date());
save_users_actions_across_time('change_lambda_right_panel_value', document.getElementById(lambdaIDRightPanel).value);
////////////console.log("hice click en esti", "#"+lambdaIDRightPanel)
//lambda_select = "#"+lambdaID
// store the previous lambda value
lambda.old = lambda.current;
lambda.current = document.getElementById(lambdaIDRightPanel).value;
vis_state.lambda = +this.value;
// adjust the text on the range slider
d3.select("#"+lambdaIDRightPanel).property("value", vis_state.lambda);
d3.select("#"+lambdaIDRightPanel + "-value").text(vis_state.lambda);
// transition the order of the bars
var increased = lambda.old < vis_state.lambda;
if (vis_state.topic > 0){
reorder_bars_new(increased, "right");
}
// store the current lambda value
//state_save(true);
document.getElementById(lambdaIDRightPanel).value = vis_state.lambda;
});
function get_name_node_sankey(graph, threshold){
graph.links.filter(function(el){
if(el.value >=threshold){ //HAY QUE CAMBIA RESTO, HAY DOS THRESHOLD AHORA!
if(el.target.node == undefined){
if(el.target<=min_target_node_value){
min_target_node_value=el.target
}
}
else{
if(el.target.node<=min_target_node_value){
min_target_node_value=el.target.node
}
}
}
}
);
var nodes_filtered_set = new Set();
graph.nodes.filter(function(d){
if(!(nodes_filtered_set.has(d.node))){
if(d.node >= min_target_node_value){
// pertenece al modelo de corpus 2
var topic_id_in_model = d.node-min_target_node_value
//var real_topic_id = topic_order_2[topic_id_in_model]-1
lamData = [];
for (var i = 0; i < jsonData_2['tinfo'].Term.length; i++) {
var obj = {};
for (var key in jsonData_2['tinfo']) {
obj[key] = jsonData_2['tinfo'][key][i];
}
lamData.push(obj);
}
}
else{
var topic_id_in_model = d.node
lamData = [];
for (var i = 0; i < jsonData['tinfo'].Term.length; i++) {
var obj = {};
for (var key in jsonData['tinfo']) {
obj[key] = jsonData['tinfo'][key][i];
}
lamData.push(obj);
}
}
var dat2 = lamData.filter(function(e) {
if(d.node==-1){
return e.Category == "Default" //This are the most relevant terms from all the corpus. We are not using it!!!
}
else{
return e.Category == "Topic" + (d.node%min_target_node_value+1); // OJO! AQUI HAY UN +1, quizas hay que sacarlo y mejorar el codigo, esto esta medio mula
}
});
// define relevance:
for (var i = 0; i < dat2.length; i++) {
dat2[i].relevance = lambda.current * dat2[i].logprob +
(1 - lambda.current) * dat2[i].loglift;
if(isNaN(dat2[i].relevance)){
dat2[i].relevance = -Infinity;
}
}
dat2.sort(fancysort("relevance"));
var top_terms = dat2.slice(0, number_top_keywords_name);
var name_string = '';
for (var i=0; i < top_terms.length; i++){
name_string += top_terms[i].Term+" "
}
name_topics_sankey[topicID + d.node] = name_string
nodes_filtered_set.add(d.node);
return d;
}
});
}
//Inspired by: https://bl.ocks.org/d3noob/013054e8d7807dff76247b81b0e29030
function visualize_sankey(graph, threshold_min, threshold_max){
//console.log('ESTOS SON LOS THRESHOLD', threshold_min, threshold_max);
inverted_links_filtered = graph;
save_users_actions_across_time('min_filtering_sankey', threshold_min);
save_users_actions_across_time('min_filtering_sankey_time', new Date());
save_users_actions_across_time('max_filtering_sankey', threshold_max);
save_users_actions_across_time('max_filtering_sankey_time', new Date());
//console.log(' value de filtering sankey', threshold_min, new Date())
//console.log(' min', threshold_min, ' max', threshold_max, ' graph', graph);
var node_padding = 25
//////////console.log("este es el graph que recibo", graph)
d3.selectAll('#svgCentralSankeyDiv').remove();
d3.selectAll('#divider_central_panel_sankey').remove();
var svgCentralSankeyDiv = d3.select("#CentralPanel").append("div")
svgCentralSankeyDiv.attr("id", "svgCentralSankeyDiv")
var divider_central_panel_sankey = document.createElement("hr");
divider_central_panel_sankey.setAttribute("class", "rounded");
divider_central_panel_sankey.setAttribute("id", "divider_central_panel_sankey");
document.getElementById("svgCentralSankeyDiv").appendChild(divider_central_panel_sankey)
var margin = { top: 10, right: 10, bottom: 10, left: 10 } // ocupar estos margenes
//get width, height according to client's window
var bounds_svgCentralSankey = d3.selectAll('#svgCentralSankeyDiv').node().getBoundingClientRect();
var user_width_sankey = bounds_svgCentralSankey.width - margin.left - margin.right;
var user_height_sankey= bounds_svgCentralSankey.height - margin.top - margin.bottom;
d3.selectAll('#svg_sankey').remove();
var nodes_filtered_set = new Set();
//get min_target_node_value
graph.links.filter(function(el){
if(el.source.node == undefined){
nodes_filtered_set.add(el.source);
}
else{
nodes_filtered_set.add(el.source.node);
}
if(el.target.node == undefined){
nodes_filtered_set.add(el.target);
if(el.target<=min_target_node_value){
min_target_node_value=el.target
}
}
else{
nodes_filtered_set.add(el.target.node);
if(el.target.node<=min_target_node_value){
min_target_node_value=el.target.node
}
}
return el.value
}
);
//////console.log("este es el graph, ",graph)
sankey_topics_automatic_match = []
var links_filtered = graph.links.filter(function(el){
if((Number(threshold_min) <= Number(el.value.toFixed(2)) )&&(Number(el.value.toFixed(2)) <= Number(threshold_max) )){
return true;
}
return (Number(threshold_min) <= Number(el.value.toFixed(2)) )&&(Number(el.value.toFixed(2)) <= Number(threshold_max))
}
);
//add a link dummy para que siempre dibuje algo
global_sankey_links_filtered = links_filtered; // i need this variable just for the user study
if( links_filtered.length == 0){
}
var margin = {top: 10, right: 10, bottom: 10, left: 10};
var formatNumber = d3.format(",.2f"), // two decimal places
format = function(d) {
if(scenario_2_is_baseline_metric == true){
return "similarity score: "+formatNumber(d);
}else{
return "similarity score: "+formatNumber(d);
}
},
color = d3.scaleOrdinal(d3.schemeAccent);
var svg_sankey = d3.select("#svgCentralSankeyDiv").append("svg")// #CentralPanel
.attr("width", "100%")
.attr("height", "100%")
.attr("id", "svg_sankey");
//I deleted the filtered of nodes. Sankey diagram shows all the nodes (even if these nodes don't have any other similarities. I could add a different color even!. Thus
//we could detect original topics. Not only the topics that are similar)
var nodes_filtered = graph.nodes
var sankey = d3.sankey()
.nodeWidth(36)
.nodePadding(node_padding)
.size([user_width_sankey, user_height_sankey])
.nodes(nodes_filtered) //it receives all the nodes
.min_target_node_value(min_target_node_value)
.links(links_filtered) //only the links between certain similarity scores appears
.jsonDataArray([jsonData,jsonData_2])
.layout(1); //32
var path = sankey.link();
var link = svg_sankey.append("g").selectAll(".link")
.data(links_filtered)
.enter().append("path")
.filter(function(d){
return d.value;
})
.attr("class", "link") //
.attr("d", path)
.style("stroke-width", function(d) {
return Math.max(1, d.dy)
})
.on("click", function(d){
//console.log('HACIENDO CLICK EN EL PATH', min_target_node_value, d.source.node, d.target.node);
topic_on_sankey(nodes_filtered[Number(d.source.node)], min_target_node_value );
topic_on_sankey(nodes_filtered[Number(d.target.node)], min_target_node_value );
console.log('DE SOURCE',d.source.node )
save_users_actions_across_time('click_path_sankey', new Date());
isSettingInitial = false;
if(Number(d.source.node)>=min_target_node_value){
real_last_clicked_sankey_model_2 = nodes_filtered[Number(d.source.node)];
save_users_actions_across_time('click_path_sankey_model_2_topic_id', nodes_filtered[Number(d.source.node)].name);
}
else{
real_last_clicked_sankey_model_1 = nodes_filtered[Number(d.source.node)];
save_users_actions_across_time('click_path_sankey_model_1_topic_id', nodes_filtered[Number(d.source.node)].name);
}
if(Number(d.target.node)>=min_target_node_value){
real_last_clicked_sankey_model_2 = nodes_filtered[Number(d.target.node)];
save_users_actions_across_time('click_path_sankey_model_2_topic_id', nodes_filtered[Number(d.target.node)].name);
}
else{
real_last_clicked_sankey_model_1 = nodes_filtered[Number(d.target.node)];
save_users_actions_across_time('click_path_sankey_model_1_topic_id', nodes_filtered[Number(d.target.node)].name);
}
})
.sort(function(a, b) { return b.dy - a.dy; }); // el dy de aqui tambien hay que modificarlo
link.append("title")
.text(function(d) {
var match = {
'source_node':topicID + d.source.node,
'source_name': name_topics_sankey[topicID + d.source.node],
'link_value': format(d.value),
'target_node': topicID + d.target.node,
'target_name': name_topics_sankey[topicID + d.target.node],
}
var title = name_topics_sankey[topicID + d.source.node] + " → " +
name_topics_sankey[topicID + d.target.node] + "\n" + format(d.value);
sankey_topics_automatic_match.push(JSON.stringify(match));
return title;});
// add in the nodes
var node = svg_sankey.append("g").selectAll(".node")
.data(nodes_filtered)//.data(graph.nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")"; }) // el d.y de aqui tambien hay que modificarlo
.on("click", function(d){
save_users_actions_across_time('click_node_sankey', new Date());
isSettingInitial = false;
topic_on_sankey(d, min_target_node_value );
if(d.node>=min_target_node_value){
real_last_clicked_sankey_model_2 = d
save_users_actions_across_time('click_node_sankey_model_2_topic_id', d.name);
}
else{
real_last_clicked_sankey_model_1 = d
save_users_actions_across_time('click_node_sankey_model_1_topic_id', d.name);
}
})
// add the rectangles for the nodes
node.append("rect")
.attr("id", function(d){
return "node_"+d.node //que esta sea la id unica del nodo
})
.attr("height", function(d){
if(d.node>=min_target_node_value){ //model 2
var Freq = jsonData_2.mdsDat.Freq[d.node-min_target_node_value]
Freq = Math.round(Freq * 10) / 10
}
else{
var Freq = jsonData.mdsDat.Freq[d.node]
Freq = Math.round(Freq * 10) / 10
}
//return Freq/100*(user_height_sankey-(min_target_node_value*1.5*node_padding));
return d.dy;
}
)
.attr("width", sankey.nodeWidth())
.style("fill", function(d) {
if(d.node < min_target_node_value){
return color1_1;
}
else{
return color2_1;
}
})
.style("stroke", function(d) {
return d3.rgb(d.color).darker(2); })
.style("opacity", 0.6)
.append("title")
.text(function(d) {
return name_topics_sankey[topicID + d.node] ;})
// add in the title for the nodes
node.append("text")
.attr("x", -6)
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("width", function(d) {
return 0.45*d3.selectAll('#svg_sankey').node().getBoundingClientRect().width
})
.attr("class", "txt")
.attr("font-weight", "bold")
.attr("text-anchor", "end")
.attr("transform", null)
.text(function(d){
if(d.node>=min_target_node_value){ //model 2
var Freq = jsonData_2.mdsDat.Freq[d.node-min_target_node_value];
var freq_current_topic = Math.round(Freq * 10) / 10;
var labeling_user_study = 'N'+String(d.node-min_target_node_value+1);
}
else{
var Freq = jsonData.mdsDat.Freq[d.node];
var freq_current_topic = Math.round(Freq * 10) / 10;
var labeling_user_study = 'E'+String(d.node+1);
}
//return labeling_user_study+' - '+"("+freq_current_topic+"%) "+ name_topics_sankey[topicID + d.node];}
return labeling_user_study+' - '+ name_topics_sankey[topicID + d.node];}
//return name_topics_sankey[topicID + d.node] ;}
) //.text(function(d) { return d.name; })
.filter(function(d) { return d.x < user_width_sankey / 2; })
.attr("x", 6 + sankey.nodeWidth())
.attr("text-anchor", "start");
if(last_clicked_model_2!=-1){
d3.select("#"+last_clicked_model_2).style("fill",color2_1)