-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathanalytics.py
708 lines (554 loc) · 29.1 KB
/
analytics.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
"""
Functions for Analytics Module
"""
import GlobalData as GD
import networkx as nx
from PIL import Image
import math
import json
import plotly.graph_objs as go
import plotly.utils as pu
from joblib import Parallel, delayed
import igraph as ig
import numpy as np
import util
ANALYTICS_TABS = [
"Degree Distribution",
"Closeness",
"Shortest Path",
"Eigenvector",
"Mod-based Communities",
"Clustering Coefficient"
]
def get_linklist(message, room):
message["fn"] = "checkbox"
if "definedlinklist" in GD.pdata.keys():
if GD.pdata["definedlinklist"] == "links":
links = None # GD[]
print("Links all." ) #links = GD[]
elif GD.pdata["definedlinklist"] == "linkslayouts":
print("Links layout specific.")
links = None # GD[]
return links
def __compute_histogram_bins(values, min_bins=2, max_bins=15):
min_value = np.min(values)
max_value = np.max(values)
value_range = max_value - min_value
bin_width = value_range / min(max_bins, len(values))
num_bins = int(value_range / bin_width)
num_bins = max(min_bins, min(max_bins, num_bins))
return (num_bins, bin_width, min_value)
def analytics_degree_distribution(graph):
# nx graph to degree distribution
degree_sequence = [d for n, d in graph.degree()] # index is node id, value is degree
print(GD.nodes["nodes"])
print(len(GD.nodes["nodes"]))
print({GD.nodes["nodes"][i]["n"]: degree_sequence[i] for i in range(len(GD.nodes["nodes"]))})
return degree_sequence
def plotly_degree_distribution(degrees, highlighted_bar=None):
maximum_amount_of_bars = 10
highlighted_degrees = []
maximum_degree = max(degrees)
if maximum_degree <= maximum_amount_of_bars:
num_bins = maximum_degree
else:
num_bins = min(int(maximum_degree ** 0.5) + 1, maximum_amount_of_bars)
bin_width = math.ceil(maximum_degree / num_bins)
bin_counts = {i: 0 for i in range(num_bins)}
for degree in degrees:
bin_index = min(int(degree // bin_width), num_bins - 1)
bin_counts[bin_index] += 1
# bar chart
if maximum_degree <= maximum_amount_of_bars:
x = list(range(num_bins))
y = [bin_counts[i] for i in range(num_bins)]
colors = ['#636efa' if i != highlighted_bar else 'orange' for i in x]
layout = go.Layout(
xaxis=dict(title='Degree', fixedrange=True),
yaxis=dict(title='Number of Nodes', fixedrange=True, type='log'),
bargap=0.1,
title=None if highlighted_bar is None else f"Selected Node Degree: {highlighted_bar}",
title_y=0.97
)
highlighted_degrees = [highlighted_bar]
fig = go.Figure(data=go.Bar(x=x, y=y, marker=dict(color=colors)), layout=layout)
# hist
else:
# convert highlighted_bar to actual bin index
if highlighted_bar is not None:
highlighted_bar = math.floor(highlighted_bar / bin_width)
colors = ['#636efa' if i != highlighted_bar else 'orange' for i in range(num_bins)]
if highlighted_bar is not None:
min_degree_selected = int(highlighted_bar * bin_width)
max_degree_selected = int((highlighted_bar + 1) * bin_width - 1) if int((highlighted_bar + 1) * bin_width - 1) <= maximum_degree else maximum_degree
highlighted_degrees = list(range(min_degree_selected, max_degree_selected + 1))
layout = go.Layout(
xaxis=dict(title='Degree Range', fixedrange=True),
yaxis=dict(title='Number of Nodes', fixedrange=True, type='log'),
bargap=0.1,
title=None if highlighted_bar is None else f"Selected Node Degrees: {min_degree_selected} to {max_degree_selected}",
title_y=0.97
)
fig = go.Figure(data=go.Histogram(x=degrees, xbins=dict(size=bin_width, start=min(degrees), end=max(degrees)), marker=dict(color=colors)), layout=layout)
fig.update_layout(width=400, height=400, font_color='rgb(200,200,200)', paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)", margin=dict(l=10, r=40, t=30, b=10))
fig.update_yaxes(showticklabels=False)
fig.update_layout(uniformtext_minsize=12, uniformtext_mode='show')
plotly_json = json.dumps(fig, cls=pu.PlotlyJSONEncoder)
return (plotly_json, highlighted_degrees)
def analytics_color_degree_distribution(degrees, highlight):
# get nodes to highlight
highlighted_degrees = set(highlight)
highlight_nodes = [i for i in range(len(degrees)) if degrees[i] in highlighted_degrees]
# gen textures
node_colors = []
for node in range(len(GD.pixel_valuesc)):
if node in highlight_nodes:
node_colors.append((255, 166, 0, 150))
continue
node_colors.append((55, 55, 55, 100))
# get links
link_colors = []
try:
with open("static/projects/"+ GD.data["actPro"] + "/links.json", "r") as links_file:
links = json.load(links_file)
# set link colors
link_colors = [(55, 55, 55, 30) for _ in links["links"]]
# create images
texture_nodes_active = Image.open("static/projects/" + GD.data["actPro"] + "/layoutsRGB/" + GD.pfile["layoutsRGB"][int(GD.pdata["layoutsRGBDD"])] + ".png", "r")
texture_links_active = Image.open("static/projects/" + GD.data["actPro"] + "/linksRGB/" + GD.pfile["linksRGB"][int(GD.pdata["linksRGBDD"])] + ".png", "r")
texture_nodes = texture_nodes_active.copy()
texture_links = texture_links_active.copy()
texture_nodes.putdata(node_colors)
texture_links.putdata(link_colors)
path_nodes = "static/projects/" + GD.data["actPro"] + "/layoutsRGB/temp.png"
path_links = "static/projects/" + GD.data["actPro"] + "/linksRGB/temp.png"
texture_nodes.save(path_nodes, "PNG")
texture_links.save(path_links, "PNG")
texture_links_active.close()
texture_nodes_active.close()
texture_links.close()
texture_nodes.close()
return {"textures_created": True, "path_nodes": path_nodes, "path_links": path_links}
except:
return {"textures_created": False}
def update_network_colors(node_colors, link_colors=None):
"""
node_colors: list where index correspond to node id and value is color in (r, g, b) format
incorporate as following:
generated_textures = analytics.update_network_colors(...)
if generated_textures["textures_created"] is False:
print("Failed to create textures for Analytics/Shortest Path.")
return
response_nodes = {}
response_nodes["usr"] = message["usr"]
response_nodes["fn"] = "updateTempTex"
response_nodes["channel"] = "nodeRGB"
response_nodes["path"] = generated_textures["path_nodes"]
emit("ex", response_nodes, room=room)
response_links = {}
response_links["usr"] = message["usr"]
response_links["fn"] = "updateTempTex"
response_links["channel"] = "linkRGB"
response_links["path"] = generated_textures["path_links"]
emit("ex", response_links, room=room)
"""
#try:
with open("static/projects/"+ GD.data["actPro"] + "/links.json", "r") as links_file:
links = json.load(links_file)
# set link colors
if link_colors is None:
link_colors = [(10,10,10, 30) for _ in links["links"]] #[(55, 55, 55, 30) for _ in links["links"]]
# create images
texture_nodes_active = Image.open("static/projects/" + GD.data["actPro"] + "/layoutsRGB/" + GD.pfile["layoutsRGB"][int(GD.pdata["layoutsRGBDD"])] + ".png", "r")
texture_links_active = Image.open("static/projects/" + GD.data["actPro"] + "/linksRGB/" + GD.pfile["linksRGB"][int(GD.pdata["linksRGBDD"])] + ".png", "r")
texture_nodes = texture_nodes_active.copy()
texture_links = texture_links_active.copy()
texture_nodes.putdata(node_colors)
texture_links.putdata(link_colors)
path_nodes = "static/projects/" + GD.data["actPro"] + "/layoutsRGB/temp.png"
path_links = "static/projects/" + GD.data["actPro"] + "/linksRGB/temp.png"
texture_nodes.save(path_nodes, "PNG")
texture_links.save(path_links, "PNG")
texture_links_active.close()
texture_nodes_active.close()
texture_links.close()
texture_nodes.close()
return {"textures_created": True, "path_nodes": path_nodes, "path_links": path_links}
# except:
# return {"textures_created": False}
def analytics_closeness(graph):
def _compute_closeness_igraph(graph):
g = ig.Graph.Adjacency((graph > 0).tolist(), mode="DIRECTED")
closeness_seq = g.closeness(mode="out")
closeness_seq = np.where(np.isnan(closeness_seq), 0, closeness_seq) # Replace NaN values with 0
return closeness_seq
if len(graph.nodes()) <= 10000 or len(graph.edges()) <= 80000:
closeness_seq = [nx.closeness_centrality(graph, node) for node in graph.nodes()]
else:
adjacency_matrix = nx.to_numpy_array(graph)
closeness_seq = _compute_closeness_igraph(adjacency_matrix)
closeness_seq = list(closeness_seq) # Convert numpy array to list
return closeness_seq
def analytics_color_continuous(assignment_arr, highlight):
# get nodes to highlight
highlight_min, highlight_max = highlight[0], highlight[1]
highlight_nodes = [i for i in range(len(assignment_arr)) if ((assignment_arr[i] >= highlight_min) and (assignment_arr[i] < highlight_max)) ]
# gen textures
node_colors = []
for node in range(len(GD.pixel_valuesc)):
if node in highlight_nodes:
node_colors.append((255, 166, 0, 100))
continue
node_colors.append((55, 55, 55, 100))
# get links
link_colors = []
try:
with open("static/projects/"+ GD.data["actPro"] + "/links.json", "r") as links_file:
links = json.load(links_file)
# set link colors
link_colors = [(55, 55, 55, 30) for _ in links["links"]]
# create images
texture_nodes_active = Image.open("static/projects/" + GD.data["actPro"] + "/layoutsRGB/" + GD.pfile["layoutsRGB"][int(GD.pdata["layoutsRGBDD"])] + ".png", "r")
texture_links_active = Image.open("static/projects/" + GD.data["actPro"] + "/linksRGB/" + GD.pfile["linksRGB"][int(GD.pdata["linksRGBDD"])] + ".png", "r")
texture_nodes = texture_nodes_active.copy()
texture_links = texture_links_active.copy()
texture_nodes.putdata(node_colors)
texture_links.putdata(link_colors)
path_nodes = "static/projects/" + GD.data["actPro"] + "/layoutsRGB/temp.png"
path_links = "static/projects/" + GD.data["actPro"] + "/linksRGB/temp.png"
texture_nodes.save(path_nodes, "PNG")
texture_links.save(path_links, "PNG")
texture_links_active.close()
texture_nodes_active.close()
texture_links.close()
texture_nodes.close()
return {"textures_created": True, "path_nodes": path_nodes, "path_links": path_links}
except:
return {"textures_created": False}
def analytics_shortest_path(graph, node_1, node_2):
node_1, node_2 = str(node_1), str(node_2)
if not graph.has_node(node_1):
print(f"ERROR: Node {GD.nodes['nodes'][int(node_1)]} not in network.")
return []
if not graph.has_node(node_2):
print(f"ERROR: Node {GD.nodes['nodes'][int(node_2)]} not in network.")
return []
try:
path = nx.shortest_path(graph, source=node_1, target=node_2, method="dijkstra")
return path
except nx.exception.NetworkXNoPath:
print(f"ERROR: Node {GD.nodes['nodes'][int(node_1)]} and node {GD.nodes['nodes'][int(node_2)]} are not connected.")
return []
# function to retreive all shortest paths
def analytics_shortest_paths(graph, node_1, node_2):
node_1, node_2 = str(node_1), str(node_2)
if not graph.has_node(node_1):
print(f"ERROR: Node {GD.nodes['nodes'][int(node_1)]} not in network.")
return []
if not graph.has_node(node_2):
print(f"ERROR: Node {GD.nodes['nodes'][int(node_2)]} not in network.")
return []
try:
paths = list(nx.all_shortest_paths(graph, source=node_1, target=node_2, method="dijkstra"))
return paths
except nx.exception.NetworkXNoPath:
print(f"ERROR: Node {GD.nodes['nodes'][int(node_1)]} and node {GD.nodes['nodes'][int(node_2)]} are not connected.")
return []
def analytics_color_shortest_path(path):
# might include this into shortest_path function
path = [int(node) for node in path]
node_colors = []
for node in range(len(GD.pixel_valuesc)):
if node in path:
node_colors.append((255, 166, 0, 150))
continue
node_colors.append((30,30,30, 60))
# get links
link_colors = []
try:
with open("static/projects/"+ GD.data["actPro"] + "/links.json", "r") as links_file:
links = json.load(links_file)
# set link colors
for link in links["links"]:
if int(link["s"]) in path and int(link["e"]) in path:
link_colors.append((255, 166, 0, 150))
continue
link_colors.append((25,25,25, 30))
# create images
texture_nodes_active = Image.open("static/projects/"+ GD.data["actPro"] + "/layoutsRGB/"+ GD.pfile["layoutsRGB"][int(GD.pdata["layoutsRGBDD"])]+".png","r")
texture_links_active = Image.open("static/projects/"+ GD.data["actPro"] + "/linksRGB/"+ GD.pfile["linksRGB"][int(GD.pdata["linksRGBDD"])]+".png","r")
texture_nodes = texture_nodes_active.copy()
texture_links = texture_links_active.copy()
texture_nodes.putdata(node_colors)
texture_links.putdata(link_colors)
path_nodes = "static/projects/"+ GD.data["actPro"] + "/layoutsRGB/temp.png"
path_links = "static/projects/"+ GD.data["actPro"] + "/linksRGB/temp.png"
texture_nodes.save(path_nodes, "PNG")
texture_links.save(path_links, "PNG")
texture_links_active.close()
texture_nodes_active.close()
texture_links.close()
texture_nodes.close()
return {"textures_created": True, "path_nodes": path_nodes, "path_links": path_links}
except:
return {"textures_created": False}
# wrapper functions for bundling
def analytics_shortest_path_run(graph):
# retreive GD node 1 and node 2 and modify session data
if "analyticsData" not in GD.pdata.keys():
### FAIL
return {"success": False, "error": "'analyticsData' not in GD.pdata! Do you have 2 nodes from current Network selected?"}
if "shortestPathNode1" not in GD.pdata["analyticsData"]:
### FAIL
return {"success": False, "error": "'shortestPathNode1' not in GD.pdata! Do you have node 1 from current Network selected?"}
if "shortestPathNode2" not in GD.pdata["analyticsData"]:
### FAIL
return {"success": False, "error": "'shortestPathNode2' not in GD.pdata! Do you have node 2 from current Network selected?"}
# write session data
if "analyticsShortestPath" not in GD.session_data.keys():
GD.session_data["analyticsShortestPath"] = {}
if "node1" not in GD.session_data["analyticsShortestPath"].keys():
GD.session_data["analyticsShortestPath"]["node1"] = GD.pdata["analyticsData"]["shortestPathNode1"]["id"]
if "node2" not in GD.session_data["analyticsShortestPath"].keys():
GD.session_data["analyticsShortestPath"]["node2"] = GD.pdata["analyticsData"]["shortestPathNode2"]["id"]
if "paths" not in GD.session_data["analyticsShortestPath"].keys():
GD.session_data["analyticsShortestPath"]["paths"] = []
if "index" not in GD.session_data["analyticsShortestPath"].keys():
GD.session_data["analyticsShortestPath"]["index"] = 0
# run shortest paths algorithm and check if a path is existing
# check if node has changed or paths is empty -> new run
if GD.pdata["analyticsData"]["shortestPathNode1"]["id"] != GD.session_data["analyticsShortestPath"]["node1"] or GD.pdata["analyticsData"]["shortestPathNode2"]["id"] != GD.session_data["analyticsShortestPath"]["node2"] or GD.session_data["analyticsShortestPath"]["paths"] == []:
# update session data from pdata
GD.session_data["analyticsShortestPath"]["node1"] = GD.pdata["analyticsData"]["shortestPathNode1"]["id"]
GD.session_data["analyticsShortestPath"]["node2"] = GD.pdata["analyticsData"]["shortestPathNode2"]["id"]
# run
node_1 = GD.session_data["analyticsShortestPath"]["node1"]
node_2 = GD.session_data["analyticsShortestPath"]["node2"]
path_data = analytics_shortest_paths(graph=graph, node_1=node_1, node_2=node_2)
# write results in session data
GD.session_data["analyticsShortestPath"]["paths"] = path_data
GD.session_data["analyticsShortestPath"]["index"] = 0
path_data = GD.session_data["analyticsShortestPath"]["paths"]
# return results
if len(path_data) == 0:
return {"success": False, "error": "No Path found. If available check previous error message."}
return {"success": True}
def analytics_shortest_path_backward():
# retrieve and modify session data
current_index = GD.session_data["analyticsShortestPath"]["index"]
path_count = len(GD.session_data["analyticsShortestPath"]["paths"])
new_index = max(0, current_index - 1 if current_index > 0 else path_count - 1)
GD.session_data["analyticsShortestPath"]["index"] = new_index
def analytics_shortest_path_forward():
# retrieve and modify session data
current_index = GD.session_data["analyticsShortestPath"]["index"]
path_count = len(GD.session_data["analyticsShortestPath"]["paths"])
new_index = current_index + 1 if current_index < path_count - 1 else 0
GD.session_data["analyticsShortestPath"]["index"] = new_index
def analytics_shortest_path_display():
# modifies and retreive session data
all_paths = GD.session_data["analyticsShortestPath"]["paths"]
current_index = GD.session_data["analyticsShortestPath"]["index"]
current_path = all_paths[current_index]
# generate textures
generated_textures = analytics_color_shortest_path(path=current_path)
# generate display information
generate_display = {"numPathsAll": len(all_paths), "numPathCurrent": current_index + 1, "pathLength": len(current_path) - 1}
# return bundled object
generated_textures.update(generate_display)
return generated_textures
def analytics_eigenvector(graph):
def _compute_eigenvector_centrality_nx(graph):
centrality = nx.eigenvector_centrality_numpy(graph)
return list(centrality.values())
def _compute_eigenvector_centrality_igraph(graph):
g = ig.Graph.Adjacency((graph > 0).tolist(), mode="DIRECTED")
centrality = g.eigenvector_centrality(directed=True)
return centrality
def _scale(centrality_seq):
min_value = min(centrality_seq)
max_value = max(centrality_seq)
scaled_seq = [(x - min_value) / (max_value - min_value) for x in centrality_seq]
return scaled_seq
if len(graph.nodes()) <= 10000 or len(graph.edges()) <= 80000:
centrality_seq = _compute_eigenvector_centrality_nx(graph)
else:
adjacency_matrix = nx.to_numpy_array(graph)
centrality_seq = _compute_eigenvector_centrality_igraph(adjacency_matrix)
#visual_centrality_seq = _scale(centrality_seq)
return centrality_seq #(centrality_seq, visual_centrality_seq)
def plotly_eigenvector(assignment_list, highlighted_bar=None):
num_bins, bin_width, min_value = __compute_histogram_bins(assignment_list)
highlighted_assignments = [highlighted_bar]
# convert highlighted_bar to bin boundaries
if highlighted_bar is not None:
highlighted_bar = math.floor((highlighted_bar - min_value) / bin_width)
colors = ['#636efa' if i != highlighted_bar else 'orange' for i in range(num_bins)] # i/10 to iter over 0 to 1 in 0.1 steps
if highlighted_bar is not None:
min_assignment_selected = (highlighted_bar * bin_width) + min_value
max_assignment_selected = ((highlighted_bar + 1) * bin_width) + min_value
highlighted_assignments = [min_assignment_selected, max_assignment_selected]
layout = go.Layout(
xaxis=dict(title='Eigenvector Value Range', fixedrange=True),
yaxis=dict(title='Number of Nodes', fixedrange=True, type='log'),
bargap=0.1,
title=None if highlighted_bar is None else f"Selected Eigenvector: {min_assignment_selected:.3f} to {max_assignment_selected:.3f}",
title_y=0.97
)
fig = go.Figure(data=go.Histogram(x=assignment_list, xbins=dict(size=bin_width, start=0, end=1), marker=dict(color=colors)), layout=layout)
fig.update_layout(width=400, height=400, font_color='rgb(200,200,200)', paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)", margin=dict(l=10, r=40, t=30, b=10))
fig.update_yaxes(showticklabels=True)
fig.update_layout(uniformtext_minsize=12, uniformtext_mode='show')
plotly_json = json.dumps(fig, cls=pu.PlotlyJSONEncoder)
return (plotly_json, highlighted_assignments)
def plotly_closeness(assignment_list, highlighted_bar=None):
num_bins, bin_width, min_value = __compute_histogram_bins(assignment_list)
print(">>",num_bins, bin_width, min_value)
highlighted_assignments = [highlighted_bar]
# convert highlighted_bar to bin boundaries
if highlighted_bar is not None:
highlighted_bar = math.floor((highlighted_bar - min_value) / bin_width)
colors = ['#636efa' if i != highlighted_bar else 'orange' for i in range(num_bins)] # i/10 to iter over 0 to 1 in 0.1 steps
if highlighted_bar is not None:
min_assignment_selected = (highlighted_bar * bin_width) + min_value
max_assignment_selected = ((highlighted_bar + 1) * bin_width) + min_value
highlighted_assignments = [min_assignment_selected, max_assignment_selected]
layout = go.Layout(
xaxis=dict(title='Closeness Range', fixedrange=True),
yaxis=dict(title='Number of Nodes', fixedrange=True, type='log'),
bargap=0.1,
title=None if highlighted_bar is None else f"Selected Closeness: {min_assignment_selected:.3f} to {max_assignment_selected:.3f}",
title_y=0.97
)
fig = go.Figure(data=go.Histogram(x=assignment_list, xbins=dict(size=bin_width, start=0, end=1), marker=dict(color=colors)), layout=layout)
fig.update_layout(width=400, height=400, font_color='rgb(200,200,200)', paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)", margin=dict(l=10, r=40, t=30, b=10))
fig.update_yaxes(showticklabels=True)
fig.update_layout(uniformtext_minsize=12, uniformtext_mode='show')
plotly_json = json.dumps(fig, cls=pu.PlotlyJSONEncoder)
return (plotly_json, highlighted_assignments)
def modularity_community_detection(ordered_graph):
if not isinstance(ordered_graph, util.OrderedGraph):
raise TypeError("The graph should be an instance of OrderedGraph.")
communities = nx.algorithms.community.modularity_max.greedy_modularity_communities(ordered_graph)
community_assignment = [0] * len(ordered_graph.node_order)
for i, comm in enumerate(communities):
for node in comm:
node_index = ordered_graph.node_order.index(node)
community_assignment[node_index] = i + 1
return community_assignment
def color_mod_community_det(communities_arr):
num_communities = max(communities_arr)
colors = util.generate_colors(n=num_communities)
colors.insert(0, (55, 55, 55, 100)) # grey out all non community nodes
node_colors = [colors[community] for community in communities_arr]
return node_colors
def generate_layout_community_det(communities_arr, ordered_graph, min_distance=0, max_distance=2):
if not isinstance(ordered_graph, util.OrderedGraph):
raise TypeError("The graph should be an instance of OrderedGraph.")
layout = {}
seed_positions = {}
for i, node in enumerate(ordered_graph.node_order):
community_label = communities_arr[i]
# distance from the current node to the seed position of the community
if community_label not in seed_positions:
# random seed position for new community
seed_positions[community_label] = (
np.random.uniform(-10, 10),
np.random.uniform(-10, 10),
np.random.uniform(-10, 10),
)
seed_position = seed_positions[community_label]
distance_to_seed = np.random.uniform(min_distance, max_distance)
# layout position based on the community seed and distance
x = seed_position[0] + np.random.uniform(-distance_to_seed, distance_to_seed)
y = seed_position[1] + np.random.uniform(-distance_to_seed, distance_to_seed)
z = seed_position[2] + np.random.uniform(-distance_to_seed, distance_to_seed)
# Add the layout position to the dictionary
layout[node] = (x, y, z)
# normalize
x, y, z = [], [], []
for node_id in range(len(communities_arr)):
x.append(layout[str(node_id)][0])
y.append(layout[str(node_id)][1])
z.append(layout[str(node_id)][2])
max_x, min_x = max(x), min(x)
max_y, min_y = max(y), min(y)
max_z, min_z = max(z), min(z)
positions = [[
(x[node_id] - min_x) / (max_x - min_x),
(y[node_id] - min_y) / (max_y - min_y),
(z[node_id] - min_z) / (max_z - min_z)
] for node_id in range(len(communities_arr))]
return positions
def generate_temp_layout(positions):
try:
### low refers to the texture layoutsl !!!!
# copy old layouts
current_layout_low = Image.open("static/projects/"+ GD.data["actPro"] + "/layoutsl/"+ GD.pfile["layouts"][int(GD.pdata["layoutsDD"])]+"l.bmp","r")
current_layout_hi = Image.open("static/projects/"+ GD.data["actPro"] + "/layouts/"+ GD.pfile["layouts"][int(GD.pdata["layoutsDD"])]+".bmp","r")
updated_layout_low = current_layout_low.copy()
updated_layout_hi = current_layout_hi.copy()
# decompose positions
pos_low = []
pos_hi = []
for node_pos in positions:
x = int(float(node_pos[0]) * 65280)
y = int(float(node_pos[1]) * 65280)
z = int(float(node_pos[2]) * 65280)
x_hi = int(x / 255)
y_hi = int(y / 255)
z_hi = int(z / 255)
x_low = x % 255
y_low = y % 255
z_low = z % 255
pos_low.append((x_low, y_low, z_low))
pos_hi.append((x_hi, y_hi, z_hi))
# save new layouts
updated_layout_low.putdata(pos_low)
updated_layout_hi.putdata(pos_hi)
path_low = "static/projects/"+ GD.data["actPro"] + "/layoutsl/templ.bmp"
path_hi = "static/projects/"+ GD.data["actPro"] + "/layouts/temp.bmp"
updated_layout_low.save(path_low, "BMP")
updated_layout_hi.save(path_hi, "BMP")
# close images
current_layout_low.close()
current_layout_hi.close()
updated_layout_low.close()
updated_layout_hi.close()
# output texture dictionary
return {"layout_created": True, "layout_low": path_low, "layout_hi": path_hi}
except Exception:
return {"layout_created": False}
def analytics_clustering_coefficient(ordered_graph):
if not isinstance(ordered_graph, util.OrderedGraph):
raise TypeError("The graph should be an instance of OrderedGraph.")
clustering_coefficients = [nx.clustering(ordered_graph, node) for node in ordered_graph.node_order]
return clustering_coefficients
def plotly_clustering_coefficient(assignment_list, highlighted_bar=None):
num_bins, bin_width, min_value = __compute_histogram_bins(assignment_list)
highlighted_assignments = [highlighted_bar]
# convert highlighted_bar to bin boundaries
if highlighted_bar is not None:
highlighted_bar = math.floor((highlighted_bar - min_value) / bin_width)
colors = ['#636efa' if i != highlighted_bar else 'orange' for i in range(num_bins)] # i/10 to iter over 0 to 1 in 0.1 steps
if highlighted_bar is not None:
min_assignment_selected = (highlighted_bar * bin_width) + min_value
max_assignment_selected = ((highlighted_bar + 1) * bin_width) + min_value
highlighted_assignments = [min_assignment_selected, max_assignment_selected]
layout = go.Layout(
xaxis=dict(title='Clustering Coefficient Range', fixedrange=True),
yaxis=dict(title='Number of Nodes', fixedrange=True, type='log'),
bargap=0.1,
title=None if highlighted_bar is None else f"Selected Cluster Coefficients: {min_assignment_selected:.3f} to {max_assignment_selected:.3f}",
title_y=0.97
)
fig = go.Figure(data=go.Histogram(x=assignment_list, xbins=dict(size=bin_width, start=0, end=1), marker=dict(color=colors)), layout=layout)
fig.update_layout(width=400, height=400, font_color='rgb(200,200,200)', paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)", margin=dict(l=10, r=40, t=30, b=10))
fig.update_yaxes(showticklabels=True)
fig.update_layout(uniformtext_minsize=12, uniformtext_mode='show')
plotly_json = json.dumps(fig, cls=pu.PlotlyJSONEncoder)
return (plotly_json, highlighted_assignments)