-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplotter.py
More file actions
1725 lines (1553 loc) · 101 KB
/
Copy pathplotter.py
File metadata and controls
1725 lines (1553 loc) · 101 KB
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
import numpy as np
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from matplotlib import gridspec
from matplotlib import colors
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import networkx as nx
import multiprocessing as mp
import pickle # used to save data (as class object)
import imageio # Used for making gifs of the network plots
import os # Used for putting the gifs somewhere
from pathlib import Path # used for file path compatibility between operating systems
import time
import utility_funcs
# Single Graph Properties: ------------------------------------------------------------------------------------------
def plot_ave_node_values(graph, individually=False, show=True, save_fig=False, title=None):
"""
Graphs nodes values over the course of a single graph's history.
:param individually: set to True to graph all nodes' values independently
"""
assert show or save_fig or title, 'Graph will be neither shown nor saved'
fig = plt.figure(figsize=(10, 4))
plt.plot(graph.nodes[:-1].sum(axis=1) / (graph.nodes.shape[1]))
plt.title(f'Sum Node values as % of possible')
plt.xlabel('Time step')
plt.ylabel(f'Information diffused')
if individually:
plt.plot(graph.nodes[:-1].mean(axis=1))
plt.title(f'Average node values')
plt.xlabel('Time step')
plt.ylabel(f'Average node values')
if save_fig:
plt.savefig(f'Ave_Node_Values {graph.nodes.shape[0]} runs.png')
if show:
plt.show()
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
def plot_eff_dist(graph, all_to_all=False, difference=False, fit=False, normalized=True, show=False, save_fig=False, title=None,
source_reward=2.6, delta=1, MPED=False):
"""
:param all_to_all: Determines if the effective distance graphed through time disregards the source, and averages for an all to all effective distance.
:param fit: Allows for linear and averaging interpolations alongside the bare data.
:param normalized: Normalized the y axis if set to True
Parameters only relevant for all_to_all=True effective distance calculations, default highly suppresses higher order paths
:param source_reward:
:param delta:
:param MPED:
"""
assert show or save_fig or title, 'Effective Distance Graph will be neither shown nor saved'
fig = plt.figure(figsize=(12, 6))
if difference:
mean_eff_dist_history = graph.get_eff_dist(all_to_all_eff_dist=all_to_all, overall_average=False, MPED=MPED, source_reward=source_reward, delta=delta)
# mean_eff_dist_history = graph.get_eff_dist(graph.A[-1], multiple_path=MPED, parameter=delta) - graph.get_eff_dist(graph.A[0], multiple_path=MPED, parameter=delta)
elif all_to_all:
mean_eff_dist_history = np.array([graph.evaluate_effective_distances(source_reward=source_reward, parameter=delta, multiple_path_eff_dist=MPED, source=None, timestep=t) for t in range(graph.A.shape[0])])
mean_eff_dist_history = np.mean(np.mean(mean_eff_dist_history, axis=1), axis=1)
# mean_eff_dist_history = np.mean(graph.evaluate_effective_distances(source_reward=source_reward, parameter=delta, multiple_path_eff_dist=MPED, source=None, timestep=-1))
else:
mean_eff_dist_history = np.mean(graph.eff_dist_to_source_history, axis=1)
x = np.array(range(len(mean_eff_dist_history)))
if normalized:
y = np.array(mean_eff_dist_history) / np.amax(mean_eff_dist_history)
else:
y = mean_eff_dist_history
plt.plot(x, y)
if all_to_all:
plt.title(f'All-to-All Effective Distance history')
else:
plt.title(f'Effective Distance history')
plt.xlabel('Time step')
plt.ylabel(f'Effective distance')
if fit:
if fit == 'log':
# log_fit = np.polyfit(np.log(x), y, 1, w=np.sqrt(y))
# plt.plot(x, np.exp(log_fit[1])*np.exp(log_fit[0]*x))
# a, b = optimize.curve_fit(lambda t, a, b: a * np.exp(b * t), x, y, p0=(1, 0.5))
# plt.plot(x, a[0] * np.exp(a[1] * x))
print("Logarithmic/exponential fitting encounters inf/NaN errors in regression :(")
if fit == 'linear':
linear_fit = np.polyfit(x, y, 1, w=np.sqrt(y))
plt.plot(x, linear_fit[0]*x + linear_fit[1])
if fit == 'average':
ave_range = int(len(y)/20)
assert ave_range % 2 == 0, 'Average range must be even (lest, for this algorithm). Default range is ave_range = int(len(y)/20)'
half_range = int((ave_range/2))
averaging_fit = [np.mean(y[index-half_range:index+half_range]) for index in x[half_range:-half_range]]
plt.plot(averaging_fit)
if show:
plt.show()
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
if save_fig:
plt.savefig(f'Effective_Distance for edge_to_eff_dist_coupling of {graph.edge_conservation_coefficient}.png')
plt.close(fig)
def plot_node_values(graph, node='all', show=False, save_fig=False, title=None):
"""
Plots node values over the course of the graph's run history.
:param node: set to 'all' to graph all node values simultanouesly, else select intended node index (< num_nodes)
"""
assert show or save_fig or title, 'Graph will be neither shown nor saved'
fig = plt.figure(figsize=(10, 4))
if node == 'all':
plt.plot(graph.nodes)
plt.title(f'All nodes\' values')
plt.xlabel('Time step')
plt.ylabel(f'Nodes values') # reveals it generally gets all the information!
else:
plt.plot(graph.nodes[:-2, node])
plt.title(f'{node}\'th Node\'s values')
plt.xlabel('Time step')
plt.ylabel(f'{node}th node\'s values') # reveals it generally gets all the information!
if save_fig:
plt.savefig(f'{node} node_values with edge_to_eff_dist_coupling of {np.round(graph.edge_conservation_coefficient, 2)} and {graph.nodes.shape[0]} runs.png')
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
if show:
plt.show()
def plot_node_edges(graph, node, show=False, save_fig=False, title=None):
"""
Graphs node's edges values.
:param node: node index whose edges are to be graphed over time.
"""
assert show or save_fig or title, 'Graph will be neither shown nor saved'
fig = plt.figure(figsize=(10, 4))
plt.plot(graph.A[:, :, node])
plt.title(f'Node Edges')
plt.xlabel('Timestep')
plt.ylabel(f'{node}th node\'s incoming edge values')
if save_fig:
plt.savefig(f'Edge values of {node} node for {graph.A.shape[0]} runs.png')
if show:
plt.show()
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
def plot_edge_sum(graph, node=None, standard_deviation=False, incoming_edges=False, show=False, save_fig=False, title=None):
"""
:param node: index of node to be examined. If None (as default) then edge sums/edge stds, all nodes are plotted.
:param standard_deviation: determines if graphing standard deviations rather than sums
:param incoming_edges: if True, considers incoming rather than outgoing edges, which are by default normalized.
# incoming edge sum only relevant if they are not normalized
"""
assert show or save_fig or title, 'Graph will be neither shown nor saved'
fig = plt.figure(figsize=(10, 4))
if standard_deviation:
edge_std_for_all_nodes = np.zeros((graph.num_nodes, graph.A[:, 0, 0].size))
for Node in range(0,
graph.A[0][-1].size): # evaluates standard deviations, Node capitalized to distinguish scope
edge_std_for_all_nodes[Node] = np.std(graph.A[:, Node], axis=1)
# edge_std_for_all_nodes[Node] = [edge_values.std() for edge_values in graph.A[:, Node][:]] # less efficient?
if node or node == 0:
fig = plt.figure(figsize=(10, 4))
plt.plot(edge_std_for_all_nodes[node, :])
plt.title(f'standard deviations, {graph.nodes.shape[0]} runs')
plt.xlabel('Time steps')
plt.ylabel(f'std of {node}th node\'s edges')
if save_fig:
plt.savefig(f'std_of_node_{node}_edges for {graph.nodes.shape[0]} runs.png')
if show:
plt.show()
else:
fig = plt.figure(figsize=(10, 4))
plt.plot(edge_std_for_all_nodes.T)
plt.title(f'Standard Deviations, {graph.nodes.shape[0]} runs')
plt.xlabel('Timestep')
plt.ylabel(f'std of all node edges')
if save_fig:
plt.savefig(f'std_of_all_node_edges with {graph.nodes.shape[0]} runs.png')
if show:
plt.show()
if incoming_edges:
edge_sums = graph.A.sum(axis=1) # returns sums of columns for every timestep
else:
edge_sums = graph.A.sum(axis=2) # returns sums of rows for every timestep
if node or node == 0:
plt.plot(edge_sums[:, node])
if incoming_edges:
plt.plot(edge_sums[node, :])
plt.title(f'sum of node {node} edges')
plt.xlabel('Time steps')
plt.ylabel(f'Sum of {node}th node\'s edges')
if save_fig:
plt.savefig(f'sum of node {node} edges.png')
if show:
plt.show()
else:
plt.plot(edge_sums)
plt.title(f'Sum of every node edges')
plt.xlabel('Time steps')
plt.ylabel(f'Sum of every nodes\' edges')
if save_fig:
plt.savefig(f'sum of every node edges.png')
if show:
plt.show()
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
def plot_degree_distribution_var_over_time(graph, show=False, save_fig=False, title=False):
"""
Plots variance of the degree distribution over time.
"""
deg_var_history = [np.var(graph.degree_distribution(timestep=timestep)) for timestep in range(graph.A.shape[0])]
fig = plt.figure(figsize=(10, 4))
plt.plot(deg_var_history)
plt.title(f'Degree Distribution Variance')
plt.xlabel('Timestep')
plt.ylabel(f'Degree Distribution Variance')
if save_fig:
plt.savefig(f'Degree Distribution Variance.png')
if show:
plt.show()
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
# NetworkX Observables: ---------------------------------------------------------------------------------------------
def plot_clustering_coefficients(nx_graphs, source=False, average_clustering=False, show=False, save_fig=False, title=None):
"""
Plots clustering Coefficients. Requires a series of pre-converted graphs as NetworkX graphs
:param source: if not None, computes ave_clustering for the single (presumably source) node
"""
if source:
if average_clustering:
clustering_coefficients = [nx.average_clustering(nx_graphs[i], weight='weight', nodes=[source]) for i in range(len(nx_graphs))]
else:
clustering_coefficients = [nx.clustering(nx_graphs[i], weight='weight', nodes=[source])[0] for i in range(len(nx_graphs))]
else:
if average_clustering:
clustering_coefficients = [nx.average_clustering(nx_graphs[i], weight='weight') for i in range(len(nx_graphs))]
else:
clustering_coefficients = np.array([list(nx.clustering(nx_graphs[i], weight='weight').values()) for i in range(len(nx_graphs))])
fig = plt.figure(figsize=(12, 6))
plt.plot(clustering_coefficients)
plt.xlabel('Time steps')
plt.ylabel(f'Clustering Coefficient')
if source and average_clustering or source is 0 and average_clustering:
plt.title(f'Average Clustering Coefficients for node [{source}]')
elif source or source is 0:
plt.title(f'Clustering Coefficients for node [{source}]')
elif average_clustering:
plt.title(f'Average Clustering Coefficients')
else:
plt.title(f'Clustering Coefficients [for all nodes]')
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
if save_fig:
plt.savefig(f'Clustering Coefficients.png')
if show:
plt.show()
def plot_ave_neighbor_degree(nx_graphs, source='in', target='in', node=False, show=False, save_fig=False, title=None):
"""
Plots average Neighbor degree. Requires a series of pre-converted graphs as NetworkX graphs
:param source: if not None, computes ave_neighborhood degree for the single (presumably source) node
"""
if node:
ave_neighbor_degree = [list(nx.average_neighbor_degree(nx_graphs[t], nodes=[node], source=source, target=target, weight='weight').values()) for t in range(len(nx_graphs))]
else:
ave_neighbor_degree = [list(nx.average_neighbor_degree(nx_graphs[t], source=source, target=target, weight='weight').values()) for t in range(len(nx_graphs))]
fig = plt.figure(figsize=(12, 6))
plt.plot(ave_neighbor_degree)
plt.xlabel('Time steps')
plt.ylabel(f'Average Neighbor Degree')
if node or node is 0:
plt.title(f'Neighbor Degree for node [{node}], target {target}, source {source}')
else:
plt.title(f'Neighbor Degree [for all nodes], target {target}, source {source}')
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
if save_fig:
plt.savefig(f'Neighbor_Degree.png')
if show:
plt.show()
def plot_shortest_path_length(nx_graphs, show=False, save_fig=False, title=None):
"""
Requires fully connected graph (no islands) though could be modified to allow for analysis of disprate components
Plots AVERAGE shortest path lengths. Requires a series of pre-converted graphs as NetworkX graphs
:param nx_graphs: requires pre-converted nx_graphs.
"""
ave_shortest_path_length = [nx.average_shortest_path_length(nx_graphs[t], weight='weight') for t in range(len(nx_graphs))]
fig = plt.figure(figsize=(12, 6))
plt.plot(ave_shortest_path_length)
plt.xlabel('Time steps')
plt.ylabel(f'Average Shortest Path Length')
plt.title(f'Average Shortest Paths')
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
if save_fig:
plt.savefig(f'Average_Shortest_Path_Lengths.png')
if show:
plt.show()
# Heatmaps: ---------------------------------------------------------------------------------------------------------
def plot_adjacency_matrix_as_heatmap(graph, timestep=-1, show=False, save_fig=False, title=None):
"""
Returns adjacency matrix at timestep plotted as a heat map. Default timestep is the latest value.
"""
assert show or save_fig or title, 'Graph will be neither shown nor saved'
fig = plt.figure(figsize=(10, 10))
plt.imshow(graph.A[timestep], cmap='viridis')
plt.colorbar()
if timestep == -1:
plt.title(f'Adjacency Matrix at final timestep as heat map')
else:
plt.title(f'Adjacency Matrix at timestep {timestep} as heat map')
if save_fig:
plt.savefig(f'Adjacency Matrix heat map at run {timestep}.png')
if show:
plt.show()
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
def plot_all_to_all_eff_dists_as_heatmap(graph, timestep=-1, source_reward=2.6, parameter=12, MPED=False, normalize=True, log_norm=False, show=False, save_fig=False, title=None):
"""
Returns all to all effective distances at timestep plotted as a heat map. Default timestep is the latest value.
"""
assert show or save_fig or title, 'Graph will be neither shown nor saved'
fig = plt.figure(figsize=(10, 10))
data = graph.evaluate_effective_distances(source_reward=source_reward, parameter=parameter, timestep=timestep, multiple_path_eff_dist=MPED, source=None)
# assert normalize != log_norm, 'cannot both log norm and norm at the same time'
if log_norm:
data = np.log(data)
if normalize:
data /= np.max(data)
plt.imshow(data, cmap='viridis')
plt.colorbar()
if MPED:
ED_type = 'MPED'
else:
ED_type = 'RWED'
if timestep == -1:
plt.title(f'All-to-All {ED_type} at final timestep as heat map')
else:
plt.title(f'All-to-All {ED_type} at timestep {timestep} as heat map')
if save_fig:
plt.savefig(f'All-to-All {ED_type} heat map at run {timestep}.png')
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
if show:
plt.show()
def plot_heatmap(TwoD_data, x_range=None, y_range=None, normalize=False, tick_scale=2, title=None, fig_title=None, interp_method=None, show=False):
"""
Generalized heatmap plotter, used for post grid-search plots.
:param TwoD_data: Requires data of the dimensionality of the resultant heatmap (thus 2d)
:param x_range: Full set of x values
:param y_range: Full set of y values
:param normalize: Optional Normalization of heatmap
:param tick_scale: spacing between x/yvalues. (e.g. tick_scale=2 => only half of x/y values are shown as ticks)
:param title: Saves file as title.
:param fig_title: Title displayed in resultant figure .png
"""
if normalize: # though data is automatically normalized in output heatmap.
data = np.array(TwoD_data / np.amax(np.array(TwoD_data)))
else:
data = TwoD_data
if x_range.any(): plt.xticks(x_range)
if y_range.any(): plt.yticks(y_range)
x_interval = (x_range[2]-x_range[1])
y_interval = (y_range[2]-y_range[1])
plt.imshow(data, cmap='viridis', extent=[x_range[0], x_range[-1]+x_interval, y_range[0], y_range[-1]+y_interval], aspect='auto', interpolation=interp_method)
xticks = np.arange(x_range[0], x_range[-1], tick_scale*x_interval)
yticks = np.arange(y_range[0], y_range[-1], tick_scale*y_interval)
plt.xticks(xticks)
plt.yticks(yticks)
plt.colorbar()
plt.xlabel('Selectivity')
plt.ylabel('Edge Conservation')
if show:
plt.show()
if fig_title:
plt.title(f'{fig_title}')
if title:
plt.savefig(f'{title}.png')
plt.close()
# Histograms: -------------------------------------------------------------------------------------------------------
def plot_weight_histogram(graph, num_bins=False, timestep=-1, show=False, save_fig=False, title=None):
"""
Plots histogram for edge weight distribution (edge weight distribution is considered for the entire graph, disconnected from nodes)
:param num_bins: explicitly set the number of bins (bars) for the histogram to use.
"""
assert show or save_fig or title, 'Graph will be neither shown nor saved'
edges = (graph.A[timestep]).flatten()
fig = plt.figure(figsize=(10, 10))
if num_bins:
plt.hist(edges, bins=num_bins)
else:
plt.hist(edges) # bins = auto, as per np.histogram
if timestep == -1:
plt.title(f"Weight histogram for all edges final timestep ({graph.A.shape[0]-1})")
else:
plt.title(f"Weight histogram for all edges timestep: {timestep} ")
if save_fig:
plt.savefig(f'Weight histogram with {num_bins} bins.png')
if show:
plt.show()
def plot_histogram(data, num_bins=False, show=False):
"""
General histogram plotter shortcut; simply input flattened data as data.
:param data: flattened data to be graphed as a histogram.
:param num_bins: If desired, specify the number of bins explicitly.
"""
fig = plt.figure(figsize=(10, 10))
if num_bins:
plt.hist(data, bins=num_bins)
else:
plt.hist(data) # bins = auto, as per np.histogram
if show:
plt.show()
def plot_degree_histogram(graph, num_bins=False, timestep=-1, show=False, save_fig=False, title=False):
"""
Plots degree distribution (of entire graph) as a histogram.
:param num_bins: explicit number of bins for histogram, (default sets them automatically)
"""
# nx_graph = graph.convert_to_nx_graph(timestep=timestep)
# degree_dist = [val[1] for val in list(nx_graph.degree(weight='weight'))]
degree_dist = graph.degree_distribution(timestep=timestep)
fig = plt.figure(figsize=(10, 10))
if num_bins:
plt.hist(degree_dist, bins=num_bins)
else:
plt.hist(degree_dist) # bins = auto, as per np.histogram
plt.xlabel("Total (outgoing) Edge Weight")
plt.xlabel("Node Count (w/ given edge weight)")
if timestep == -1:
plt.title(f"Degree histogram for all edges final timestep ")
else:
plt.title(f"Degree histogram for all edges timestep: {timestep} ")
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
if save_fig:
plt.savefig(f'Degree histogram with {num_bins} bins.png')
if show:
plt.show()
def plot_edge_histogram(graph, num_bins=False, timestep=-1, show=False, save_fig=False, title=False):
"""
Plots degree distribution (of entire graph) as a histogram.
:param num_bins: explicit number of bins for histogram, (default sets them automatically)
"""
edge_degree_dist = graph.A[timestep].flatten()
fig = plt.figure(figsize=(10, 10))
if num_bins:
plt.hist(edge_degree_dist, bins=num_bins)
else:
plt.hist(edge_degree_dist) # bins = auto, as per np.histogram
if timestep == -1:
plt.title(f"Edge Degree histogram for all edges final timestep ")
else:
plt.title(f"Edge Degree histogram for all edges timestep: {timestep} ")
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
if save_fig:
plt.savefig(f'Edge Degree histogram with {num_bins} bins.png')
if show:
plt.show()
def plot_source_distribution(graph, num_bins=False, timestep=-1, show=False, save_fig=False, title=False):
"""
Plots source distribution over the course of the graphs history as a histogram
:param num_bins: Explicitly set the number of desired histogram bins. Default automatically sets for data
:param timestep: cut off point of graph history to examine source history. Defaults to the end of the graph
"""
if len(utility_funcs.arr_dimen(graph.source_node_history)) > 1:
source_distribution = np.array(graph.source_node_history)[:, :timestep].flatten()
else:
source_distribution = graph.source_node_history[:timestep]
fig = plt.figure(figsize=(10, 10))
if num_bins:
plt.hist(source_distribution, bins=num_bins)
else:
plt.hist(source_distribution) # bins = auto, as per np.histogram
if timestep == -1:
plt.title(f"Source histogram for all edges final timestep ")
else:
plt.title(f"Source histogram for all edges timestep: {timestep} ")
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
if save_fig:
plt.savefig(f'Source histogram with {num_bins} bins.png')
if show:
plt.show()
def plot_effective_distance_histogram(eff_dists, num_bins=False, timestep=-1, show=False, save_fig=False):
"""
TODO: consider deletion
"""
eff_dists = eff_dists.flatten()
fig = plt.figure(figsize=(10, 10))
if num_bins:
plt.hist(eff_dists, bins=num_bins)
else:
plt.hist(eff_dists) # bins = auto, as per np.histogram
if timestep == -1:
plt.title(f"Effective distance histogram for all to all edges final timestep")
else:
plt.title(f"Effective distance histogram for all to all paths timestep: {timestep} ")
if save_fig:
plt.savefig(f'Effective distance histogram at step {timestep}.png')
if show:
plt.show()
# Network Illustrations: --------------------------------------------------------------------------------------------
def plot_nx_network(nx_graph, node_size_scaling=100, show=False, save_fig=False, title=None):
fig = plt.figure(figsize=(10, 10))
pos = nx.spring_layout(nx_graph, k=0.5, scale=0.5, weight='weight', seed=42)
labels = nx.draw_networkx_labels(nx_graph, pos=pos, font_color='blue', font_size=20) # For use in debugging
# labels = nx.draw_networkx_labels(nx_graph, pos=pos, font_color='blue', font_size=0) # For use in debugging
# node_weights = [1]*len(nx_graph.nodes())
node_weights = [weight*node_size_scaling for weight in nx.get_node_attributes(nx_graph, "weight").values()]
weights = [1.6 for u, v in nx_graph.edges()] # Simple binary weights
edge_colors = 'black'
nx.draw_networkx_edges(nx_graph, pos, nodelist=['0'], alpha=0.8, width=weights, arrowsize=4, edge_color=edge_colors, connectionstyle='arc3, rad=0.2', edge_cmap='winter')
node_colors = ['grey' for _ in nx_graph]
nx.draw_networkx_nodes(nx_graph, pos, node_size=node_weights, node_color=node_colors, linewidths=weights, label=labels, cmap=plt.get_cmap('viridis'))
plt.title(f"Network Graph")
if title:
plt.savefig(f'{title}.png')
if show:
plt.show()
if save_fig and not title:
plt.savefig(f'Network Structures.png')
plt.close(fig)
def plot_single_network(graph, timestep, directed=True, node_size_scaling=None, source_weighting=False, position=None, show=False, save_fig=False, seedless=False, title=None):
"""
:param timestep: Point at which the network's structure is to be graphed.
:param directed: As the Graph class considers only directed networks, this delta is not be to shifted unless considering undirected graphs.
:param node_size_scaling: Works as a scale for the size of nodes in the plot. Defaults to length of the graph (num_runs)
:param source_weighting: If True, nodes are scaled proportional to the number of times they have been the source. Only relevant for variable source seeding.
:param position: sets the position of the nodes, as used when ensuring that subsequent graphs are not shifting the node positions (e.g. for the animator)
"""
fig = plt.figure(figsize=(10, 10))
if directed:
nx_G = nx.to_directed(nx.from_numpy_matrix(np.array(graph.A[timestep]), create_using=nx.DiGraph))
else:
nx_G = nx.from_numpy_matrix(np.array(graph.A[timestep]))
if position: # allows for setting a constant layout
pos = nx.spring_layout(nx_G, weight='weight', pos=position, fixed=list(nx_G.nodes))
else:
pos = nx.spring_layout(nx_G, k=0.5, scale=0.5, weight='weight', seed=42)
if node_size_scaling is None:
node_size_scaling = 2*graph.nodes.shape[0] # So that nodes are sized proportional to the number of times they *could've* been the source
# labels = nx.draw_networkx_labels(nx_G, pos=pos, font_color='blue', font_size=20) # For use in debugging
labels = None
# pos = nx.drawing.layout.spring_layout(nx_G, k=0.5, pos=pos, weight='weight', fixed=list(nx_G.nodes))
weights = [np.round((nx_G[u][v]['weight'] * 2.5), 10) for u, v in nx_G.edges()]
nx.draw_networkx_edges(nx_G, pos, nodelist=['0'], alpha=0.8, width=weights, arrowsize=4, edge_color='k',
connectionstyle='arc3, rad=0.2', edge_cmap='winter')
node_colors = ['grey' for _ in nx_G]
if not seedless:
node_colors[graph.source_node_history[timestep - 1]] = 'red'
# edge_colors = range(2, nx_G.number_of_edges() + 2)
edge_colors = 'black'
if source_weighting: # sizes nodes proportional to the number of times they've been a source
source_weights = [graph.source_node_history[:timestep].count(node)*node_size_scaling for node in range(graph.nodes.shape[1]-1)]
# source_weight_sum = sum(source_weights)
# source_weights = [node_size_scaling*pow((weight/source_weight_sum), 0.5) for weight in source_weights]
source_weights = [weight if weight > 0 else 1*node_size_scaling for weight in source_weights]
nx.draw_networkx_nodes(nx_G, pos,
edgecolors=edge_colors,
node_size=source_weights,
node_color=node_colors,
linewidths=weights,
label=labels,
cmap=plt.get_cmap('viridis'))
plt.title(f"Nodes size proportional to number of times they've been the source [timestep: {timestep}]")
else:
incoming_edge_sum = graph.A[timestep].sum(axis=1)
incoming_edge_sum = [node_size_scaling * node / sum(incoming_edge_sum) for node in incoming_edge_sum]
nx.draw_networkx_nodes(nx_G, pos,
edgecolors=edge_colors,
node_size=incoming_edge_sum,
node_color=node_colors,
linewidths=weights,
label=labels,
cmap=plt.get_cmap('viridis'))
plt.title(f"Nodes size proportional to outgoing edge weights [timestep: {timestep}]")
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
if show:
plt.show()
if save_fig and not title:
plt.savefig(f'Network Structure(s) after {graph.nodes.shape[0]} runs.png')
plt.close(fig)
def plot_network(graph, directed=True, node_size_scaling=200, nodes_sized_by_eff_distance=False, no_seeding=False,
show=False, save_fig=False, title=None):
"""
Plots the graph at four equispaced points spanning the entire time to denote network evolution through time in a single figure.
:param directed: As the Graph class considers only directed networks, this delta is not be to shifted unless considering undirected graphs.
:param node_size_scaling: Works as a scale for the size of nodes in the plot.
:param nodes_sized_by_eff_distance: Determines if the nodes are sized inversely proportional to their effective distance from the source 9at the timesteps at which at they are graphed)
"""
fig = plt.figure(figsize=(12, 6))
assert show or save_fig or title, 'Graph will be neither shown nor saved'
count = 1
timesteps = [0, int(graph.nodes.shape[0] / 3), int(graph.nodes.shape[0] * (2 / 3)), (graph.nodes.shape[0])-1]
for timestep in timesteps:
if directed:
nx_G = nx.to_directed(nx.from_numpy_matrix(np.array(graph.A[timestep]), create_using=nx.DiGraph))
if count == 1:
pos = nx.spring_layout(nx_G, k=0.5, scale=0.5, weight='weight')
# pos = nx.spring_layout(nx_G.reverse(copy=True), k=0.5, scale=0.5, weight='weight')
# Transposing is likely the intended effect, and more readily done
else:
nx_G = nx.from_numpy_matrix(np.array(graph.A[timestep]))
if count == 1:
pos = nx.spring_layout(nx_G, k=0.5, scale=5.0, weight='weight')
# pos = nx.spring_layout(nx_G.reverse(copy=True), k=0.5, scale=0.5, weight='weight')
# Transposing is likely the intended effect
incoming_edge_sum = graph.A[timestep].sum(axis=1)
plt.subplot(1, 4, count)
count += 1
weights = [nx_G[u][v]['weight'] * 1.5 for u, v in nx_G.edges()]
incoming_edge_sum = [(node_size_scaling * node / sum(incoming_edge_sum)) for node in incoming_edge_sum]
edge_colors = 'black'
node_colors = ['grey'] * graph.nodes.shape[1]
if not no_seeding: node_colors[graph.source_node_history[timestep]] = 'red'
nx.draw_networkx_edges(nx_G, pos, nodelist=['0'], alpha=0.8, width=weights, arrowsize=4, connectionstyle='arc3, rad=0.2')
nx.draw_networkx_nodes(G=nx_G, pos=pos,
edgecolors=edge_colors,
node_size=incoming_edge_sum,
node_color=node_colors,
linewidths=weights,
cmap=plt.get_cmap('viridis'))
plt.title("timestep: {0}".format(timestep))
if nodes_sized_by_eff_distance:
nx.draw_networkx_nodes(nx_G, pos,
edgecolors=edge_colors,
node_size=graph.nodes,
node_color=node_colors,
linewidths=weights,
cmap=plt.get_cmap('viridis'))
plt.title("timestep: {0}".format(timestep))
if show:
plt.show()
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
if save_fig:
plt.savefig(f'Network Structure(s) for edge_to_eff_dist_coupling of {np.round(graph.edge_conservation_coefficient, 2)}, {graph.nodes.shape[0]} runs.png')
plt.close(fig)
# Network Animations: --------------------------------------------------------------------------------------------
def animate_network_evolution(graph, node_size_scaling=200, source_weighting=False, directory_name='network_animation',
file_title='network_evolution', parent_directory=None, gif_duration_in_sec=5,
num_runs_per_fig=None, verbose=False):
"""
Creates a gif and mp4 of the network evolution and stores them in a folder with the individual frames.
:param node_size_scaling: Works as a scale for the size of nodes in the plot. Defaults to length of the graph (num_runs)
:param source_weighting: If True, nodes are scaled proportional to the number of times they have been the source. Only relevant for variable source seeding.
:param directory_name: string, name of directory for resultant figures and animations. Of course, a path behind the title (e.g. directory_name=Path(directory_path, 'network_animation'))
determines the location of the resultant file as well.
:param file_title: string, sets title of resultant gif and mp4. by default, (if no path set into file title string) places the file into the above specified directory.
:param parent_directory: string, set to determine directory of output animation and stills. Defaults to the parent directory of this python file.
:param gif_duration_in_sec: int, determines the mp4 and gif's eventual duration in seconds.
:param num_runs_per_fig: int, set the number of runs between graphed figure (which individually compose the frames of the resultant animation)
:param verbose: bool, if True, prints intermediary % completion and eventual total time for completion.
"""
assert num_runs_per_fig != 0, 'Number of runs per figure must be larger than 0, or else omitted for graph every run'
if parent_directory is None:
source_directory = os.path.dirname(__file__)
else:
source_directory = parent_directory
vid_path = Path(source_directory, directory_name)
fig_path = Path(vid_path, 'figures')
try:
os.mkdir(vid_path), f'Created folder for network structure gif at {vid_path}'
os.mkdir(fig_path), f'Created folder for figures at {fig_path}'
except OSError:
print(f'{vid_path} already exists, adding or overwriting contents')
pass
nx_G = nx.to_directed(nx.from_numpy_matrix(np.array(graph.A[0]), create_using=nx.DiGraph))
initial_position = nx.drawing.layout.spring_layout(nx_G, k=0.5, scale=0.5, weight='weight')
for i in range(0, graph.A.shape[0] - 1):
files = Path(fig_path, f'{i:04}')
if num_runs_per_fig:
if i % num_runs_per_fig == 0:
plot_single_network(graph, i, node_size_scaling=node_size_scaling, source_weighting=source_weighting,
position=initial_position, show=False, save_fig=True, title=files)
else:
plot_single_network(graph, i, node_size_scaling=node_size_scaling, source_weighting=source_weighting,
position=initial_position, show=False, save_fig=True, title=files)
if verbose:
if int(i % graph.A.shape[0]) % int(graph.A.shape[0] / 10) == 0:
print(f'{(i / graph.A.shape[0]) * 100:.1f}%-ish done')
if i == graph.A.shape[0] - 1:
print('Now creating video from rendered images... (ignore resolution reformatting error)')
if num_runs_per_fig:
writer = imageio.get_writer(f'{Path(vid_path, file_title)}.mp4',
fps=((graph.A.shape[0] / num_runs_per_fig) / gif_duration_in_sec))
else:
writer = imageio.get_writer(f'{Path(vid_path, file_title)}.mp4', fps=(graph.A.shape[0] / gif_duration_in_sec))
images = []
for filename in sorted(os.listdir(fig_path)):
if filename.endswith(".png"):
images.append(imageio.imread(Path(fig_path, filename)))
writer.append_data(imageio.imread(Path(fig_path, filename)))
imageio.mimsave(f'{Path(vid_path, file_title)}.gif', images)
writer.close()
if verbose:
print(f'\n gif and mp4 of network evolution created in {vid_path} \n Stills stored in {fig_path} \n')
def parallelized_animate_network_evolution(graph, source_weighting=False, node_size_scaling=True, directory_name='network_animation',
file_title='network_evolution', parent_directory=None, gif_duration_in_sec=5,
num_runs_per_fig=None, changing_layout=False, verbose=False):
"""
Creates a gif and mp4 of the network evolution and stores them in a folder with the individual frames, using all system cores for frame generation individually.
:param node_size_scaling: Works as a scale for the size of nodes in the plot. Defaults to length of the graph (num_runs)
:param source_weighting: If True, nodes are scaled proportional to the number of times they have been the source. Only relevant for variable source seeding.
:param directory_name: string, name of directory for resultant figures and animations. Of course, a path behind the title (e.g. directory_name=Path(directory_path, 'network_animation'))
determines the location of the resultant file as well.
:param file_title: string, sets title of resultant gif and mp4. by default, (if no path set into file title string) places the file into the above specified directory.
:param parent_directory: string, set to determine directory of output animation and stills. Defaults to the parent directory of this python file.
:param gif_duration_in_sec: int, determines the mp4 and gif's eventual duration in seconds.
:param num_runs_per_fig: int, set the number of runs between graphed figure (which individually compose the frames of the resultant animation)
:param verbose: bool, if True, prints intermediary % completion and eventual total time for completion.
"""
assert num_runs_per_fig != 0, 'Number of runs per figure must be larger than 0, or else omitted for graph every run'
start_time = time.time()
if parent_directory is None:
source_directory = os.path.dirname(__file__)
else:
source_directory = parent_directory
vid_path = Path(source_directory, directory_name)
fig_path = Path(vid_path, 'figures')
try:
os.makedirs(vid_path), f'Created folder for network structure gif at {vid_path}'
os.makedirs(fig_path), f'Created folder for figures at {fig_path}'
except OSError:
print(f'{vid_path}/{fig_path} already exists, adding or overwriting contents')
pass
nx_G = nx.to_directed(nx.from_numpy_matrix(np.array(graph.A[0]), create_using=nx.DiGraph))
if changing_layout:
initial_position = None
else:
initial_position = nx.drawing.layout.spring_layout(nx_G, k=0.5, scale=0.5, weight='weight')
index = 0
while index < graph.A.shape[0] - 1:
processes = []
used_cores = 0
while used_cores < mp.cpu_count():
if index > graph.A.shape[0] - 1:
break
index += 1
files = Path(fig_path, f'{index:04}')
if num_runs_per_fig:
if index % num_runs_per_fig == 0 or index < 10: # As the first few are generally the most important
p = mp.Process(target=plot_single_network, args=(graph, index, True, node_size_scaling, source_weighting, initial_position, False, True, False, files))
p.start()
processes.append(p)
used_cores += 1
else:
p = mp.Process(target=plot_single_network, args=(graph, index, True, node_size_scaling, source_weighting, initial_position, False, True, False, files))
p.start()
processes.append(p)
used_cores += 1
if verbose:
utility_funcs.print_run_percentage(index, graph.A.shape[0])
if index == graph.A.shape[0]-1: print('Now creating video from rendered images... (ignore resolution reformatting error)')
for process in processes:
process.join()
if num_runs_per_fig:
writer = imageio.get_writer(f'{Path(vid_path, file_title)}.mp4',
fps=((graph.A.shape[0] / num_runs_per_fig) / gif_duration_in_sec))
else:
writer = imageio.get_writer(f'{Path(vid_path, file_title)}.mp4', fps=(graph.A.shape[0] / gif_duration_in_sec))
images = []
for filename in sorted(os.listdir(fig_path)):
if filename.endswith(".png"):
images.append(imageio.imread(Path(fig_path, filename)))
writer.append_data(imageio.imread(Path(fig_path, filename)))
imageio.mimsave(f'{Path(vid_path, file_title)}.gif', images)
writer.close()
if verbose:
print(f'\n gif and mp4 of network evolution created in {vid_path} \n Stills stored in {fig_path} \n')
print(f"Time to animate: {int((time.time()-start_time) / 60)} minutes, {np.round((time.time()-start_time) % 60, 2)} seconds")
# def animate_grid_search_results(graph, by_edge_conservation=True, data_directory=None, subdata_directory=None, gif_duration_in_sec=5, num_runs_per_fig=None, verbose=False):
"""
# Creates a gif and mp4 of the end networks running through parameter values and stores them in a folder with the individual frames, using all system cores for frame generation individually.
# :param gif_duration_in_sec: int, determines the mp4 and gif's eventual duration in seconds.
# :param num_runs_per_fig: int, set the number of runs between graphed figure (which individually compose the frames of the resultant animation)
# :param verbose: bool, if True, prints intermediary % completion and eventual total time for completion.
assert num_runs_per_fig != 0, 'Number of runs per figure must be larger than 0, or else omitted for graph every run'
start_time = time.time()
if subdata_directory is None:
subdata_directory = data_directory
print(f'No output directory given, defaulting to output_dir same as data directory at: \n {data_directory}')
vid_path = Path(data_directory, 'grid_search_animations')
try:
os.mkdir(vid_path), f'Created folder for grid_search gif at {vid_path}'
except OSError:
print(f'{vid_path} already exists, adding or overwriting contents')
pass
# num_cores_used = int(fraction_cores_used * mp.cpu_count())*(bool(int(fraction_cores_used * mp.cpu_count()))) + 1*(not bool(int(fraction_cores_used * mp.cpu_count())))
selectivity_val = float(str(str(data_directory).split('/')[-1]).split('_')[-1])
for root, dirs, files in os.walk(data_directory):
f = sorted(files) # Order preserved due to 0 padding.
for file in f:
with open(Path(data_directory, file), 'rb') as data:
G = pickle.load(data)
data.close()
if num_runs_per_fig:
writer = imageio.get_writer(f'{Path(vid_path, file_title)}.mp4',
fps=((graph.A.shape[0] / num_runs_per_fig) / gif_duration_in_sec))
else:
writer = imageio.get_writer(f'{Path(vid_path, file_title)}.mp4', fps=(graph.A.shape[0] / gif_duration_in_sec))
images = []
for filename in sorted(os.listdir(fig_path)):
if filename.endswith(".png"):
images.append(imageio.imread(Path(fig_path, filename)))
writer.append_data(imageio.imread(Path(fig_path, filename)))
imageio.mimsave(f'{Path(vid_path, file_title)}.gif', images)
writer.close()
if verbose:
print(f'\n gif and mp4 of network grid search created in {vid_path} \n Stills stored in {fig_path} \n')
print(f"Time lapsed {utility_funcs.time_lapsed_h_m_s(time.time() - start_time)}")
"""
# 2D Plotting: ------------------------------------------------------------------------------------------------------
def plot_2d_data(data, xlabel=None, ylabel=None, color=None, plot_limits=None, show=False, fig_title=None, title=False):
fig = plt.figure(figsize=(10, 8))
if plot_limits is not None:
if plot_limits[0]: plt.xlim(*plot_limits[0])
if plot_limits[1]: plt.ylim(*plot_limits[1])
if xlabel is not None:
plt.xlabel(xlabel)
if ylabel is not None:
plt.ylabel(ylabel)
x, y = data[:, 0], data[:, 1]
plt.scatter(x, y, c=color, cmap='viridis')
if show:
plt.show()
if fig_title:
plt.title(f'{fig_title}')
if title:
plt.savefig(f'{title}.png')
plt.close(fig)
# 3D Plotting: ------------------------------------------------------------------------------------------------------
def plot_3d(function, x_range, y_range=None, piecewise=False, z_limits=None, spacing=0.05):
"""
Basic plotter for a 3d function, with the function to be given explicitly as z(x, y), along with the relevant x range.
:param function: z(x,y)
:param x_range: [lower bound, upper bound]
:param y_range: defaults to x_range, otherwise list as [lower bound, upper bound]
:param piecewise: set true if function is piecewise (i.e. contains conditional)
:param z_limits: [lower bound, upper bound]
:param spacing: interval between both x and y ranges.
"""
if y_range is None:
y_range = x_range
fig = plt.figure(figsize=(10, 8))
ax = fig.gca(projection='3d')
X = np.arange(x_range[0], x_range[1], spacing)
Y = np.arange(y_range[0], y_range[1], spacing)
if piecewise:
Z = np.zeros((len(X), len(Y)))
for i in range(len(X)):
for j in range(len(Y)):
Z[i][j] = function(X[i], Y[j])
X, Y = np.meshgrid(X, Y)
else:
X, Y = np.meshgrid(X, Y)
Z = function(X, Y)
surf = ax.plot_surface(X, Y, Z, cmap=cm.winter, linewidth=0, antialiased=False)
if z_limits:
ax.set_zlim(z_limits[0], z_limits[1])
ax.set_xlabel('Effective Distance')
ax.set_ylabel('Edge Value')
ax.set_zlabel('Info Score')
# ax.set_xlabel('x')
# ax.set_ylabel('y')
# ax.set_zlabel('z')
plt.show()
def general_3d_data_plot(data, xlabel=None, ylabel=None, zlabel=None, plot_limits=None, color=None, plot_projections=False, projections=False, fig_title=None, show=False, title=False):
# :param plot_limits: give as a list of lists of limits, i.e. [[x_min, x_max], [y_min, y_max], [z_min, z_max]]
cmap = 'viridis'
if xlabel == 'Treeness' or xlabel == 'treeness':
xdata, ydata, zdata = data[:, 2], data[:, 1], data[:, 0]
else:
xdata, ydata, zdata = data[:, 0], data[:, 1], data[:, 2]
fig = plt.figure(figsize=(10, 10))
if xlabel is not None:
x_label = xlabel
else:
x_label = 'X'
if ylabel is not None:
y_label = ylabel
else:
y_label = 'Y'
if zlabel is not None:
z_label = zlabel
else:
z_label = 'Z'
if plot_projections: