-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathhiv_tx_network.js
executable file
·2988 lines (2606 loc) · 89.4 KB
/
hiv_tx_network.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
var _ = require("underscore"),
timeDateUtil = require("./timeDateUtil.js"),
kGlobals = require("./globals.js"),
misc = require("./misc.js"),
clustersOfInterest = require("./clustersOfInterest.js");
/*------------------------------------------------------------
define a barebones class for the network object
mostly here to encapsulate function definitions
so they don't pollute the main function
------------------------------------------------------------*/
/**
* Represents an HIV transmission network with annotations
*
* @class HIVTxNetwork
* @param {Object} json - A JSON object containing the network data.
* @param {HTMLElement} button_bar_ui - A UI element for interacting with the network.
* @param {Object} cluster_attributes - Attributes related to clusters within the network.
*/
class HIVTxNetwork {
constructor(json, button_bar_ui, primary_key_function, secondaryGraph) {
this.json = json;
this.button_bar_ui = button_bar_ui;
this.warning_string = "";
this.subcluster_table = null;
this.priority_set_table_write = null;
this.priority_set_table_writeable = null;
this.cluster_attributes = [];
this.minimum_cluster_size = 0;
this.isPrimaryGraph = !secondaryGraph;
/** SLKP 20241029
this function is used to identify which nodes are duplicates
it converts the name of the node (sequence) into a primary key ID (by default, taking the .id string up to the first pipe)
all sequences/nodes that map to the same primary key are assumed to represent the same entity / individual
**/
this.primary_key = _.isFunction(primary_key_function)
? primary_key_function
: (node) => {
const i = node.id.indexOf("|");
if (i >= 0) {
return node.id.substr(0, i);
}
return node.id;
};
this.tabulate_multiple_sequences();
/** initialize UI/UX elements */
this.initialize_ui_ux_elements();
/** the list of defined clusters of interest,
format as follows (SLKP, 20240715: may need updating)
{
'name' : 'unique name',
'nodes' : [
{
'node_id' : text,
'added' : date,
'kind' : text
}],
'created' : date,
'description' : 'text',
'modified' : date,
'kind' : 'text'
}
*/
this.defined_priority_groups = [];
/**
time filter element for various displays
*/
this.using_time_filter = null;
}
/** initialize UI/UX elements */
initialize_ui_ux_elements() {
/** define a D3 behavior to make node labels draggable */
this.node_label_drag = d3.behavior
.drag()
.on("drag", function (d) {
d.label_x += d3.event.dx;
d.label_y += d3.event.dy;
d3.select(this).attr(
"transform",
"translate(" +
(d.label_x + d.rendered_size * 1.25) +
"," +
(d.label_y + d.rendered_size * 0.5) +
")"
);
})
.on("dragstart", () => {
d3.event.sourceEvent.stopPropagation();
})
.on("dragend", () => {
d3.event.sourceEvent.stopPropagation();
});
/** default node colorizer */
this.colorizer = {
selected: function (d) {
return d === "selected" ? d3.rgb(51, 122, 183) : "#FFF";
},
};
/** if there is computed support for network edges, use it to highlight
possible spurious edges **/
this.highlight_unsuppored_edges = true;
/** default node shaper */
this.node_shaper = {
id: null,
shaper: function () {
return "circle";
},
};
/** d3 layout option setting */
this.charge_correction = 5;
/**
filters which control which clusters get rendered
*/
this.cluster_filtering_functions = {
size: this.filter_by_size,
singletons: this.filter_singletons,
};
}
/**
Iterate over nodes in the network, identify all those which share the same
primary key (i.e., the same individual), tabulate them, and collate node attributes
*/
tabulate_multiple_sequences() {
/**
generate a primary key to node ID map
[primary key] => [array of IDs]
*/
this.primary_key_list = {};
this.has_multiple_sequences = false;
_.each(this.json.Nodes, (n) => {
const p_key = this.primary_key(n);
if (!(p_key in this.primary_key_list)) {
this.primary_key_list[p_key] = [n];
} else {
this.primary_key_list[p_key].push(n);
this.has_multiple_sequences = true;
this.legend_multiple_sequences = true;
}
if (!this.legend_multiple_sequences) {
if (n[kGlobals.network.AliasedSequencesID]) {
this.legend_multiple_sequences = true;
}
}
});
/**
iterate over all duplicate sequences, synchronize node attributes
*/
if (this.has_multiple_sequences) {
_.each(this.primary_key_list, (seqs, primary_id) => {
if (seqs.length > 1) {
let consensus_attributes = {};
_.each(seqs, (seq_record) => {
_.each(seq_record[kGlobals.network.NodeAttributeID], (v, k) => {
if (!(k in consensus_attributes)) {
consensus_attributes[k] = [v];
} else {
consensus_attributes[k].push(v);
}
});
});
// only copy values if there's strict consensus
consensus_attributes = _.omit(
_.mapObject(consensus_attributes, (d, k) => {
let freq = _.countBy(d, (i) => i);
if (_.size(freq) == 1) {
return _.keys(freq)[0];
}
return null;
}),
(d) => !d
);
_.each(seqs, (seq_record) => {
_.extend(
seq_record[kGlobals.network.NodeAttributeID],
consensus_attributes
);
});
}
});
}
}
/**
this is a function which calculates country node centers
for the (experimental) option of rendering networks with
topo maps
*/
_calc_country_nodes = (calc_options) => {
if (calc_options && "country-centers" in calc_options) {
this.mapProjection = d3.geo
.mercator()
.translate([
this.margin.left + this.width / 2,
this.margin.top + this.height / 2,
])
.scale((150 * this.width) / 960);
_.each(this.countryCentersObject, (value) => {
value.countryXY = this.mapProjection([value.longt, value.lat]);
});
}
};
/**
@cluster [dict] : cluster object
return true if the cluster passes all the currently defined filters
see this.cluster_filtering_functions
*/
cluster_display_filter(cluster) {
return _.every(this.cluster_filtering_functions, (f) => f(cluster));
}
/**
@cluster [dict] : cluster object
return true if cluster size is at least this.minimum_cluster_size
*/
filter_by_size = (cluster) => {
return cluster.children.length >= this.minimum_cluster_size;
};
/**
@node_list [array] : list of nodes
returns the list of unique "individuals", collapsing nodes representing
multiple sequences from the same entity into a single blob
*/
unique_entity_list = (node_list) => {
return _.map(
_.groupBy(node_list, (n) => this.primary_key(n)),
(d, k) => k
);
};
/**
@node_list [array] : list of node IDs
returns the list of unique "individuals", collapsing nodes representing
multiple sequences from the same entity into a single blob
*/
unique_entity_list_from_ids = (node_list) => {
return this.unique_entity_list(
_.map(node_list, (d) => {
return { id: d };
})
);
};
/**
@node_list [array] : list of nodes
returns [primary key] => [objects] dict
*/
unique_entity_object_list = (node_list) => {
return _.groupBy(node_list, (n) => this.primary_key(n));
};
/**
@cluster [dict] : cluster object
return true if cluster size is at least 2
*/
filter_singletons = (cluster) => {
return cluster.children.length > 1;
};
/**
@cluster [dict] : cluster object
return true if the cluster is new compared to the previous network
*/
filter_if_added = (cluster) => {
return this.cluster_attributes[cluster.cluster_id].type !== "existing";
};
/**
@cluster [dict] : cluster object
return true if the cluster has nodes newer than this.using_time_filter
*/
filter_time_period = (cluster) => {
return _.some(
this.nodes_by_cluster[cluster.cluster_id],
(n) =>
this.attribute_node_value_by_id(
n,
timeDateUtil.getClusterTimeScale()
) >= this.using_time_filter
);
};
get_reference_date() {
/**
get the reference (creation) date for the network
same as "today", unless this is not the primary network (cluster or subcluster view),
in which case the reference date for the parent is used
*/
if (!this.isPrimaryGraph && this.parent_graph_object)
return this.parent_graph_object.today;
return this.today;
}
lookup_option(key, default_value, options) {
/**
retrieve an option associated with "key"
if not found in Settings or options, return "default value"
*/
if (this.json.Settings && this.json.Settings[key])
return this.json.Settings[key];
if (options && options[key]) return options[key];
return default_value;
}
static lookup_form_generator() {
return '<div><ul data-hivtrace-ui-role = "priority-membership-list"></ul></div>';
}
/** retrive the DOM ID for an element given its data-hivtrace-ui-role
@param role: data-hivtrace-ui-role
@param nested: true if this is being called from a secondary network or element (dialog, cluster view etc),
which does not have primary button_ui elements
*/
get_ui_element_selector_by_role(role, not_nested) {
if (not_nested && !this.isPrimaryGraph) {
return undefined;
}
return (
(not_nested ? "" : "#" + this.button_bar_ui) +
misc.get_ui_element_selector_by_role(role)
);
}
/**
Process the network to simplify multiple sequences per individual
1. Identify null clusters, i.e., clusters that consist only of sequences with the same primary key (individual)
Delete ALL null clusters; remove all nodes and edges associated with them
2. Identify identical sequence sets, i.e., sequences with the same individual that have the same connection patterns,
(a) All sequences in the set have the same primary key
(b) All sequences in the set are connected to each other (at length <= reduce_distance_within)
(c) All sequences in the set are connected to the same set of OTHER sequences (at length <= reduce_distance_between)
All identical sequence sets are collapsed to a
*/
process_multiple_sequences(reduce_distance_within, reduce_distance_between) {
if (this.has_multiple_sequences && this.isPrimaryGraph) {
reduce_distance_within = reduce_distance_within || 0.000001;
reduce_distance_between = reduce_distance_between || 0.015;
let clusters = misc.hivtrace_cluster_depthwise_traversal(
this.json.Nodes,
this.json.Edges
);
let complete_clusters = misc.hivtrace_cluster_depthwise_traversal(
this.json.Nodes,
this.json.Edges,
(d) => d.length <= reduce_distance_within
);
let adjacency = misc.hivtrace_compute_adjacency(
this.json.Nodes,
this.json.Edges,
(d) => d.length <= reduce_distance_between
);
let adjacency05 = misc.hivtrace_compute_adjacency(
this.json.Nodes,
this.json.Edges,
(d) => d.length <= 0.005
);
let nodes_to_delete = new Set();
_.each(clusters, (cluster, cluster_index) => {
let entity_list = this.unique_entity_list(cluster);
if (entity_list.length == 1) {
_.each(cluster, (ncn) => {
nodes_to_delete.add(ncn.id);
// these are all null nodes (clusters made of single individual sequences)
});
}
});
//let c95 = this.extract_single_cluster (clusters[95]);
//console.log (misc.hivtrace_cluster_depthwise_traversal (c95.Nodes, c95.Edges, (d)=>d.length <= reduce_distance_within));
let null_size = nodes_to_delete.size;
console.log("Marked ", null_size, " nodes in null clusters");
_.each(complete_clusters, (cluster, cluster_index) => {
if (cluster.length > 1) {
if (_.some(cluster, (n) => nodes_to_delete.has(n.id))) {
return;
}
let uel = this.unique_entity_object_list(cluster);
_.each(uel, (dup_seqs, uid) => {
if (dup_seqs.length > 1) {
let dup_ids = new Set(_.map(dup_seqs, (d) => d.id));
let neighborhood = new Set(
_.map(
_.filter(
[...adjacency[dup_seqs[0].id]],
(d) => !dup_ids.has(d)
)
)
);
let neighborhood05 = new Set(
_.map(
_.filter(
[...adjacency05[dup_seqs[0].id]],
(d) => !dup_ids.has(d)
)
)
);
let reduce = true;
//if (neighborhood.size > 0) {
for (let idx = 1; idx < dup_seqs.length; idx += 1) {
let other_nbhd = new Set(
_.map(
_.filter(
[...adjacency[dup_seqs[idx].id]],
(d) => !dup_ids.has(d)
)
)
);
let other_nbhd05 = new Set(
_.map(
_.filter(
[...adjacency05[dup_seqs[idx].id]],
(d) => !dup_ids.has(d)
)
)
);
if (
!(
other_nbhd.isSubsetOf(neighborhood) &&
neighborhood.isSubsetOf(other_nbhd)
) ||
!(
other_nbhd.isSubsetOf(neighborhood05) &&
neighborhood.isSubsetOf(other_nbhd05)
)
) {
reduce = false;
break;
}
}
//}
if (reduce) {
dup_seqs[0][kGlobals.network.AliasedSequencesID] = _.map(
dup_seqs,
(d) => d.id
);
_.each(dup_seqs, (d, i) => {
if (i > 0) {
nodes_to_delete.add(d.id);
}
});
}
}
});
}
});
console.log(
"Marked ",
nodes_to_delete.size - null_size,
" collapsible nodes"
);
/** now iterate over non-trivial clusters, and see if any nodes are collapsible **/
// delete designated nodes and update network structures
if (nodes_to_delete.size) {
let new_node_list = [];
let new_edge_set = [];
let old_node_idx_to_new_node_idx = [];
let new_counter = 0;
_.each(this.json.Nodes, (n, i) => {
if (nodes_to_delete.has(n.id)) {
old_node_idx_to_new_node_idx.push(-1);
} else {
new_node_list.push(n);
old_node_idx_to_new_node_idx.push(new_counter);
new_counter++;
}
});
_.each(this.json.Edges, (e, i) => {
let new_source = old_node_idx_to_new_node_idx[e.source],
new_target = old_node_idx_to_new_node_idx[e.target];
if (new_source >= 0 && new_target >= 0) {
e.source = new_source;
e.target = new_target;
new_edge_set.push(e);
}
});
//console.log (new_edge_set);
this.json.Nodes = new_node_list;
this.json.Edges = new_edge_set;
this.tabulate_multiple_sequences();
}
}
}
/**
When MSPP are present, this function will annotate node objects with fields
that indicate whether or not the nodes belong to multiple clusters or subclusters
*/
annotate_multiple_clusters_on_nodes() {
if (this.has_multiple_sequences) {
_.each(this.primary_key_list, (nodes, key) => {
if (nodes.length >= 2) {
let cl = _.groupBy(nodes, (n) => n.cluster);
if (_.size(cl) > 1) {
_.each(nodes, (n) => {
n["multiple clusters"] = _.keys(cl);
});
} else {
_.each(nodes, (n) => {
delete n["multiple clusters"];
});
}
cl = _.filter(
_.map(
_.groupBy(nodes, (n) => n.subcluster_label),
(d, k) => k
),
(d) => d != "undefined"
);
if (_.size(cl) > 1) {
_.each(nodes, (n) => {
n["multiple subclusters"] = cl;
});
} else {
_.each(nodes, (n) => {
delete n["multiple subclusters"];
});
}
}
});
}
}
/**
When MSPP are present, this function will reduce the network
encoded by .Nodes and .Edges in filtered_json, and
reduce all sequences that represent the same entity into one node.
Such nodes inherit the union of their links (so at least of the sequences being
collapsed link to X, the "joint" node will link to X).
The joint nodes will also receive aggregated attributes;
if the nodes being merged have different attributes values for a given key, the
merged node will have a ';' separated list of attributes for the same key.
*/
simplify_multisequence_cluster(filtered_json) {
/**
20241030 SLKP
Perform a greedy collapse of all the sequences that map to the same primary key
For a reduced cluster view
*/
let reduced_nodes = _.pairs(
_.mapObject(
this.unique_entity_object_list(filtered_json.Nodes),
(v) => this.aggregate_indvidual_level_records(v)[0]
)
);
let uid_index = _.object(_.map(reduced_nodes, (d, i) => [d[0], i]));
let oui_index = {};
_.each(reduced_nodes, (d) => {
let aliased = d[1][kGlobals.network.AliasedSequencesID] || [d[1].id];
_.each(aliased, (nn) => {
oui_index[nn] = uid_index[d[0]];
});
});
let adjacency = misc.hivtrace_compute_adjacency(
filtered_json.Nodes,
filtered_json.Edges
);
let reduced_adjacency = _.map(uid_index, (d) =>
_.map(uid_index, (d2) => 0)
);
let reduced_lengths = _.map(uid_index, (d) => _.map(uid_index, (d2) => 0));
_.each(filtered_json.Edges, (e) => {
let reduced_src = oui_index[filtered_json.Nodes[e.source].id],
reduced_tgt = oui_index[filtered_json.Nodes[e.target].id];
if (reduced_src != reduced_tgt) {
reduced_adjacency[reduced_src][reduced_tgt] += 1;
reduced_adjacency[reduced_tgt][reduced_src] += 1;
reduced_lengths[reduced_src][reduced_tgt] += e.length;
reduced_lengths[reduced_tgt][reduced_src] += e.length;
}
});
let reduced_edges = [];
_.each(reduced_adjacency, (row, i) => {
for (let j = i + 1; j < row.length; j++) {
if (row[j] > 0) {
reduced_edges.push({
source: i,
target: j,
attributes: [],
length: reduced_lengths[i][j] / row[j],
weight: row[j],
});
}
}
});
filtered_json.Edges = reduced_edges;
filtered_json.Nodes = _.map(reduced_nodes, (d) => d[1]);
return filtered_json;
}
/**
generate a cross-hatch pattern for filling nodes with a specific color
and add it as a definition to the network SVG
*/
generate_cross_hatch_pattern(color) {
let id = "id" + this.dom_prefix + "_diagonalHatch_" + color.substr(1, 10);
if (this.network_svg.select("#" + id).empty()) {
function getComplementaryColor(backgroundColor) {
const color = d3.rgb(backgroundColor);
const luminance = color.r * 0.299 + color.g * 0.587 + color.b * 0.114;
return luminance > 128 ? "#000000" : "#ffffff";
}
let defs = this.network_svg.append("defs");
/*defs.append("pattern")
.attr("id", id)
.attr("patternUnits", "userSpaceOnUse")
.attr("width", "2")
.attr("height", "4")
.attr("patternTransform", "rotate(30 2 2)")
.append("path")
.attr("d", "M -1,2 l 6,0")
.attr("stroke", color)
.attr("stroke-width", "3"); //this is actual shape for arrowhead
*/
let pattern = defs
.append("pattern")
.attr("id", id)
.attr("patternUnits", "userSpaceOnUse")
.attr("width", "6")
.attr("height", "6")
.attr("patternTransform", "rotate(45)");
pattern
.append("rect")
.attr("width", "3")
.attr("height", "6")
.attr("fill", color)
.attr("transform", "translate(0,0)");
pattern
.append("rect")
.attr("width", "3")
.attr("height", "6")
.attr("fill", getComplementaryColor(color))
.attr("transform", "translate(3,0)");
}
return id;
}
/** filter the list of CoI to return those which have not been reviewed/validated */
priority_groups_pending() {
return _.filter(this.defined_priority_groups, (pg) => pg.pending).length;
}
/** filter the list of CoI to return those which have been automatically expanded */
priority_groups_expanded() {
return _.filter(this.defined_priority_groups, (pg) => pg.expanded).length;
}
/** filter the list of CoI to return those which have been created by the system */
priority_groups_automatic() {
return _.filter(
this.defined_priority_groups,
(pg) => pg.createdBy === kGlobals.CDCCOICreatedBySystem
).length;
}
/** lookup a CoI by name; null if not found */
priority_groups_find_by_name = function (name) {
if (this.defined_priority_groups) {
return _.find(this.defined_priority_groups, (g) => g.name === name);
}
return null;
};
/** generate a set of all unique temporal events (when new data were added to ANY CoI)
return a Set of date strings formatted with timeDateUtil.DateViewFormatSlider */
priority_groups_all_events = function () {
const events = new Set();
if (this.defined_priority_groups) {
_.each(this.defined_priority_groups, (g) => {
_.each(g.nodes, (n) => {
events.add(timeDateUtil.DateViewFormatSlider(n.added));
});
});
}
return events;
};
/**
compute the overlap between CoI
@groups: an array with CoI objects
1. Populate this.priority_node_overlap dictionary which
stores, for every node present in AT LEAST ONE CoI, the set of all
PGs it belongs to, as in "node-id" => set ("PG1", "PG2"...)
2. For each CoI, create and populate a member field, .overlaps
which is a dictionary that stores
{
sets : #of CoI with which it shares nodes
nodes: the # of nodes contained in overlaps
}
*/
priority_groups_compute_overlap = function (groups) {
this.priority_node_overlap = {};
var entities_by_pg = {};
var size_by_pg = {};
_.each(groups, (pg) => {
entities_by_pg[pg.name] = this.aggregate_indvidual_level_records(
pg.node_objects
);
size_by_pg[pg.name] = entities_by_pg[pg.name].length;
_.each(entities_by_pg[pg.name], (n) => {
const entity_id = this.entity_id(n);
if (!(entity_id in this.priority_node_overlap)) {
this.priority_node_overlap[entity_id] = new Set();
}
this.priority_node_overlap[entity_id].add(pg.name);
});
});
_.each(groups, (pg) => {
const overlap = {
sets: new Set(),
nodes: 0,
supersets: [],
duplicates: [],
};
const by_set_count = {};
_.each(entities_by_pg[pg.name], (n) => {
const entity_id = this.entity_id(n);
if (this.priority_node_overlap[entity_id].size > 1) {
overlap.nodes++;
this.priority_node_overlap[entity_id].forEach((pgn) => {
if (pgn !== pg.name) {
if (!(pgn in by_set_count)) {
by_set_count[pgn] = [];
}
by_set_count[pgn].push(entity_id);
}
overlap.sets.add(pgn);
});
}
});
_.each(by_set_count, (nodes, name) => {
if (nodes.length == size_by_pg[pg.name]) {
if (size_by_pg[name] == size_by_pg[pg.name]) {
overlap.duplicates.push(name);
} else {
overlap.supersets.push(name);
}
}
});
pg.overlap = {
nodes: overlap.nodes,
sets: Math.max(0, overlap.sets.size - 1),
superset: overlap.supersets,
duplicate: overlap.duplicates,
};
});
};
/** generate the name for a cluster of interest */
generateClusterOfInterestID(subcluster_id) {
const id =
this.CDC_data["jurisdiction_code"] +
"_" +
timeDateUtil.DateViewFormatClusterCreate(this.CDC_data["timestamp"]) +
"_" +
subcluster_id;
let suffix = "";
let k = 1;
let found =
this.auto_create_priority_sets.find((d) => d.name === id + suffix) ||
this.defined_priority_groups.find((d) => d.name === id + suffix);
while (found !== undefined) {
suffix = "_" + k;
k++;
found =
this.auto_create_priority_sets.find((d) => d.name === id + suffix) ||
this.defined_priority_groups.find((d) => d.name === id + suffix);
}
return id + suffix;
}
/** does the node have "new node" attribute */
static is_new_node(node) {
return node.attributes.indexOf("new_node") >= 0;
}
/** create a map between node IDs and node objects */
map_ids_to_objects() {
if (!this.node_id_to_object) {
this.node_id_to_object = {};
_.each(this.json.Nodes, (n, i) => {
this.node_id_to_object[n.id] = n;
});
}
}
/** Fetch the value of an attribute from the node
@param d: node object
@param id: [string] the attribute whose value should be fetched
@param number: [bool] if true, only return numerical values
*/
attribute_node_value_by_id(d, id, number, is_date) {
try {
if (kGlobals.network.NodeAttributeID in d && id) {
if (id in d[kGlobals.network.NodeAttributeID]) {
let v;
if (this.json[kGlobals.network.GraphAttrbuteID][id].volatile) {
v = this.json[kGlobals.network.GraphAttrbuteID][id].map(d, this);
} else {
v = d[kGlobals.network.NodeAttributeID][id];
}
if (_.isString(v)) {
if (v.length === 0) {
return kGlobals.missing.label;
} else if (number) {
v = Number(v);
return _.isNaN(v) ? kGlobals.missing.label : v;
} else if (date) {
return v.getTime();
}
}
return v;
}
}
} catch (e) {
console.log("attribute_node_value_by_id", e, d, id, number);
}
return kGlobals.missing.label;
}
/**
Is this node NOT genetic, i.e. added to the network via social or other means
*/
static is_edge_injected(e) {
return "edge_type" in e;
}
/**
Extract the nodes and edges between them into a separate object
@param nodes [array] the list of nodes to extract
@param filter [function, optional] (edge) -> bool filtering function for deciding which edges will be used to define clusters
@param no_clone [bool] if set to T, node objects are **not** shallow cloned in the return object
@return [dict] the object representing "Nodes" and "Edges" in the extracted cluster
*/
extract_single_cluster(
nodes,
filter,
no_clone,
given_json,
include_extra_edges,
edge_subset
) {
var cluster_json = {};
var map_to_id = {};
cluster_json.Nodes = _.map(nodes, (c, i) => {
map_to_id[c.id] = i;
if (no_clone) {
return c;
}
var cc = _.clone(c);
cc.cluster = 1;
return cc;
});
given_json = given_json || this.json;
cluster_json.Edges = _.filter(
edge_subset ? edge_subset : given_json.Edges,
(e) => {
if (_.isUndefined(e.source) || _.isUndefined(e.target)) {
return false;
}
return (
given_json.Nodes[e.source].id in map_to_id &&
given_json.Nodes[e.target].id in map_to_id &&
(include_extra_edges || !HIVTxNetwork.is_edge_injected(e))
);
}
);
if (filter) {
cluster_json.Edges = _.filter(cluster_json.Edges, filter);
}
cluster_json.Edges = _.map(cluster_json.Edges, (e) => {
var ne = _.clone(e);
ne.source = map_to_id[given_json.Nodes[e.source].id];
ne.target = map_to_id[given_json.Nodes[e.target].id];
return ne;
});
return cluster_json;
}
/**
Grow a CoI defined in @pg based on its growth mode
@return the set of added nodes (by numeric ID)
@nodeID2idx : if provided, maps the name of the node to its index
in the `nodes` array; avoids repeated traversal if provided
@edgesByNode : if provided, maps the INDEX of the node to the list of edges in the entire network