-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_util.py
1731 lines (1360 loc) · 61.2 KB
/
my_util.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 sys
import math
import time
import ndlib
import random
import logging
import gpytorch
import warnings
import numpy as np
import pandas as pd
import heapdict as hd
import networkx as nx
import torch.nn as nn
from pyDOE import lhs
import statistics as s
import itertools as it
import scipy.sparse as sp
from graphGeneration import *
from scipy.linalg import expm
from scipy.sparse import diags
import matplotlib.pyplot as plt
import torch.nn.functional as F
from collections import Counter
from scipy.sparse import issparse
from gpytorch.module import Module
import ndlib.models.epidemics as ep
from scipy.sparse import csc_matrix
from gpytorch.means.mean import Mean
from joblib import Parallel, delayed
from scipy.sparse.linalg import eigsh
import community as community_louvain
from torch_geometric.data import Data
import ndlib.models.ModelConfig as mc
from scipy.interpolate import interp2d
from botorch.models import SingleTaskGP
from botorch.fit import fit_gpytorch_model
from torch_geometric.nn.inits import reset
from botorch.fit import fit_gpytorch_model
from hodgelaplacians import HodgeLaplacians
from gpytorch.models.exact_gp import ExactGP
from botorch.optim import optimize_acqf_discrete
from concurrent.futures import ThreadPoolExecutor
from gpytorch.kernels import RBFKernel, RFFKernel
from botorch.acquisition import ExpectedImprovement
from gpytorch.priors.torch_priors import GammaPrior
from gpytorch.mlls import ExactMarginalLogLikelihood
from gpytorch.means.constant_mean import ConstantMean
from gpytorch.likelihoods.likelihood import Likelihood
from gpytorch.kernels import MaternKernel, ScaleKernel
from sklearn.cluster import KMeans, SpectralClustering
from typing import Any, List, NoReturn, Optional, Union
from gpytorch.constraints.constraints import GreaterThan
from torch_geometric.nn import GCNConv, global_mean_pool
from botorch.models.transforms.input import InputTransform
from botorch.models.transforms.outcome import Log, OutcomeTransform
from botorch.models import SaasFullyBayesianSingleTaskGP
from gpytorch.likelihoods.gaussian_likelihood import GaussianLikelihood
from gpytorch.distributions.multivariate_normal import MultivariateNormal
from botorch.fit import fit_fully_bayesian_model_nuts
from botorch.models.utils import fantasize as fantasize_flag, validate_input_scaling
from random import uniform, seed
import operator
import copy
from torch_geometric.utils import to_networkx
from botorch.models.model import Model
from botorch.posteriors import GPyTorchPosterior
from botorch.acquisition import UpperConfidenceBound
from gpytorch.kernels import Kernel
from gpytorch.constraints import Positive
from gpytorch.means import ZeroMean
from gnngp import GNNGP
from datasets import load_data, transition_matrix
from jax import numpy as jnp
from jax import random as jax_random
from neural_tangents import stax
################################################
# Global parameters
################################################
diffusion_model = "ic" # "ic" or "lt"
graph_size = 1000
candidate_size = 50 # candidate pool size
number_of_sources = 3 # budget for IM
num_iterations = 300 # budget for BO
actual_time_step_size = 5 # diffusion parameter
allowed_shortest_distance = 1 # shortest distance between sources for filtering
num_of_sims = 10
number_of_clusters = 20
num_initial_samples = 20
def get_gaussian_likelihood_with_gamma_prior(
batch_shape: Optional[torch.Size] = None,
) -> GaussianLikelihood:
r"""Constructs the GaussianLikelihood that is used by default by
several models. This uses a Gamma(1.1, 0.05) prior and constrains the
noise level to be greater than MIN_INFERRED_NOISE_LEVEL (=1e-4).
"""
batch_shape = torch.Size() if batch_shape is None else batch_shape
noise_prior = GammaPrior(1.1, 0.05)
noise_prior_mode = (noise_prior.concentration - 1) / noise_prior.rate
return GaussianLikelihood(
noise_prior=noise_prior,
batch_shape=batch_shape,
noise_constraint=GreaterThan(
1e-4,
transform=None,
initial_value=noise_prior_mode,
),
)
# define a class inherited from SingleTaskGP for RBF/rff kernel
class RBFSingleTaskGP(SingleTaskGP):
def __init__(self, train_X: torch.Tensor,
train_Y: torch.Tensor,
likelihood: Optional[Likelihood] = None,
covar_module: Optional[Module] = None,
mean_module: Optional[Mean] = None,
outcome_transform: Optional[OutcomeTransform] = None,
input_transform: Optional[InputTransform] = None,
) -> None:
r"""
Args:
train_X: A `batch_shape x n x d` tensor of training features.
train_Y: A `batch_shape x n x m` tensor of training observations.
likelihood: A likelihood. If omitted, use a standard
GaussianLikelihood with inferred noise level.
covar_module: The module computing the covariance (Kernel) matrix.
If omitted, use a `RBF`.
mean_module: The mean function to be used. If omitted, use a
`ConstantMean`.
outcome_transform: An outcome transform that is applied to the
training data during instantiation and to the posterior during
inference (that is, the `Posterior` obtained by calling
`.posterior` on the model will be on the original scale).
input_transform: An input transform that is applied in the model's
forward pass.
"""
with torch.no_grad():
transformed_X = self.transform_inputs(
X=train_X, input_transform=input_transform
)
if outcome_transform is not None:
train_Y, _ = outcome_transform(train_Y)
self._validate_tensor_args(X=transformed_X, Y=train_Y)
ignore_X_dims = getattr(self, "_ignore_X_dims_scaling_check", None)
validate_input_scaling(
train_X=transformed_X, train_Y=train_Y, ignore_X_dims=ignore_X_dims
)
self._set_dimensions(train_X=train_X, train_Y=train_Y)
train_X, train_Y, _ = self._transform_tensor_args(X=train_X, Y=train_Y)
if likelihood is None:
likelihood = get_gaussian_likelihood_with_gamma_prior(
batch_shape=self._aug_batch_shape
)
else:
self._is_custom_likelihood = True
ExactGP.__init__(
self, train_inputs=train_X, train_targets=train_Y, likelihood=likelihood
)
if mean_module is None:
mean_module = ConstantMean(batch_shape=self._aug_batch_shape)
self.mean_module = mean_module
if covar_module is None:
covar_module = RBFKernel()
self._subset_batch_dict = {
"likelihood.noise_covar.raw_noise": -2,
"mean_module.raw_constant": -1,
"covar_module.raw_outputscale": -1,
"covar_module.base_kernel.raw_lengthscale": -3,
}
self.covar_module = covar_module
# TODO: Allow subsetting of other covar modules
if outcome_transform is not None:
self.outcome_transform = outcome_transform
if input_transform is not None:
self.input_transform = input_transform
self.to(train_X)
def forward(self, x: torch.Tensor) -> MultivariateNormal:
if self.training:
x = self.transform_inputs(x)
mean_x = self.mean_module(x)
covar_x = self.covar_module(x)
return MultivariateNormal(mean_x, covar_x)
# top candidate_size nodes with highest degree centrality as candidate pool
def create_candidate_set_pool_filtering(G, candidate_size=100, number_of_sources=3, allowed_shortest_distance=2):
deg = sorted(G.degree, key=lambda x: x[1], reverse=True)
candidates = []
for candidate in deg[:candidate_size]:
candidates.append(candidate[0])
candidate_source_sets = []
for selected_set in comb(candidates, number_of_sources):
shortest_distance = 5
for i in range(number_of_sources-2):
start = selected_set[i]
for j in range(i+1, number_of_sources-1):
end = selected_set[j]
distance = nx.shortest_path_length(G, source=start, target=end)
if distance < shortest_distance:
shortest_distance = distance
if shortest_distance > allowed_shortest_distance:
candidate_source_sets.append(selected_set)
# check_candidate_set(candidate_source_sets)
return candidate_source_sets
def check_candidate_set(candidate_source_sets):
candidate_sets = candidate_source_sets
print("candidate sets", candidate_sets)
logging.basicConfig(filename='candidate_sets_analysis.log', level=logging.INFO)
logging.info("Analyzing candidate sets...")
for i, set in enumerate(candidate_sets):
logging.info(f"Set {i+1} size: {len(set)}")
def create_candidate_set_pool(G, candidate_size=100, number_of_sources=3):
deg = sorted(G.degree, key=lambda x: x[1], reverse=True)
candidates = []
for candidate in deg[:candidate_size]:
candidates.append(candidate[0])
candidate_source_sets = []
for selected_set in comb(candidates, number_of_sources):
candidate_source_sets.append(selected_set)
return candidate_source_sets
def fourier_transfer_for_all_candidate_set(candidate_sets, UT):
n = len(UT)
# print("n", n)
signals = []
for source_set in candidate_sets:
a = [0 for i in range(n)]
# print('a', a)
for node in source_set:
# print("node", node)
a[node] = 1
signal = np.matmul(a, UT)
signals.append(signal)
# print('signals',signals)
return signals
def create_signal_from_source_set(G, sampled_set, UT):
n = len(UT)
a = [0 for i in range(n)]
for node in sampled_set:
a[node] = 1
signal = np.matmul(a, UT)
return signal
def find_source_set_from_fourier(signal, number_of_sources, UT_inv):
source_set = []
a = np.matmul(signal, UT_inv)
b = np.around(a)
for i in range(len(b)):
if b[i] == 1:
source_set.append(i)
if len(source_set) != number_of_sources:
raise NameError('length of source set is not the estimated number')
return source_set
################################################
# Mostly for Sobol
################################################
def combinations(alist):
n = len(alist)
subs = [[]]
for item in alist:
subs += [curr + [item] for curr in subs]
subs.sort(key=len)
return subs
def subcombs(alist):
subs = combinations(alist)
subs.remove([])
subs.remove(alist)
subs.sort(key=len)
return subs
def substract(alist, blist):
a = []
for i in alist:
a.append(i)
for i in blist:
a.remove(i)
return a
def diff(rank, order):
n = len(rank)
if (len(order) != n):
print('the lengths do not match')
pass
else:
difference = 0
for i in range(n):
item = rank[i]
index = order.index(item)
delta = abs(index - i)
difference += delta
return difference
def simulationIC(r, g, result, config):
title = []
for i in result:
title.append(i)
title.append('result')
df = pd.DataFrame(columns=title)
n = len(result)
for combs in combinations(result):
input = []
for i in range(n):
item = 1 if result[i] in combs else 0
input.append(item)
for i in range(r):
input1 = []
for item in input:
input1.append(item)
g_mid = g.__class__()
g_mid.add_nodes_from(g)
g_mid.add_edges_from(g.edges)
model_mid = ep.IndependentCascadesModel(g_mid)
config_mid = mc.Configuration()
config_mid.add_model_initial_configuration('Infected', combs)
for a, b in g_mid.edges():
weight = config.config["edges"]['threshold'][(a, b)]
g_mid[a][b]['weight'] = weight
config_mid.add_edge_configuration('threshold', (a, b), weight)
model_mid.set_initial_status(config_mid)
iterations = model_mid.iteration_bunch(actual_time_step_size)
trends = model_mid.build_trends(iterations)
total_no = 0
for j in range(actual_time_step_size):
a = iterations[j]['node_count'][1]
total_no += a
input1.append(total_no)
newdf = pd.DataFrame([input1], columns=title)
df = pd.concat([df,newdf])
return df
def simulationLT(r, g, result, config):
title = []
for i in result:
title.append(i)
title.append('result')
df = pd.DataFrame(columns=title)
n = len(result)
for combs in combinations(result):
input = []
for i in range(n):
item = 1 if result[i] in combs else 0
input.append(item)
for i in range(r):
input1 = []
for item in input:
input1.append(item)
g_mid = g.__class__()
g_mid.add_nodes_from(g)
g_mid.add_edges_from(g.edges)
model_mid = ep.ThresholdModel(g_mid)
config_mid = mc.Configuration()
config_mid.add_model_initial_configuration('Infected', combs)
for a, b in g_mid.edges():
weight = config.config["edges"]['threshold'][(a, b)]
g_mid[a][b]['weight'] = weight
config_mid.add_edge_configuration('threshold', (a, b), weight)
for i in g_mid.nodes():
threshold = random.randrange(1, 20)
threshold = round(threshold / 100, 2)
config_mid.add_node_configuration("threshold", i, threshold)
model_mid.set_initial_status(config_mid)
iterations = model_mid.iteration_bunch(actual_time_step_size)
trends = model_mid.build_trends(iterations)
total_no = iterations[actual_time_step_size-1]['node_count'][1]
input1.append(total_no)
newdf = pd.DataFrame([input1], columns=title)
df = pd.concat([df,newdf])
return df
def SobolT(df, result):
sobolt = {}
for node in result:
backup = []
for item in result:
backup.append(item)
backup.remove(node)
var = []
for sub in combinations(backup):
means = []
for case in combinations([node]):
total = []
seeds = sub + case
subdf = df
for item in result:
if item in seeds:
a = (subdf[item] == 1)
else:
a = (subdf[item] == 0)
subdf = subdf[a]
means.append(s.mean(subdf['result']))
var.append(s.pvariance(means))
sobolt[node] = s.mean(var)
return sobolt
def effectIC(g, config, sources,rounds=10):
input = []
for i in range(rounds):
g_mid = g.__class__()
g_mid.add_nodes_from(g)
g_mid.add_edges_from(g.edges)
model_mid = ep.IndependentCascadesModel(g_mid)
config_mid = mc.Configuration()
config_mid.add_model_initial_configuration('Infected', sources)
for a, b in g_mid.edges():
weight = config.config["edges"]['threshold'][(a, b)]
g_mid[a][b]['weight'] = weight
config_mid.add_edge_configuration('threshold', (a, b), weight)
model_mid.set_initial_status(config_mid)
iterations = model_mid.iteration_bunch(actual_time_step_size)
trends = model_mid.build_trends(iterations)
total_no = 0
for j in range(actual_time_step_size):
a = iterations[j]['node_count'][1]
total_no += a
input.append(total_no)
e = s.mean(input)
v = s.stdev(input)
return e,v
def effectLT(g, config, sources,rounds=10):
input = []
for i in range(rounds):
g_mid = g.__class__()
g_mid.add_nodes_from(g)
g_mid.add_edges_from(g.edges)
model_mid = ep.ThresholdModel(g_mid)
config_mid = mc.Configuration()
config_mid.add_model_initial_configuration('Infected', sources)
for a, b in g_mid.edges():
weight = config.config["edges"]['threshold'][(a, b)]
g_mid[a][b]['weight'] = weight
config_mid.add_edge_configuration('threshold', (a, b), weight)
for i in g.nodes():
threshold = random.randrange(1, 20)
threshold = round(threshold / 100, 2)
config_mid.add_node_configuration("threshold", i, threshold)
model_mid.set_initial_status(config_mid)
iterations = model_mid.iteration_bunch(actual_time_step_size)
trends = model_mid.build_trends(iterations)
total_no = iterations[actual_time_step_size-1]['node_count'][1]
input.append(total_no)
e = s.mean(input)
v = s.stdev((input))
return e,v
#######################################################
def compute_padding(G, alpha=0.5):
simplices = generate_simplices(G, 1)
hodge = HodgeLaplacians(simplices, maxdimension=1)
L_0 = hodge.getHodgeLaplacian(d=0).toarray()
L_1 = hodge.getHodgeLaplacian(d=1).toarray()
max_dim = max(L_0.shape[0], L_1.shape[0])
padded_L_0 = np.zeros((max_dim, max_dim))
padded_L_1 = np.zeros((max_dim, max_dim))
padded_L_0[:L_0.shape[0], :L_0.shape[1]] = L_0
padded_L_1[:L_1.shape[0], :L_1.shape[1]] = L_1
# Weighted combination of padded Hodge Laplacians
L_combined = alpha * padded_L_0 + (1 - alpha) * padded_L_1
return L_combined
def compute_heat_kernel(L, t):
"""Compute the heat kernel for a given Laplacian matrix and time t."""
return expm(-t * L)
def resize_matrix(smaller, target_dim):
x = np.linspace(0, 1, num=smaller.shape[0])
y = np.linspace(0, 1, num=smaller.shape[1])
interp = interp2d(x, y, smaller, kind='cubic')
new_x = np.linspace(0, 1, num=target_dim[0])
new_y = np.linspace(0, 1, num=target_dim[1])
return interp(new_x, new_y)
def combined_heat_kernel(G, t=1.0, alpha=0.5):
simplices = generate_simplices(G, 1)
hodge = HodgeLaplacians(simplices, maxdimension=1)
L_0 = hodge.getHodgeLaplacian(d=0).toarray()
L_1 = hodge.getHodgeLaplacian(d=1).toarray()
K_0 = compute_heat_kernel(L_0, t)
K_1 = compute_heat_kernel(L_1, t)
if K_0.shape[0] > K_1.shape[0]:
resized_K_1 = resize_matrix(K_1, K_0.shape)
combined_kernel = alpha * K_0 + (1 - alpha) * resized_K_1
else:
resized_K_0 = resize_matrix(K_0, K_1.shape)
combined_kernel = alpha * resized_K_0 + (1 - alpha) * K_1
return combined_kernel
def combined_heat_kernel_nl_sparse(G, simplices, t=1.0, alpha=0.5):
hodge = HodgeLaplacians(simplices, maxdimension=2)
L_0 = hodge.getHodgeLaplacian(d=0)
L_1 = hodge.getHodgeLaplacian(d=1)
L_0 = normalize_laplacian_sparse(L_0).toarray()
L_1 = normalize_laplacian_sparse(L_1).toarray()
K_0 = compute_heat_kernel(L_0, t)
K_1 = compute_heat_kernel(L_1, t)
if K_0.shape[0] > K_1.shape[0]:
resized_K_1 = resize_matrix(K_1, K_0.shape)
combined_kernel = alpha * K_0 + (1 - alpha) * resized_K_1
else:
resized_K_0 = resize_matrix(K_0, K_1.shape)
combined_kernel = alpha * resized_K_0 + (1 - alpha) * K_1
return combined_kernel
def to_csr_matrix(graph):
"""Convert a networkx graph to a CSR matrix."""
return csr_matrix(nx.to_numpy_array(graph))
def generate_boundary_matrix_1(adj_matrix):
"""Generate the boundary matrix for 1-simplices (edges)."""
num_vertices = adj_matrix.shape[0]
edges = np.transpose(adj_matrix.nonzero())
num_edges = edges.shape[0]
B_1 = sp.lil_matrix((num_vertices, num_edges))
for index, (i, j) in enumerate(edges):
if i < j:
B_1[i, index] = 1
B_1[j, index] = -1
return B_1.tocsr(), num_edges
def compute_hodge_laplacian_1(B_1):
"""Compute the Hodge Laplacian for 1-simplices."""
return B_1.T @ B_1
def find_triangles(graph):
"""Find all triangles in the graph."""
triangles = set()
for node in graph.nodes():
neighbors = set(graph.neighbors(node))
for u in neighbors:
for v in neighbors:
if u != v and graph.has_edge(u, v) and node < u < v:
triangles.add((node, u, v))
return list(triangles)
def generate_boundary_matrix_2(graph, triangles):
"""Generate the boundary matrix for 2-simplices (triangles)."""
edge_map = {}
edge_count = 0
for u, v in graph.edges():
sorted_edge = tuple(sorted((u, v)))
if sorted_edge not in edge_map:
edge_map[sorted_edge] = edge_count
edge_count += 1
B_2 = sp.lil_matrix((edge_count, len(triangles)))
for i, triangle in enumerate(triangles):
edges = [tuple(sorted((triangle[j], triangle[k]))) for j in range(3) for k in range(j + 1, 3)]
for edge in edges:
B_2[edge_map[edge], i] = 1
return B_2.tocsr()
def find_tetrahedrons(graph):
"""Find all tetrahedrons in the graph."""
tetrahedrons = set()
for u in graph.nodes():
neighbors_u = set(graph.neighbors(u))
for v in neighbors_u:
if u < v:
common_uv = neighbors_u.intersection(set(graph.neighbors(v)))
for w in common_uv:
if v < w:
common_uvw = common_uv.intersection(set(graph.neighbors(w)))
for x in common_uvw:
if w < x and graph.has_edge(u, x) and graph.has_edge(v, x) and graph.has_edge(w, x):
tetrahedrons.add((u, v, w, x))
return list(tetrahedrons)
def is_tetrahedron(graph, nodes):
"""Check if the given nodes form a tetrahedron (complete graph K4) in the graph."""
possible_edges = [(nodes[i], nodes[j]) for i in range(len(nodes)) for j in range(i + 1, len(nodes))]
return all(graph.has_edge(*edge) for edge in possible_edges)
def generate_boundary_matrix_3(graph, triangles, tetrahedrons):
"""Generate the boundary matrix for 3-simplices (tetrahedrons)."""
triangle_index = {tri: idx for idx, tri in enumerate(triangles)}
B_3 = sp.lil_matrix((len(triangles), len(tetrahedrons)))
for tet_idx, tet in enumerate(tetrahedrons):
for trio in [(tet[i], tet[j], tet[k]) for i in range(4) for j in range(i + 1, 4) for k in range(j + 1, 4)]:
tri = tuple(sorted(trio))
if tri in triangle_index:
B_3[triangle_index[tri], tet_idx] = 1 if (tet.index(tri[0]) + tet.index(tri[1]) + tet.index(tri[2])) % 2 == 0 else -1
return B_3.tocsr()
def get_laplacian_0(graph):
"""Retrieve the Hodge Laplacian for 0-simplices (vertices) directly from the graph."""
# Convert the graph to an adjacency matrix in CSR format
A = nx.adjacency_matrix(graph)
# Create the degree matrix
degrees = np.array(A.sum(axis=1)).flatten()
D = sp.diags(degrees)
# Compute the Laplacian
L_0 = D - A
return L_0
def get_laplacian_1(graph):
"""Retrieve the Hodge Laplacian for 1-simplices directly from the graph."""
adj_matrix = to_csr_matrix(graph)
B_1, _ = generate_boundary_matrix_1(adj_matrix)
L_1 = compute_hodge_laplacian_1(B_1)
return L_1
def get_laplacian_2(graph):
"""Retrieve the Hodge Laplacian for 2-simplices directly from the graph."""
triangles = find_triangles(graph)
B_2 = generate_boundary_matrix_2(graph, triangles)
L_2 = B_2.T @ B_2
return L_2
def get_laplacian_3(graph):
"""Retrieve the Hodge Laplacian for 3-simplices directly from the graph."""
triangles = find_triangles(graph)
tetrahedrons = find_tetrahedrons(graph)
B_3 = generate_boundary_matrix_3(graph, triangles, tetrahedrons)
L_3 = B_3.T @ B_3
return L_3
def generate_simplices_edge(graph):
simplices = []
# Add edges (1-simplices)
for u, v in graph.edges():
simplices.append((min(u, v), max(u, v)))
return simplices
def generate_simplices_triangle(graph):
simplices = []
# Add edges (1-simplices)
for u, v in graph.edges():
simplices.append((min(u, v), max(u, v)))
# Add triangles (2-simplices)
for node in graph.nodes():
neighbors = list(graph.neighbors(node))
for i in range(len(neighbors)):
for j in range(i + 1, len(neighbors)):
if graph.has_edge(neighbors[i], neighbors[j]):
triangle = tuple(sorted((node, neighbors[i], neighbors[j])))
simplices.append(triangle)
return simplices
################################################
def generate_simplices(graph, dimension):
simplices = []
# Add nodes (0-simplices) if needed
if dimension >= 0:
for node in graph.nodes():
simplices.append((node,))
# Add edges (1-simplices)
if dimension >= 1:
for u, v in graph.edges():
simplices.append((min(u, v), max(u, v)))
# Higher-dimensional simplices
if dimension >= 2:
# Add triangles (2-simplices)
for node in graph.nodes():
neighbors = list(graph.neighbors(node))
for i in range(len(neighbors)):
for j in range(i + 1, len(neighbors)):
if graph.has_edge(neighbors[i], neighbors[j]):
triangle = tuple(sorted((node, neighbors[i], neighbors[j])))
simplices.append(triangle)
if dimension >= 3:
# Add tetrahedrons (3-simplices)
for node in graph.nodes():
neighbors = list(graph.neighbors(node))
for i in range(len(neighbors)):
for j in range(i + 1, len(neighbors)):
for k in range(j + 1, len(neighbors)):
if (graph.has_edge(neighbors[i], neighbors[j]) and
graph.has_edge(neighbors[i], neighbors[k]) and
graph.has_edge(neighbors[j], neighbors[k])):
tetrahedron = tuple(sorted((node, neighbors[i], neighbors[j], neighbors[k])))
simplices.append(tetrahedron)
return simplices
def generate_simplices_tetrahedron(graph):
simplices = []
# Add edges (1-simplices)
for u, v in graph.edges():
simplices.append((min(u, v), max(u, v)))
# Add triangles (2-simplices)
for node in graph.nodes():
neighbors = list(graph.neighbors(node))
for i in range(len(neighbors)):
for j in range(i + 1, len(neighbors)):
if graph.has_edge(neighbors[i], neighbors[j]):
triangle = tuple(sorted((node, neighbors[i], neighbors[j])))
simplices.append(triangle)
# Add tetrahedrons (3-simplices)
for node in graph.nodes():
neighbors = list(graph.neighbors(node))
for i in range(len(neighbors)):
for j in range(i + 1, len(neighbors)):
for k in range(j + 1, len(neighbors)):
if (graph.has_edge(neighbors[i], neighbors[j]) and
graph.has_edge(neighbors[i], neighbors[k]) and
graph.has_edge(neighbors[j], neighbors[k])):
tetrahedron = tuple(sorted((node, neighbors[i], neighbors[j], neighbors[k])))
simplices.append(tetrahedron)
return simplices
def transform_features(candidates, eig_vect):
"""Apply transformation using eigenvectors to candidate sets. Adjust for dimension discrepancies."""
transformed = []
eig_dim = eig_vect.shape[0] # Dimensionality of the eigenvector space
for candidate in candidates:
# Convert candidate to numpy array if it's not already
candidate_array = np.asarray(candidate)
# Check if the candidate array matches the expected dimensions
if candidate_array.size != eig_dim:
# Handle dimension mismatch (could be error handling or padding)
if candidate_array.size > eig_dim:
# Truncate array if too long (not recommended without specific reason)
candidate_array = candidate_array[:eig_dim]
else:
# Pad array with zeros if too short
candidate_array = np.pad(candidate_array, (0, eig_dim - candidate_array.size), mode='constant')
candidate_vector = candidate_array.reshape(-1, 1)
transformed_vector = np.dot(eig_vect.T, candidate_vector).flatten()
transformed.append(transformed_vector)
return transformed
def normalize_laplacian_dense(L):
"""Normalize the Laplacian matrix."""
D = np.diag(np.sqrt(1 / np.diag(L)))
return np.dot(np.dot(D, L), D)
def normalize_laplacian_sparse(L):
# Sum up the rows of L, get the degree of each vertex/simplice
degree = np.array(L.sum(axis=1)).flatten() # Convert to 1D numpy array if it's not already
# Avoid division by zero in case of isolated nodes or similar issues
degree[degree == 0] = 1
# Create the diagonal matrix D^-1/2
D_inv_sqrt = diags(1.0 / np.sqrt(degree))
# Compute the normalized Laplacian L_sym = D^-1/2 * L * D^-1/2
L_normalized = D_inv_sqrt.dot(L).dot(D_inv_sqrt)
# Optionally convert to a dense matrix if needed and manageable size-wise
# L_normalized_dense = L_normalized.toarray() # Use this only if the matrix is not too large
return L_normalized
def get_graph_infomation(G):
# Check if the graph is directed
is_directed = G.is_directed()
# Calculate the density of the graph
density = nx.density(G)
# Check the number of connected components
if is_directed:
connected_components = nx.number_strongly_connected_components(G)
else:
connected_components = nx.number_connected_components(G)
# Get the degree distribution
degrees = [degree for node, degree in G.degree()]
# Calculate the average clustering coefficient
avg_clustering = nx.average_clustering(G)
print("Number of nodes:", G.number_of_nodes())
print("Number of edges:", G.number_of_edges())
print("Directed:", is_directed)
print("Density:", density)
print("Connected Components:", connected_components)
print("Average Degree:", sum(degrees) / len(degrees))
print("Average Clustering Coefficient:", avg_clustering)
def estimate_max_simplex_degree(graph):
# Convert the graph to a NetworkX graph if it isn't one already
if not isinstance(graph, nx.Graph):
G = nx.Graph(graph)
else:
G = graph
# Find all cliques in the graph
cliques = list(nx.find_cliques(G))
# Find the maximum size of these cliques
max_clique_size = max(len(clique) for clique in cliques)
# The highest degree of simplices corresponds to the size of the largest clique minus one
return max_clique_size - 1
def get_n_n_from_hodge(L0, L1, B):
return L0.dot(B.dot(L1).dot(B.T))
def get_m_m_from_hodge(L0, L1, B):
return L1.dot(B.T.dot(L0).dot(B))
####################### BOIM full helper begins #########################
def compute_eigen_decomposition(matrix):
# Check if the input matrix is a sparse matrix
if issparse(matrix):
print("Sparse matrix detected.")
# Check if it's a csr_matrix
if isinstance(matrix, csr_matrix):
print("CSR matrix detected.")
# Convert csr_matrix to dense array using toarray()
matrix_dense = matrix.toarray()
elif isinstance(matrix, csc_matrix):
print("CSC matrix detected.")
# Convert csc_matrix to dense array using toarray()
matrix_dense = matrix.toarray()
else:
print("Other sparse matrix format detected.")
# For other sparse formats, use todense()
matrix_dense = matrix.todense()
else:
print("Dense matrix detected.")
# If it's already a dense matrix, use it directly
matrix_dense = matrix
# Compute eigenvalues and eigenvectors
_, eig_vect = np.linalg.eigh(matrix_dense)
# Compute the inverse of eigenvectors
UT = np.linalg.inv(eig_vect)
UT_inv = eig_vect
# print("UT", UT)
return UT, UT_inv
def perform_clustering_and_select_signals(number_of_clusters, sets_after_fourier_transfer):
# print("candidate_sets", candidate_sets)
# sets_after_fourier_transfer = fourier_transfer_for_all_candidate_set(candidate_sets, UT)
# print("sets_after_fourier_transfer", sets_after_fourier_transfer)
kmeans = KMeans(n_clusters=number_of_clusters, random_state=0).fit(sets_after_fourier_transfer)
labels = kmeans.labels_
groups = [[] for i in range(number_of_clusters)]
for j in range(len(labels)):
groups[labels[j]].append(sets_after_fourier_transfer[j])
# return groups, sets_after_fourier_transfer
return groups
def simulate_initial_training(groups, G, config, num_of_sims, diffusion_model, number_of_sources, UT_inv):
train_X = []
train_Y = []
for i in range(number_of_clusters):
selected_signal = random.choice(groups[i])
source_set = find_source_set_from_fourier(selected_signal, number_of_sources, UT_inv)
if diffusion_model == 'ic':
e,_ = effectIC(G, config, source_set, num_of_sims)
elif diffusion_model == 'lt':
e,_ = effectLT(G, config, source_set, num_of_sims)
else:
raise NotImplementedError("Diffusion model not recognized.")
input = torch.FloatTensor(selected_signal)
train_X.append(input)
train_Y.append([float(e)])
return torch.stack(train_X), torch.tensor(train_Y)
def iterative_optimization(train_X, train_Y, groups, number_of_sources, UT_inv, G, config, num_of_sims, diffusion_model, num_iterations):
function_values = [train_Y.max().item()]
acquisition_values = []
max_train_Y_values = [train_Y.max().item()]
for iteration in range(num_iterations):
# from each cluster, sample 1 instances, select the one with the highest acquisition function value from the samples