-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculate_gates_bell_pairs_main.py
More file actions
1675 lines (1402 loc) · 62 KB
/
calculate_gates_bell_pairs_main.py
File metadata and controls
1675 lines (1402 loc) · 62 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 25 11:02:32 2024
@author: siddhu
"""
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import random
from collections import defaultdict, deque
from networkx.drawing.layout import circular_layout
from itertools import combinations, groupby
import math
import csv
import concurrent.futures
import time
from multiprocessing import Pool, cpu_count
from joblib import Parallel, delayed
import pickle
def gnp_random_connected_graph(n, p):
"""
Generates a random undirected graph, similarly to an Erdős-Rényi
graph, but enforcing that the resulting graph is connected
"""
edges = combinations(range(n), 2)
G = nx.Graph()
G.add_nodes_from(range(n))
if p <= 0:
return G
if p >= 1:
return nx.complete_graph(n, create_using=G)
for _, node_edges in groupby(edges, key=lambda x: x[0]):
node_edges = list(node_edges)
random_edge = random.choice(node_edges)
G.add_edge(*random_edge)
for e in node_edges:
if random.random() < p:
G.add_edge(*e)
# print(G.edges())
return G
def BA(n, c, alt=False):
"""
Generates a random sample from the Barabasi-Albert ensemble,
starting from the complete graph of c+1 nodes, such that
the total number of nodes in the graph is n=c+1+x, with
x=0,1,2,...
Note that n should be greater than or equal to c+1.
"""
if alt:
### Here, the starting graph is the star graph of c+1 nodes
return nx.barabasi_albert_graph(n, c)
else:
return nx.barabasi_albert_graph(n, c, initial_graph=nx.complete_graph(c + 1))
def generate_data_BA(num_samples=500, display=True, save_to_file=True):
# N=np.linspace(50,500,10,dtype=int)
# N=np.linspace(50,200,1,dtype=int)
N = [100, 200, 300]
P = np.arange(0.01, 0.98, 0.02)
F = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
print(
"Generating data for BA networks with number of nodes N =",
N,
"and fractions P =",
P,
)
print("\nThe number of samples is", num_samples)
C = {} ### size of the largest connected component
R = {} ### density of the full graph
R0 = {} ### density of the largest connected component
K = {} ### max degree of the full graph
K0 = {} ### max degree of the largest connected component
Cl = {} ### average clustering coefficient of the full graph
Cl0 = {} ### average clustering coefficient of the largest connected component
deg = {} ### average degree of the full graph
deg0 = {} ### average degree of the largest connected component
gates_SS = {}
stars_SS = {}
gates_MMG = {}
gates_MMGupd = {}
for n in N:
for f in F:
for p in P:
C[n, f, p] = []
R[n, f, p] = []
R0[n, f, p] = []
K[n, f, p] = []
K0[n, f, p] = []
Cl[n, f, p] = []
Cl0[n, f, p] = []
deg[n, f, p] = []
deg0[n, f, p] = []
gates_SS[n, f, p] = []
stars_SS[n, f, p] = []
gates_MMG[n, f, p] = []
gates_MMGupd[n, f, p] = []
def take_sample(n, p): ### When in the complete case (f=1)
# print(0)
c = int(n * p)
if c == 0:
c = 1
G = BA(n, c)
# S = sorted(nx.connected_components(G), key=len, reverse=True)
# G0 = G.subgraph(S[0]) ### The largest connected component
steiner_G0 = generate_steiner_subgraph(G, list(G.nodes()))
# print('done generating graphs')
data = {}
data["size"] = len(G.nodes())
data["density"] = nx.density(G)
# data['density of largest component']=nx.density(G0)
data["highest degree"] = max(degree_distribution(G).values())
# data['highest degree of largest component']=max(degree_distribution(G0).values())
data["average degree"] = average_degree(G)
# data['average degree of largest component']=average_degree(G0)
data["average clustering coefficient"] = nx.average_clustering(G)
# data['average clustering coefficient of largest component']=nx.average_clustering(G0)
ss_output = calculate_gate_ss(G)
data["gates SS"] = ss_output[0] / n
data["number of stars"] = len(ss_output[1])
# print('done ss')
data["gates MMG"] = calculate_gate_steiner(G, list(G.nodes())) / n
# print('done MMG')
data["gates MMG upd"] = calculate_gate_ss(steiner_G0)[0] / n
# print('done MMG upd')
return data
def take_sample_subset(n, f, p):
# print(0)
c = int(n * p)
if c == 0:
c = 1
G = BA(n, c)
m = int(np.ceil(n * f))
S = generate_selected_nodes(G, m)
G0 = generate_connected_subgraph_sid(G, S)
steiner_G0 = generate_steiner_subgraph(G, S)
data = {}
data["size"] = len(G0.nodes())
data["density"] = nx.density(G)
data["density of subset"] = nx.density(G0)
data["highest degree"] = max(degree_distribution(G).values())
data["highest degree of subset"] = max(degree_distribution(G0).values())
data["average degree"] = average_degree(G)
data["average degree of subset"] = average_degree(G0)
data["average clustering coefficient"] = nx.average_clustering(G)
data["average clustering coefficient of subset"] = nx.average_clustering(G0)
ss_output = calculate_gate_ss(G0)
data["gates SS"] = ss_output[0] / m
data["number of stars"] = len(ss_output[1])
# print('done ss')
data["gates MMG"] = calculate_gate_steiner(G0, list(G0.nodes())) / m
# print('done MMG')
data["gates MMG upd"] = calculate_gate_ss(steiner_G0)[0] / m
# print('done MMG upd')
return data
output = {}
for n in N:
for p in P:
for f in F:
if display:
print(n, f, p)
if f == 1:
output[n, f, p] = Parallel(n_jobs=8)(
delayed(take_sample)(n, p) for i in range(num_samples)
)
# output[n,d] = [take_sample(n,d) for i in range(num_samples)]
C[n, f, p].append(
np.mean([data["size"] for data in output[n, f, p]])
)
R[n, f, p].append(
np.mean([data["density"] for data in output[n, f, p]])
)
# R0[n,f].append(np.mean([data['density of subset'] for data in output[n,f,p]]))
K[n, f, p].append(
np.mean([data["highest degree"] for data in output[n, f, p]])
)
# K0[n,f].append(np.mean([data['highest degree of subset'] for data in output[n,f,p]]))
Cl[n, f, p].append(
np.mean(
[
data["average clustering coefficient"]
for data in output[n, f, p]
]
)
)
# Cl0[n,f].append(np.mean([data['average clustering coefficient of subset'] for data in output[n,f,p]]))
deg[n, f, p].append(
np.mean([data["average degree"] for data in output[n, f, p]])
)
# deg0[n,f].append(np.mean([data['average degree of subset'] for data in output[n,f,p]]))
gates_SS[n, f, p].append(
np.mean([data["gates SS"] for data in output[n, f, p]])
)
stars_SS[n, f, p].append(
np.mean([data["number of stars"] for data in output[n, f, p]])
)
gates_MMG[n, f, p].append(
np.mean([data["gates MMG"] for data in output[n, f, p]])
)
gates_MMGupd[n, f, p].append(
np.mean([data["gates MMG upd"] for data in output[n, f, p]])
)
else:
output[n, f, p] = Parallel(n_jobs=8)(
delayed(take_sample_subset)(n, f, p) for i in range(num_samples)
)
# output[n,d] = [take_sample(n,d) for i in range(num_samples)]
C[n, f, p].append(
np.mean([data["size"] for data in output[n, f, p]])
)
R[n, f, p].append(
np.mean([data["density"] for data in output[n, f, p]])
)
R0[n, f, p].append(
np.mean([data["density of subset"] for data in output[n, f, p]])
)
K[n, f, p].append(
np.mean([data["highest degree"] for data in output[n, f, p]])
)
K0[n, f, p].append(
np.mean(
[
data["highest degree of subset"]
for data in output[n, f, p]
]
)
)
Cl[n, f, p].append(
np.mean(
[
data["average clustering coefficient"]
for data in output[n, f, p]
]
)
)
Cl0[n, f, p].append(
np.mean(
[
data["average clustering coefficient of subset"]
for data in output[n, f, p]
]
)
)
deg[n, f, p].append(
np.mean([data["average degree"] for data in output[n, f, p]])
)
deg0[n, f, p].append(
np.mean(
[
data["average degree of subset"]
for data in output[n, f, p]
]
)
)
gates_SS[n, f, p].append(
np.mean([data["gates SS"] for data in output[n, f, p]])
)
stars_SS[n, f, p].append(
np.mean([data["number of stars"] for data in output[n, f, p]])
)
gates_MMG[n, f, p].append(
np.mean([data["gates MMG"] for data in output[n, f, p]])
)
gates_MMGupd[n, f, p].append(
np.mean([data["gates MMG upd"] for data in output[n, f, p]])
)
output_avg = {}
for n in N:
for f in F:
for p in P:
output_avg[n, f, p] = {}
output_avg[n, f, p]["size"] = np.array(C[n, f, p])
output_avg[n, f, p]["density"] = np.array(R[n, f, p])
output_avg[n, f, p]["density of subset"] = np.array(R0[n, f, p])
output_avg[n, f, p]["highest degree"] = np.array(K[n, f, p])
output_avg[n, f, p]["highest degree of subset"] = np.array(K0[n, f, p])
output_avg[n, f, p]["average clustering coefficient"] = np.array(
Cl[n, f, p]
)
output_avg[n, f, p]["average clustering coefficient of subset"] = (
np.array(Cl0[n, f, p])
)
output_avg[n, f, p]["average degree"] = np.array(deg[n, f, p])
output_avg[n, f, p]["average degree of subset"] = np.array(
deg0[n, f, p]
)
output_avg[n, f, p]["gates SS"] = np.array(gates_SS[n, f, p])
output_avg[n, f, p]["number of stars"] = np.array(stars_SS[n, f, p])
output_avg[n, f, p]["gates MMG"] = np.array(gates_MMG[n, f, p])
output_avg[n, f, p]["gates MMG upd"] = np.array(gates_MMGupd[n, f, p])
if save_to_file:
timestr = time.strftime("%Y%m%d-%H%M%S")
filename = "data_BA_" + timestr + ".pkl"
with open(filename, "wb") as f:
pickle.dump([N, F, P, num_samples, output_avg, output], f)
return N, F, P, num_samples, output_avg, output
else:
return N, F, P, num_samples, output_avg, output
def generate_data_ER(num_samples=500, display=True, save_to_file=True):
# N=np.linspace(50,500,10,dtype=int)
# N=np.linspace(50,200,1,dtype=int)
N = [100, 200, 300]
P = np.arange(0.01, 0.98, 0.02)
F = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
print(
"Generating data for ER networks with number of nodes N =",
N,
"and probabilities P =",
P,
)
print("\nThe number of samples is", num_samples)
C = {} ### size of the largest connected component
R = {} ### density of the full graph
R0 = {} ### density of the largest connected component
K = {} ### max degree of the full graph
K0 = {} ### max degree of the largest connected component
Cl = {} ### average clustering coefficient of the full graph
Cl0 = {} ### average clustering coefficient of the largest connected component
deg = {} ### average degree of the full graph
deg0 = {} ### average degree of the largest connected component
gates_SS = {}
stars_SS = {}
gates_MMG = {}
gates_MMGupd = {}
for n in N:
for f in F:
for p in P:
C[n, f, p] = []
R[n, f, p] = []
R0[n, f, p] = []
K[n, f, p] = []
K0[n, f, p] = []
Cl[n, f, p] = []
Cl0[n, f, p] = []
deg[n, f, p] = []
deg0[n, f, p] = []
gates_SS[n, f, p] = []
stars_SS[n, f, p] = []
gates_MMG[n, f, p] = []
gates_MMGupd[n, f, p] = []
def take_sample(n, p): ### When in the complete case (f=1)
# print(0)
G = gnp_random_connected_graph(n, p)
# S = sorted(nx.connected_components(G), key=len, reverse=True)
# G0 = G.subgraph(S[0]) ### The largest connected component
steiner_G0 = generate_steiner_subgraph(G, list(G.nodes()))
# print('done generating graphs')
data = {}
data["size"] = len(G.nodes())
data["density"] = nx.density(G)
# data['density of largest component']=nx.density(G0)
data["highest degree"] = max(degree_distribution(G).values())
# data['highest degree of largest component']=max(degree_distribution(G0).values())
data["average degree"] = average_degree(G)
# data['average degree of largest component']=average_degree(G0)
data["average clustering coefficient"] = nx.average_clustering(G)
# data['average clustering coefficient of largest component']=nx.average_clustering(G0)
ss_output = calculate_gate_ss(G)
data["gates SS"] = ss_output[0] / n
data["number of stars"] = len(ss_output[1])
# print('done ss')
data["gates MMG"] = calculate_gate_steiner(G, list(G.nodes())) / n
# print('done MMG')
data["gates MMG upd"] = calculate_gate_ss(steiner_G0)[0] / n
# print('done MMG upd')
return data
def take_sample_subset(n, f, p):
# print(0)
G = gnp_random_connected_graph(n, p)
m = int(np.ceil(n * f))
S = generate_selected_nodes(G, m)
G0 = generate_connected_subgraph_sid(G, S)
steiner_G0 = generate_steiner_subgraph(G, S)
data = {}
data["size"] = len(G0.nodes())
data["density"] = nx.density(G)
data["density of subset"] = nx.density(G0)
data["highest degree"] = max(degree_distribution(G).values())
data["highest degree of subset"] = max(degree_distribution(G0).values())
data["average degree"] = average_degree(G)
data["average degree of subset"] = average_degree(G0)
data["average clustering coefficient"] = nx.average_clustering(G)
data["average clustering coefficient of subset"] = nx.average_clustering(G0)
ss_output = calculate_gate_ss(G0)
data["gates SS"] = ss_output[0] / m
data["number of stars"] = len(ss_output[1])
# print('done ss')
data["gates MMG"] = calculate_gate_steiner(G0, list(G0.nodes())) / m
# print('done MMG')
data["gates MMG upd"] = calculate_gate_ss(steiner_G0)[0] / m
# print('done MMG upd')
return data
output = {}
for n in N:
for p in P:
for f in F:
if display:
print(n, f, p)
if f == 1:
output[n, f, p] = Parallel(n_jobs=8)(
delayed(take_sample)(n, p) for i in range(num_samples)
)
# output[n,d] = [take_sample(n,d) for i in range(num_samples)]
C[n, f, p].append(
np.mean([data["size"] for data in output[n, f, p]])
)
R[n, f, p].append(
np.mean([data["density"] for data in output[n, f, p]])
)
# R0[n,f].append(np.mean([data['density of subset'] for data in output[n,f,p]]))
K[n, f, p].append(
np.mean([data["highest degree"] for data in output[n, f, p]])
)
# K0[n,f].append(np.mean([data['highest degree of subset'] for data in output[n,f,p]]))
Cl[n, f, p].append(
np.mean(
[
data["average clustering coefficient"]
for data in output[n, f, p]
]
)
)
# Cl0[n,f].append(np.mean([data['average clustering coefficient of subset'] for data in output[n,f,p]]))
deg[n, f, p].append(
np.mean([data["average degree"] for data in output[n, f, p]])
)
# deg0[n,f].append(np.mean([data['average degree of subset'] for data in output[n,f,p]]))
gates_SS[n, f, p].append(
np.mean([data["gates SS"] for data in output[n, f, p]])
)
stars_SS[n, f, p].append(
np.mean([data["number of stars"] for data in output[n, f, p]])
)
gates_MMG[n, f, p].append(
np.mean([data["gates MMG"] for data in output[n, f, p]])
)
gates_MMGupd[n, f, p].append(
np.mean([data["gates MMG upd"] for data in output[n, f, p]])
)
else:
output[n, f, p] = Parallel(n_jobs=8)(
delayed(take_sample_subset)(n, f, p) for i in range(num_samples)
)
# output[n,d] = [take_sample(n,d) for i in range(num_samples)]
C[n, f, p].append(
np.mean([data["size"] for data in output[n, f, p]])
)
R[n, f, p].append(
np.mean([data["density"] for data in output[n, f, p]])
)
R0[n, f, p].append(
np.mean([data["density of subset"] for data in output[n, f, p]])
)
K[n, f, p].append(
np.mean([data["highest degree"] for data in output[n, f, p]])
)
K0[n, f, p].append(
np.mean(
[
data["highest degree of subset"]
for data in output[n, f, p]
]
)
)
Cl[n, f, p].append(
np.mean(
[
data["average clustering coefficient"]
for data in output[n, f, p]
]
)
)
Cl0[n, f, p].append(
np.mean(
[
data["average clustering coefficient of subset"]
for data in output[n, f, p]
]
)
)
deg[n, f, p].append(
np.mean([data["average degree"] for data in output[n, f, p]])
)
deg0[n, f, p].append(
np.mean(
[
data["average degree of subset"]
for data in output[n, f, p]
]
)
)
gates_SS[n, f, p].append(
np.mean([data["gates SS"] for data in output[n, f, p]])
)
stars_SS[n, f, p].append(
np.mean([data["number of stars"] for data in output[n, f, p]])
)
gates_MMG[n, f, p].append(
np.mean([data["gates MMG"] for data in output[n, f, p]])
)
gates_MMGupd[n, f, p].append(
np.mean([data["gates MMG upd"] for data in output[n, f, p]])
)
output_avg = {}
for n in N:
for f in F:
for p in P:
output_avg[n, f, p] = {}
output_avg[n, f, p]["size"] = np.array(C[n, f, p])
output_avg[n, f, p]["density"] = np.array(R[n, f, p])
output_avg[n, f, p]["density of subset"] = np.array(R0[n, f, p])
output_avg[n, f, p]["highest degree"] = np.array(K[n, f, p])
output_avg[n, f, p]["highest degree of subset"] = np.array(K0[n, f, p])
output_avg[n, f, p]["average clustering coefficient"] = np.array(
Cl[n, f, p]
)
output_avg[n, f, p]["average clustering coefficient of subset"] = (
np.array(Cl0[n, f, p])
)
output_avg[n, f, p]["average degree"] = np.array(deg[n, f, p])
output_avg[n, f, p]["average degree of subset"] = np.array(
deg0[n, f, p]
)
output_avg[n, f, p]["gates SS"] = np.array(gates_SS[n, f, p])
output_avg[n, f, p]["number of stars"] = np.array(stars_SS[n, f, p])
output_avg[n, f, p]["gates MMG"] = np.array(gates_MMG[n, f, p])
output_avg[n, f, p]["gates MMG upd"] = np.array(gates_MMGupd[n, f, p])
if save_to_file:
timestr = time.strftime("%Y%m%d-%H%M%S")
filename = "data_ER_" + timestr + ".pkl"
with open(filename, "wb") as f:
pickle.dump([N, F, P, num_samples, output_avg, output], f)
return N, F, P, num_samples, output_avg, output
else:
return N, F, P, num_samples, output_avg, output
def generate_data_photonic(
num_samples=500, circle=True, display=True, save_to_file=True
):
# N=np.linspace(50,500,10,dtype=int)
# N=np.linspace(50,200,1,dtype=int)
N = [100, 200, 300, 400, 500]
D = np.linspace(50, 1000, 20) ### maximum distances
# D=[800]
print(
"Generating data for photonic networks with number of nodes N =",
N,
"and distances D =",
D,
)
print("\nThe number of samples is", num_samples)
C = {} ### size of the largest connected component
R = {} ### density of the full graph
R0 = {} ### density of the largest connected component
K = {} ### max degree of the full graph
K0 = {} ### max degree of the largest connected component
Cl = {} ### average clustering coefficient of the full graph
Cl0 = {} ### average clustering coefficient of the largest connected component
deg = {} ### average degree of the full graph
deg0 = {} ### average degree of the largest connected component
gates_SS = {}
gates_SS_normalized = {}
stars_SS = {}
gates_MMG = {}
gates_MMG_normalized = {}
gates_MMGupd = {}
gates_MMGupd_normalized = {}
for n in N:
for d in D:
C[n, d] = []
R[n, d] = []
R0[n, d] = []
K[n, d] = []
K0[n, d] = []
Cl[n, d] = []
Cl0[n, d] = []
deg[n, d] = []
deg0[n, d] = []
gates_SS[n, d] = []
gates_SS_normalized[n, d] = []
stars_SS[n, d] = []
gates_MMG[n, d] = []
gates_MMG_normalized[n, d] = []
gates_MMGupd[n, d] = []
gates_MMGupd_normalized[n, d] = []
def take_sample(n, d):
# print(0)
if circle:
G = generate_random_geometric_graph_circle(n, d)
else:
G = generate_random_geometric_graph(n, d)
S = sorted(nx.connected_components(G), key=len, reverse=True)
G0 = G.subgraph(S[0]) ### The largest connected component
steiner_G0 = generate_steiner_subgraph(G0, list(G0.nodes()))
# print('done generating graphs')
data = {}
data["size"] = len(G0.nodes())
data["density"] = nx.density(G)
data["density of largest component"] = nx.density(G0)
data["highest degree"] = max(degree_distribution(G).values())
data["highest degree of largest component"] = max(
degree_distribution(G0).values()
)
data["average degree"] = average_degree(G)
data["average degree of largest component"] = average_degree(G0)
data["average clustering coefficient"] = nx.average_clustering(G)
data["average clustering coefficient of largest component"] = (
nx.average_clustering(G0)
)
output_SS = calculate_gate_ss(G0)
data["gates SS"] = (output_SS[0], output_SS[0] / len(G0.nodes()))
data["number of stars"] = len(output_SS[1])
# print('done ss')
output_steiner = calculate_gate_steiner(G0, list(G0.nodes()))
data["gates MMG"] = (output_steiner, output_steiner / len(G0.nodes()))
# print('done MMG')
output_SS_steiner = calculate_gate_ss(steiner_G0)[0]
data["gates MMG upd"] = (
output_SS_steiner,
output_SS_steiner / len(steiner_G0.nodes()),
)
# print('done MMG upd')
return data
output = {}
for n in N:
for d in D:
if display:
print(n, d)
output[n, d] = Parallel(n_jobs=8)(
delayed(take_sample)(n, d) for i in range(num_samples)
)
# output[n,d] = [take_sample(n,d) for i in range(num_samples)]
C[n, d].append(np.mean([data["size"] for data in output[n, d]]))
R[n, d].append(np.mean([data["density"] for data in output[n, d]]))
R0[n, d].append(
np.mean([data["density of largest component"] for data in output[n, d]])
)
K[n, d].append(np.mean([data["highest degree"] for data in output[n, d]]))
K0[n, d].append(
np.mean(
[
data["highest degree of largest component"]
for data in output[n, d]
]
)
)
Cl[n, d].append(
np.mean(
[data["average clustering coefficient"] for data in output[n, d]]
)
)
Cl0[n, d].append(
np.mean(
[
data["average clustering coefficient of largest component"]
for data in output[n, d]
]
)
)
deg[n, d].append(np.mean([data["average degree"] for data in output[n, d]]))
deg0[n, d].append(
np.mean(
[
data["average degree of largest component"]
for data in output[n, d]
]
)
)
gates_SS[n, d].append(
np.mean([data["gates SS"][0] for data in output[n, d]])
)
gates_SS_normalized[n, d].append(
np.mean([data["gates SS"][1] for data in output[n, d]])
)
stars_SS[n, d].append(
np.mean([data["number of stars"] for data in output[n, d]])
)
gates_MMG[n, d].append(
np.mean([data["gates MMG"][0] for data in output[n, d]])
)
gates_MMG_normalized[n, d].append(
np.mean([data["gates MMG"][1] for data in output[n, d]])
)
gates_MMGupd[n, d].append(
np.mean([data["gates MMG upd"][0] for data in output[n, d]])
)
gates_MMGupd_normalized[n, d].append(
np.mean([data["gates MMG upd"][1] for data in output[n, d]])
)
output_avg = {}
for n in N:
output_avg[n, d] = {}
output_avg[n, d]["size"] = np.array(C[n, d])
output_avg[n, d]["density"] = np.array(R[n, d])
output_avg[n, d]["density of largest component"] = np.array(R0[n, d])
output_avg[n, d]["highest degree"] = np.array(K[n, d])
output_avg[n, d]["highest degree of largest component"] = np.array(K0[n, d])
output_avg[n, d]["average clustering coefficient"] = np.array(Cl[n, d])
output_avg[n, d]["average clustering coefficient of largest component"] = (
np.array(Cl0[n, d])
)
output_avg[n, d]["average degree"] = np.array(deg[n, d])
output_avg[n, d]["average degree of largest component"] = np.array(deg0[n, d])
output_avg[n, d]["gates SS"] = np.array(gates_SS[n, d])
output_avg[n, d]["gates SS normalized"] = np.array(gates_SS_normalized[n, d])
output_avg[n, d]["number of stars"] = np.array(stars_SS[n, d])
output_avg[n, d]["gates MMG"] = np.array(gates_MMG[n, d])
output_avg[n, d]["gates MMG normalized"] = np.array(gates_MMG_normalized[n, d])
output_avg[n, d]["gates MMG upd"] = np.array(gates_MMGupd[n, d])
output_avg[n, d]["gates MMG upd normalized"] = np.array(
gates_MMGupd_normalized[n, d]
)
if save_to_file:
timestr = time.strftime("%Y%m%d-%H%M%S")
filename = "data_photonic_" + timestr + ".pkl"
with open(filename, "wb") as f:
pickle.dump([N, D, num_samples, output_avg, output], f)
return N, D, num_samples, output_avg, output
else:
return N, D, num_samples, output_avg, output
def draw_graph(graph, color="orange", layout="circular"):
"""
Draw the given graph using NetworkX and Matplotlib.
"""
if layout == "circular":
pos = circular_layout(graph)
else:
pos = nx.spring_layout(
graph
) # Default to spring layout if layout is not circular
plt.figure(figsize=(5, 5))
nx.draw(
graph,
pos,
with_labels=True,
node_color=color,
node_size=300,
font_size=10,
font_color="black",
font_weight="bold",
)
# plt.title("Graph Visualization")
plt.show()
def pick_stars_ss(G):
MG = {}
SG = {}
tn = set() # to track all nodes used so far
MG[0] = G.copy()
all_nodes = set(MG[0].nodes())
# Step 1: Create a sorted list of nodes by degree (descending)
degree_table = sorted(MG[0].degree(), key=lambda x: x[1], reverse=True)
# print("Degree Table (sorted):", degree_table)
# Step 2: Iterate through the sorted list to build stars
for l, (center_node, _) in enumerate(degree_table):
# if center_node in tn:
# continue # skip if already covered
neighbors = list(MG[0].neighbors(center_node))
# Build strict star: only center connected to each neighbor
SG[l] = nx.Graph()
SG[l].add_node(center_node)
for neighbor in neighbors:
SG[l].add_edge(center_node, neighbor)
# Update covered nodes
tn.update([center_node] + neighbors)
# Stop if all nodes are covered
if tn >= all_nodes:
break
return SG
def connected_stars(G): #:, SG):
"""
CSG means Connected Sub Graphs.
SGcp = copy of SG, Sub Graphs (those sub graphs are stars picked in above function pick_stars_ss)
"""
SG = pick_stars_ss(G)
if len(SG) == 1:
CSG_list = list(SG.values())
# print("I am here to exit abce")
else:
CSG = {}
# Make a copy of SG
SGcp = SG.copy()
# Counter for sequential indices in CSG
csg_index = 0
# Create a list of keys to iterate over
keys_to_delete = []
# Iterate through each subgraph in SGcp
for sg_key, sg in SGcp.items():
"""
This for loop is just to push two stars which share a common node(s) from SGCP into CSG. If no two such two stars are found then extra edge between those disjoint stars is also added to CSG along witht the corresponding two stars. Once added to CSG, those exact stars from SGcp are deleted. So CSG will have stars that are defintely connected.
"""
# Initialize common_found flag for current subgraph
common_found = False
# Iterate through all remaining subgraphs to find common nodes
for i, other_sg in SGcp.items():
if sg_key == i:
continue # Skip comparing the same subgraph with itself
common_nodes = set(sg.nodes()).intersection(set(other_sg.nodes()))
if common_nodes:
# print(f"Common nodes found between sg[{sg_key}] and sg[{i}]: {common_nodes}")
common_found = True
# Append both subgraphs to CSG
CSG[csg_index] = sg
csg_index += 1
CSG[csg_index] = other_sg
csg_index += 1
# Mark keys for deletion
keys_to_delete.extend([sg_key, i])
# Break out of the loop since common nodes are found
break
if common_found:
break # Stop iterating over other subgraphs if common nodes are found
if not common_found:
# print(f"No common nodes found for sg[{sg_key}], so going to find an edge.")
# Check for an edge between SGcp[0] and other subgraphs
for i, other_sg in SGcp.items():
if i == 0:
continue # Skip comparing with SGcp[0]
# Check for an edge between SGcp[0] and other_sg
for u, v in G.edges:
if (u in sg.nodes and v in other_sg.nodes) or (
v in sg.nodes and u in other_sg.nodes
):
# print(f"Edge found between sg[0] and sg[{i}]: ({u}, {v})")
# Add the edge as a graph to CSG
edge_graph = nx.Graph()
edge_graph.add_edge(u, v)
CSG[csg_index] = edge_graph
csg_index += 1
# Add SGcp[0] and other_sg to CSG
CSG[csg_index] = sg
csg_index += 1
CSG[csg_index] = other_sg
csg_index += 1
# Mark keys for deletion
keys_to_delete.extend([0, i])
common_found = True
break # Stop searching for edges once a match is found
if common_found:
break # Stop searching for edges if a match is found
if common_found:
break # Stop iterating over subgraphs if an edge is found
# Delete marked keys from SGcp
for key in keys_to_delete:
del SGcp[key]
SGcp_list = list(
SGcp.values()
) # There is some prob to continue with dicts so converted to list.
CSG_list = list(
CSG.values()
) # There is some prob to continue with dicts so converted to list.
# print("I am out of first loop")
# for i, graph in enumerate(CSG_list):
# draw_graph(graph, 'lightblue', layout='circular')
"""
Now we have at least two stars in CSG. Those are deleted from SGcp. Now we do two more loops called part 1 and part 2 to push the rest of the SGcp stars to the connected stars list CSG.
The code below is of two parts. part 1 is to check if there is a common node between any graphs SGcp and CSG, if yes those are pushed from SGcp to CSG.
The part 2 is when all graphs are disjoint. Then it finds a common edge between any SGcp and CSG graph and adds that to SGcp.
Part 1 and 2 are excuted untill the SGcp list is empty.
"""
execute_part_1 = True
while SGcp_list:
# print("Entering while loop")
# print("Length of SGcp_list:", len(SGcp_list))
# print("Length of CSG_list:", len(CSG_list))
# for sgcp_graph in SGcp_list:
# print("Nodes in sgcp_graph:", sgcp_graph.nodes())
if execute_part_1:
# print("Executing Part 1")
for sgcp_graph in SGcp_list:
for csg_graph in CSG_list:
common_nodes = set(sgcp_graph.nodes()).intersection(
csg_graph.nodes()
)
if common_nodes:
# print("Found common nodes")
# Copy the graph from SGcp_list to CSG_list
CSG_list.append(sgcp_graph.copy())
# print("Length of CSG_list after appending:", len(CSG_list))
# Remove the graph from SGcp_list
SGcp_list.remove(sgcp_graph)
# print("Length of SGcp_list after removing:", len(SGcp_list))
break # Break the inner loop as we found a match for the current sgcp_graph
execute_part_1 = False # Switch to Part 2 for the next iteration
if SGcp_list: # Check if SGcp_list is not empty before entering Part 2
# print("Executing Part 2")
# Flag to track if a connecting edge is found
connecting_edge_found = False
for sgcp_graph in SGcp_list:
# Iterate through each node in sgcp_graph
# draw_graph(sgcp_graph, 'lightgreen', layout='circular')
for node in sgcp_graph.nodes():
# Check if the node has an edge connecting to any graph in CSG_list
for csg_graph in CSG_list:
# Iterate over edges of the original graph G
for edge in G.edges():
# Check if the edge is between the current node in sgcp_graph and any node in csg_graph
if (
edge[0] in sgcp_graph.nodes()