forked from dafishcode/suite2p_analysis_py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matts_network_functions.py
1418 lines (978 loc) · 45.2 KB
/
matts_network_functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.figure import Figure
from matplotlib import cm
import numpy as np
import random
import math
import community
from scipy import stats
#Functiosn to move to Admin
def create_empty_array(size):
new_array = create_empty_list(size)
for row in range(size):
columns = create_empty_list(size)
new_array[row] = columns
return new_array
def create_zero_array(size):
new_array = create_empty_list(size)
for row in range(size):
columns = create_zero_list(size)
new_array[row] = columns
new_array = np.array(new_array)
return new_array
def create_ones_array(size):
new_array = create_empty_list(size)
for row in range(size):
columns = create_list_of(size,float(1))
new_array[row] = columns
new_array = np.array(new_array)
return new_array
def symmetrical_to_upper_triangle(original_matrix):
number_of_rows,number_of_columns = np.shape(original_matrix)
new_matrix = create_zero_array(number_of_columns)
for row in range(number_of_rows):
for column in range(row, number_of_columns):
value = original_matrix[row][column]
new_matrix[row][column] = value
new_matrix = np.array(new_matrix)
np.fill_diagonal(new_matrix,0)
return new_matrix
def create_random_array(size,density,min_value,max_value):
new_array = create_empty_list(size)
for row in range(size):
columns = create_zero_list(size)
new_array[row] = columns
new_array = np.array(new_array)
for row in range(size):
for column in range(size):
if get_boolean_with_probability(density) == True:
value = random.uniform(min_value,max_value)
new_array[row][column] = value
return new_array
def create_random_array_int(size,density,min_value,max_value):
new_array = create_empty_list(size)
for row in range(size):
columns = create_zero_list(size)
new_array[row] = columns
new_array = np.array(new_array)
for row in range(size):
for column in range(size):
if get_boolean_with_probability(density) == True:
value = int(random.uniform(min_value,max_value))
new_array[row][column] = value
return new_array
def create_empty_list(size):
new_list = []
for number in range(size):
new_list.append([])
return new_list
def create_zero_list(size):
new_list = []
for number in range(size):
new_list.append(float(0))
return new_list
def create_list_of(size,item):
new_list = []
for number in range(size):
new_list.append(item)
return new_list
def assign_colour(item,number_of_items,colour_map):
colour_map = cm.get_cmap(colour_map)
value = float(item)/number_of_items
float_tuple = colour_map(value)
return float_tuple
def create_node_colour_map(node_value_list):
colour_map = []
#Get Max Weight
max_weight = 0
for node_value_pair in node_value_list:
weight = node_value_pair[1]
if weight > max_weight:
max_weight = weight
#Assign Colours
for node_value_pair in node_value_list:
weight = node_value_pair[1]
colour = assign_colour(weight,max_weight,"inferno")
colour_map.append(colour)
return colour_map
def split_list_into_chunks_of_the_same_thing(input_list):
unique_values = list(set(input_list))
unique_values.sort(reverse=True)
new_list = create_empty_list(len(unique_values))
for unique_index in range(len(unique_values)):
unique_item = unique_values[unique_index]
for list_item in input_list:
if list_item == unique_item:
new_list[unique_index].append(list_item)
return new_list
def get_boolean_with_probability(probability):
number_1 = random.uniform(0,1)
if probability == 0:
return False
if probability == 1:
return True
if probability > number_1:
return True
else:
return False
#Module Functions:
def check_module_imported():
return "Yeppers!"
#Create Graph Functions
def create_graph(connectivity_matrix):
#graph = nx.from_numpy_matrix(connectivity_matrix,parallel_edges=False)
graph = nx.from_numpy_array(connectivity_matrix)
return graph
def create_weighted_graph(connectivity_matrix):
graph = nx.from_numpy_array(connectivity_matrix, create_using=nx.DiGraph)
return graph
def get_edge_weights(graph,scaling_factor):
weight_list = []
weights = nx.get_edge_attributes(graph,"weight")
edges = nx.edges(graph)
for edge in edges:
weight = weights[edge] * scaling_factor
weight_list.append(weight)
return weight_list
def get_edge_weights_thresholded(graph,threshold):
weight_list = []
weights = nx.get_edge_attributes(graph, "weight")
edges = nx.edges(graph)
for edge in edges:
weight = weights[edge]
if weight <= threshold:
weight_list.append(weight)
else:
weight_list.append(0)
return weight_list
#Clustering Algorithms
def louvain_partition_graph(graph):
colour_map = []
partitions = community.best_partition(graph)
community_list = partitions.values()
number_of_partitions = max(community_list)
for neuron in partitions:
colour_map.append(assign_colour(partitions[neuron],number_of_partitions,"tab10"))#"viridis"
return colour_map
#Plotting Functions
def plot_graph_basic(graph):
nx.draw(graph, pos=nx.spring_layout(graph), node_size=40)
plt.show()
def plot_graph_basic_positions(graph,positions):
nx.draw(graph, pos=positions, node_size=40)
plt.show()
def plot_graph_basic_weights(graph):
edge_weights = get_edge_weights(graph,1)
colour_map = cm.get_cmap("plasma")
node_colours = louvain_partition_graph(graph)
circle_layout = nx.circular_layout(graph)
#edge_vmin=(min(edge_weights)),edge_vmax=max(edge_weights)
nx.draw(graph, pos=nx.spring_layout(graph), node_size=40, arrows=False, with_labels=False, edge_color=edge_weights, edge_cmap=colour_map, node_color=node_colours)
plt.show()
def plot_graph_basic_edge_labels(graph):
edge_weights = get_edge_weights(graph,0.5)
#edge_weights = get_edge_weights_thresholded(graph,0.5)
colour_map = cm.get_cmap("Blues")
circle_layout = nx.circular_layout(graph)
#edge_vmin=(min(edge_weights)),edge_vmax=max(edge_weights)
nx.draw(graph, pos=circle_layout, node_size=40, arrows=False, with_labels=True, edge_color=edge_weights,edge_cmap=colour_map)
nx.draw_networkx_edge_labels(graph, pos=circle_layout, node_size=40, arrows=False, with_labels=True, edge_color=edge_weights, edge_cmap=colour_map)
plt.show()
def plot_graph_basic_sizes(graph,sizes):
edge_weights = get_edge_weights(graph,0.5)
#edge_weights = get_edge_weights_thresholded(graph,0.5)
colour_map = cm.get_cmap("plasma")
circle_layout = nx.circular_layout(graph)
#edge_vmin=(min(edge_weights)),edge_vmax=max(edge_weights)
nx.draw(graph, pos=nx.spring_layout(graph), node_size=sizes, arrows=False, with_labels=False, edge_color=edge_weights,edge_cmap=colour_map)
plt.show()
def plot_graph_basic_sizes_and_positions(graph,sizes,positions,node_colours):
edge_weights = get_edge_weights(graph,0.5)
#edge_weights = get_edge_weights_thresholded(graph,0.5)
colour_map = cm.get_cmap("Purples")
circle_layout = nx.circular_layout(graph)
edge_widths = []
maximum_weight = max(edge_weights)
for weight in edge_weights:
edge_widths.append((weight/maximum_weight) * 10)
#edge_vmin=(min(edge_weights)),edge_vmax=max(edge_weights)
nx.draw(graph, pos=positions, node_size=40, arrows=False, with_labels=False, edge_color=edge_weights,edge_cmap=colour_map, width=edge_widths, node_color=node_colours)
plt.show()
def plot_graph_basic_custom_colour_map(graph,positions,node_colours):
edge_weights = get_edge_weights(graph,0.5)
colour_map = cm.get_cmap("Purples")
nx.draw(graph, pos=positions, node_size=200, arrows=False, with_labels=False, edge_color=edge_weights,edge_cmap=colour_map, node_color=node_colours)
plt.show()
def plot_graph_edge_widths_node_sizes(graph,figure,canvas,node_sizes,node_positions,node_colours):
edge_weights = get_edge_weights(graph, 0.5)
colour_map = cm.get_cmap("Purples")
edge_widths = []
maximum_weight = max(edge_weights)
for weight in edge_weights:
edge_widths.append((weight / maximum_weight) * 10)
figure.clear()
axis = figure.add_subplot(111)
nx.draw(graph, ax=axis, pos=node_positions, node_size=node_sizes, arrows=False, with_labels=False, edge_color=edge_weights,edge_cmap=colour_map, width=edge_widths, node_color=node_colours)
plt.show()
canvas.draw()
canvas.update()
def plot_graph_weights_over_threshold(graph,threshold):
colour_map = cm.get_cmap("Blues")
circle_layout = nx.circular_layout(graph)
threshold_edge_list,edge_weights = get_edges_over_threshold(graph,threshold)
nx.draw(graph, pos=nx.spring_layout(graph), node_size=40, arrows=False, with_labels=False, edge_color=edge_weights, edge_cmap=colour_map, edge_vmin=(min(edge_weights)),edge_vmax=max(edge_weights),edgelist=threshold_edge_list)
plt.show()
def plot_graph_custom_colourmap(graph,figure,canvas,scaled_node_positions,custom_colour_map,threshold,node_sizes=40):
figure.clear()
axis = figure.add_subplot(111)
colour_map = cm.get_cmap("Blues")
threshold_edge_list, edge_weights = get_edges_over_threshold(graph, threshold)
node_colours = custom_colour_map
nx.draw(graph, pos=scaled_node_positions, ax=axis, node_size=node_sizes, arrows=False, with_labels=False, edge_color=edge_weights,edge_cmap=colour_map,node_color = node_colours, edgelist=threshold_edge_list, edge_vmax=max(edge_weights), edge_vmin=0)
plt.show()
canvas.draw()
canvas.update()
def plot_graph_custom_node_and_edge_colourmaps(graph,figure,canvas,scaled_node_positions,node_colours, edge_colours):
figure.clear()
axis = figure.add_subplot(111)
edge_weights = get_edge_weights(graph,1)
nx.draw(graph, pos=scaled_node_positions, ax=axis, node_size=40, arrows=False, with_labels=False, edge_color=edge_colours,node_color = node_colours, edge_vmax=max(edge_weights), edge_vmin=1)
plt.show()
canvas.draw()
canvas.update()
def plot_graph_custom_colourmap_sizes(graph,figure,canvas,scaled_node_positions,custom_colour_map,threshold,node_sizes):
figure.clear()
axis = figure.add_subplot(111)
colour_map = cm.get_cmap("Blues")
threshold_edge_list, edge_weights = get_edges_over_threshold(graph, threshold)
node_colours = custom_colour_map
nx.draw(graph, pos=scaled_node_positions, ax=axis, node_size=node_sizes, arrows=False, with_labels=False,
edge_color=edge_weights, edge_cmap=colour_map, node_color=node_colours, edgelist=threshold_edge_list)
plt.show()
canvas.draw()
canvas.update()
def plot_graph_thresholed_weights(figure,canvas,graph,scaled_node_positions,threshold):
figure.clear()
axis = figure.add_subplot(111)
colour_map = cm.get_cmap("Blues")
threshold_edge_list, edge_weights = get_edges_over_threshold(graph, threshold)
node_colours = louvain_partition_graph(graph)
node_sizes = create_list_of(len(scaled_node_positions),40)#get_centrality_node_sizes(graph,750)
nx.draw(graph, pos=scaled_node_positions, ax=axis, node_size=40, arrows=False, with_labels=False, edge_color=edge_weights,edge_cmap=colour_map, edgelist=threshold_edge_list,node_color = node_colours)
plt.show()
canvas.draw()
canvas.update()
def plot_graph_thresholed_weights_edge_colour_map(figure,canvas,graph,scaled_node_positions,threshold,edge_colour_map):
figure.clear()
axis = figure.add_subplot(111)
colour_map = cm.get_cmap(edge_colour_map)
threshold_edge_list, edge_weights = get_edges_over_threshold(graph, threshold)
node_colours = louvain_partition_graph(graph)
node_sizes = get_centrality_node_sizes(graph,750)
nx.draw(graph, pos=scaled_node_positions, ax=axis, node_size=40, arrows=False, with_labels=False, edge_color=edge_weights,edge_cmap=colour_map, edgelist=threshold_edge_list,node_color = node_colours)
plt.show()
canvas.draw()
canvas.update()
def plot_graph_node_sizes(figure,canvas,graph,edge_weights,node_sizes,scaled_node_positions):
spring_layout = nx.spring_layout(graph)
circle_layout = nx.circular_layout(graph)
kamada_layout = nx.kamada_kawai_layout(graph)
spectral_layout = nx.spectral_layout(graph)
figure.clear()
axis = figure.add_subplot(111)
colour_map = cm.get_cmap("Blues")
node_colours = louvain_partition_graph(graph)
nx.draw(graph,pos=scaled_node_positions, ax=axis, node_size=node_sizes,node_color = node_colours, edge_color=edge_weights, edge_vmin=0, edge_vmax=1, edge_cmap=colour_map, with_labels=False, font_color="white", font_size="10")
canvas.draw()
canvas.update()
def default_plot_graph(figure,canvas,graph,positions=None,node_sizes=40,colour_map="Blues",node_colours="b",edge_weights=None,edge_scaling_factor=1):
figure.clear()
axis = figure.add_subplot(111)
map = cm.get_cmap(colour_map)
if positions == None:
positions = nx.spring_layout(graph)
if edge_weights == None:
edge_weights = get_edge_weights(graph,edge_scaling_factor)
nx.draw(graph,
ax=axis,
pos=positions,
node_size=node_sizes,
node_color=node_colours,
edge_color=edge_weights,
edge_vmin=0,
edge_vmax=1,
edge_cmap=map)
canvas.draw()
canvas.update()
def get_centrality_node_sizes(graph,scaling_factor):
eigenvector_centrailities = nx.algorithms.eigenvector_centrality(graph)
number_of_nodes = len(eigenvector_centrailities)
centraility_list = create_empty_list(number_of_nodes)
for node in range(number_of_nodes):
centraility_list[node] = (eigenvector_centrailities[node] * eigenvector_centrailities[node]) * scaling_factor * 5
#print "centraility list", centraility_list
return centraility_list
def expanded_subnetwork_analysis(graphs, original_subnetwork):
expanded_subnetworks = []
expanded_node_dict = {}
for graph in graphs:
expanded_subnetwork = get_expanded_subnetwork(graph,original_subnetwork)
expanded_subnetworks.append(expanded_subnetwork)
number_of_subnetworks = len(expanded_subnetworks)
for subnetwork in expanded_subnetworks:
for node in subnetwork:
if node in expanded_node_dict:
number_of_appearences = expanded_node_dict[node]
expanded_node_dict[node] = number_of_appearences + 1
else:
expanded_node_dict[node] = 1
for node in expanded_node_dict.keys():
expanded_node_dict[node] = (float(expanded_node_dict[node])/number_of_subnetworks) * 100
return expanded_node_dict
#return expanded_subnetworks
def get_expanded_subnetwork(graph,original_subnetwork):
additional_nodes = []
edge_dict = nx.get_edge_attributes(graph,"weight")
for node in original_subnetwork:
strongest_neighbour = None
strongest_weight = 0
neighbours = list(nx.neighbors(graph,node))
for neighbour in neighbours:
if neighbour in original_subnetwork:
pass
else:
if (node,neighbour) in edge_dict:
edge_weight = edge_dict[(node,neighbour)]
elif (neighbour,node) in edge_dict:
edge_weight = edge_dict[(neighbour,node)]
if edge_weight > strongest_weight:
strongest_weight = edge_weight
strongest_neighbour = neighbour
additional_nodes.append(strongest_neighbour)
additional_nodes = set(additional_nodes)
additional_nodes = list(additional_nodes)
additional_nodes.sort()
return additional_nodes
#print additional_nodes
def convert_matrix_to_binary(matrix):
rows,columns = np.shape(matrix)
new_matrix = create_zero_array(rows)
for row in range(rows):
for column in range(columns):
if matrix[row][column] > 0:
new_matrix[row][column] = 1
return new_matrix
#Rewire Functions
def randomly_rewire(graph,probability):
edges = nx.edges(graph)
number_of_nodes = nx.number_of_nodes(graph)
for edge in edges:
#Rewire with certain probability
if get_boolean_with_probability(probability) == True:
node_1 = edge[0]
node_2 = edge[1]
#Create a list of possible new nodes, avoiding existing connections
existing_neighbours = nx.neighbors(graph,node_1)
list_of_new_potential_neighbours = range(0,number_of_nodes)
for neighbour in existing_neighbours:
list_of_new_potential_neighbours.remove(neighbour)
#Pick the new random node
new_node_index = random.randint(0,(len(list_of_new_potential_neighbours)-1))
new_node = list_of_new_potential_neighbours[new_node_index]
#Remove old connection and add the new one
graph.remove_edge(node_1,node_2)
graph.add_edge(node_1, new_node)
return graph
def create_list_of_integers(size):
new_list = []
for x in range(size):
list.append(x)
return new_list
def get_upper_triangle_part_of_matrix(matrix):
list_of_items = []
number_of_rows, number_of_columns = np.shape(matrix)
for row in range(number_of_rows-1):
for column in range(row+1, number_of_columns):
item = matrix[row][column]
list_of_items.append(item)
return list_of_items
def randomise_graph(graph):
number_of_nodes = nx.number_of_nodes(graph)
random_matrix = create_zero_array(number_of_nodes)
connection_matrix = nx.to_numpy_array(graph)
# Create a list of randomised edges
randomised_edges = get_upper_triangle_part_of_matrix(connection_matrix)
random.shuffle(randomised_edges)
# Go Through Upper Triangular Matrix and Fill in Edges
edge = 0
for row in range(number_of_nodes-1):
for column in range(row+1, number_of_nodes):
random_matrix[row][column] = randomised_edges[edge]
edge += 1
# Turn Matrix into Graph
random_graph = create_graph(random_matrix)
return random_graph
def randomly_rewire_undirected(graph,probability):
number_of_rewirings = 0
number_of_nodes = nx.number_of_nodes(graph)
weight_dict = nx.get_edge_attributes(graph, "weight")
existing_edges = nx.edges(graph)
node_list = nx.nodes(graph)
#Get List Of All Potential Edges (undirected):
all_potential_edges = []
for node_1 in node_list:
for node_2 in node_list:
if node_1 == node_2:
pass
else:
all_potential_edges.append((node_1,node_2))
#Get Pool of Re-wired Edges
potential_pool = all_potential_edges
for edge in existing_edges:
if edge in potential_pool: #Should I have Had to Add This In?
potential_pool.remove(edge)
if (edge[1],edge[0]) in potential_pool:
potential_pool.remove((edge[1],edge[0]))
#Go Through and Poentially Swap Each One
new_graph_edge_dict = {}
for edge in existing_edges:
#If Edge Not Swapped Just Add To The New Edge List
if get_boolean_with_probability(probability) == False or len(potential_pool) == 0:
new_graph_edge_dict[edge] = weight_dict[edge]
else:
number_of_rewirings += 1
#Select an Edge to swap with
new_edge = potential_pool[random.randint(0,len(potential_pool)-1)]
#Add New Edge To New Graph
new_graph_edge_dict[new_edge] = weight_dict[edge]
#Remove New Edge From Potential Pool
potential_pool.remove(new_edge)
#Add Previous Edge To Potential Pool
potential_pool.append(edge)
#Turn New Edge Dict Into New Graph
new_graph = nx.Graph()
for node in node_list:
new_graph.add_node(node)
for edge in new_graph_edge_dict:
new_graph.add_edge(edge[0], edge[1], weight=new_graph_edge_dict[edge])
return new_graph
#Lattice Graph Functions
def create_directed_unweighted_lattice(number_of_nodes):
connection_matrix = create_zero_array(number_of_nodes)
for node_from in range(number_of_nodes):
for neighbour in range(-2,3):
if neighbour == 0:
pass
else:
node_to = node_from + neighbour
if node_to < 0:
node_to = number_of_nodes + node_to
if node_to >= (number_of_nodes):
node_to = node_to - (number_of_nodes + 1)
connection_matrix[node_from][node_to] = 1
np.fill_diagonal(connection_matrix, 0)
graph = create_graph(connection_matrix)
return graph
def create_directed_weighted_lattice(number_of_nodes):
connection_matrix = create_zero_array(number_of_nodes)
spacing = 2 # + 1
start_value = 0 - spacing
end_value = spacing + 1
for node_from in range(number_of_nodes):
for neighbour in range(start_value, end_value):
if neighbour == 0:
pass
else:
node_to = node_from + neighbour
if node_to == node_from:
pass
else:
if node_to < 0:
node_to = (number_of_nodes+node_from) + neighbour
elif node_to >= (number_of_nodes):
node_to = node_to - (number_of_nodes)
maximum_distance = (float(number_of_nodes) / 2) + 1
current_distance = abs(neighbour)
weight = maximum_distance - current_distance
connection_matrix[node_from][node_to] = weight
np.fill_diagonal(connection_matrix, 0)
graph = create_weighted_graph(connection_matrix)
return graph
def create_undirected_weighted_lattice(number_of_nodes):
connection_matrix = create_zero_array(number_of_nodes)
spacing = 2 # + 1
start_value = 0 - spacing
end_value = spacing + 1
for node_from in range(number_of_nodes):
for neighbour in range(start_value, end_value):
if neighbour == 0:
pass
else:
node_to = node_from + neighbour
if node_to == node_from:
pass
else:
if node_to < 0:
node_to = (number_of_nodes+node_from) + neighbour
elif node_to >= (number_of_nodes):
node_to = node_to - (number_of_nodes)
maximum_distance = (float(number_of_nodes) / 2) + 1
current_distance = abs(neighbour)
weight = maximum_distance - current_distance
if connection_matrix[node_to][node_from] == 0:
connection_matrix[node_from][node_to] = weight
np.fill_diagonal(connection_matrix, 0)
graph = create_weighted_graph(connection_matrix)
return graph
def create_directed_equivalent_lattice(graph):
connection_matrix = nx.to_numpy_array(graph)
number_of_nodes, number_of_nodes_2 = np.shape(connection_matrix)
edge_weights = get_edge_weights(graph, 1)
weight_groups = split_list_into_chunks_of_the_same_thing(edge_weights)
lattice_matrix = create_zero_array(number_of_nodes)
distance_index = 1
points_to_fill = get_matrix_positions_at_distance(lattice_matrix, distance_index)
for group in weight_groups:
for weight in group:
# Fill that point and remove it from pool
point_index = random.randint(0, len(points_to_fill) - 1)
point_to_fill = points_to_fill[point_index]
lattice_matrix[point_to_fill[0]][point_to_fill[1]] = weight
# Remove the reverse point to make sure it dosent take a different weight
points_to_fill.remove(point_to_fill)
# If the list is empty, get the next distance
if len(points_to_fill) == 0:
distance_index += 1
new_potential_points = get_matrix_positions_at_distance(lattice_matrix, distance_index)
# Check They are all empty and their reverse are not filled
for new_potential_point in new_potential_points:
if lattice_matrix[new_potential_point[0]][new_potential_point[1]] == 0:
points_to_fill.append(new_potential_point)
lattice_matrix = np.array(lattice_matrix)
lattice_graph = create_weighted_graph(lattice_matrix)
return lattice_graph
def create_undirected_equivalent_lattice(graph):
#graph = nx.to_undirected(graph)
connection_matrix = nx.to_numpy_array(graph)
number_of_nodes, number_of_nodes_2 = np.shape(connection_matrix)
edge_weights = get_edge_weights(graph, 1)
weight_groups = split_list_into_chunks_of_the_same_thing(edge_weights)
lattice_matrix = create_zero_array(number_of_nodes)
distance_index = 1
points_to_fill = get_undirected_matrix_positions_at_distance(lattice_matrix, distance_index)
for group in weight_groups:
for weight in group:
# Fill that point and remove it from pool
point_index = random.randint(0, len(points_to_fill) - 1)
point_to_fill = points_to_fill[point_index]
lattice_matrix[point_to_fill[0]][point_to_fill[1]] = weight
# Remove the reverse point to make sure it dosent take a different weight
points_to_fill.remove(point_to_fill)
# If the list is empty, get the next distance
if len(points_to_fill) == 0:
distance_index += 1
new_potential_points = get_undirected_matrix_positions_at_distance(lattice_matrix, distance_index)
# Check They are all empty and their reverse are not filled
for new_potential_point in new_potential_points:
if lattice_matrix[new_potential_point[0]][new_potential_point[1]] == 0:
points_to_fill.append(new_potential_point)
lattice_matrix = np.array(lattice_matrix)
lattice_graph = create_weighted_graph(lattice_matrix)
return lattice_graph
#Get Matrix Positions
def get_matrix_positions_at_distance(matrix,distance):
matrix_height,matrix_width = np.shape(matrix)
list_of_positions = []
for row in range(matrix_height):
node_in_front = row + distance
node_behind = row - distance
if node_in_front >= (matrix_width):
node_in_front = node_in_front - (matrix_width)
if node_behind < 0:
node_behind = matrix_width + node_behind
if node_in_front == node_behind:
list_of_positions.append([row,node_in_front])
else:
list_of_positions.append((row, int(node_behind)))
list_of_positions.append((row, int(node_in_front)))
return list_of_positions
def get_undirected_matrix_positions_at_distance(matrix,distance):
matrix_height,matrix_width = np.shape(matrix)
list_of_positions = []
for row in range(matrix_height):
node_in_front = row + distance
node_behind = row - distance
if node_in_front >= (matrix_width):
node_in_front = node_in_front - (matrix_width)
if node_behind < 0:
node_behind = matrix_width + node_behind
if node_in_front == node_behind:
list_of_positions.append([row,node_in_front])
else:
list_of_positions.append((row, int(node_behind)))
list_of_positions.append((row, int(node_in_front)))
for position in list_of_positions:
reverse_position = (position[1],position[0])
if reverse_position in list_of_positions:
list_of_positions.remove((reverse_position))
return list_of_positions
def get_edges_over_threshold(graph,threshold):
edge_list = []
weight_list = []
edges = nx.get_edge_attributes(graph,"weight")
for edge in edges:
if edges[edge] >= threshold:
edge_list.append(edge)
weight_list.append(edges[edge])
return edge_list, weight_list
def invert_weights(graph):
connection_matrix = nx.to_numpy_array(graph)
#connection_matrix = symmetrical_to_upper_triangle(connection_matrix)
number_of_nodes = nx.number_of_nodes(graph)
for row in range(number_of_nodes):
for column in range(number_of_nodes):
value = connection_matrix[row][column]
if value == 0:
pass
else:
value = float(1/value)
connection_matrix[row][column] = value
graph = create_graph(connection_matrix)
return graph
def invert_weights_and_scale(graph):
connection_matrix = nx.to_numpy_array(graph)
connection_matrix = symmetrical_to_upper_triangle(connection_matrix)
number_of_nodes = nx.number_of_nodes(graph)
for row in range(number_of_nodes):
for column in range(number_of_nodes):
value = connection_matrix[row][column]
if value == 0:
pass
else:
value = float(1) / float(value)
connection_matrix[row][column] = value
graph = create_graph(connection_matrix)
return graph
#Graph Analysis Functions
def get_small_world_propensity(graph):
equivalent_lattice = create_undirected_equivalent_lattice(graph)
equivalent_random = randomise_graph(graph)
observed_clustering = nx.average_clustering(graph,weight="weight")
lattice_clustering = nx.average_clustering(equivalent_lattice,weight="weight")
random_clustering = nx.average_clustering(equivalent_random,weight="weight")
#plot_graph_basic_weights(graph)
#plot_graph_basic_weights(equivalent_lattice)
#plot_graph_basic_weights(equivalent_random)
observed_length = get_average_shortest_path_length(graph)
lattice_length = get_average_shortest_path_length(equivalent_lattice)
random_length = get_average_shortest_path_length(equivalent_random)
try:
delta_c = (lattice_clustering - observed_clustering) / (lattice_clustering - random_clustering)
delta_l = (observed_length - random_length) / (lattice_length - random_length)
small_world_propensity = math.sqrt(((delta_c*delta_c) + (delta_l*delta_l)) / 2)
except:
small_world_propensity = 0
"""
print "observed_clustering" , observed_clustering