-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNetwork.py
162 lines (140 loc) · 5.55 KB
/
Network.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
import EffRApprox as er
import Spielman_Sparse as spl
import numpy as np
from scipy import sparse
import networkx as nx
class Network:
def __init__(self, E_list, weights, *args):
if len(args) != 0:
for arg in args:
if arg.size() > 10000:
A = nx.adjacency_matrix(arg)
if not self._csr_allclose(a=A, b=A.T):
A.setdiag(0)
A = (A + A.T) / 2
self.graph = A
self._getIDs(arg)
# self.data = arg.nodes.data()
# self.pos = self._getpos(arg)
self.pop = self._getpop(arg)
del arg
G = nx.from_scipy_sparse_matrix(A)
self.neighbors = self._findneighbors(G)
self._getedgelist(A)
else:
A = nx.adjacency_matrix(arg).toarray()
if not np.allclose(A, A.T):
np.fill_diagonal(A, 0)
A = (A + A.T) / 2
self.E_list, self.weights = er.Mtrx_Elist(A)
self.graph = A
self.neighbors = self._findneighbors(A)
else:
self.E_list = E_list
self.weights = weights
self.IDs = None
self.data = None
self.neighbors = self._findneighbors(er.Elist_Mtrx(E_list, weights))
self.graph = self.adj()
def _getIDs(self, G):
nodes = [i for i in G.nodes]
IDs = {}
for i in range(len(nodes)):
IDs[nodes[i]] = i
self.IDs = IDs
def _getpos(self, G):
pos = {}
nodes = {}
long = nx.get_node_attributes(G, 'longitude')
lat = nx.get_node_attributes(G, 'latitude')
ids = [x for x in self.IDs.keys()]
for i in range(len(self.IDs)):
nodes[i] = ids[i]
for i in range(G.number_of_nodes()):
pos[nodes[i]] = (long[nodes[i]], lat[nodes[i]])
return pos
@staticmethod
def _csr_allclose(a, b, rtol=1e-5, atol=1e-8):
c = np.abs(np.abs(a - b) - rtol * np.abs(b))
return c.max() <= atol
# @staticmethod
# def _findneighbors(G):
# neighbors = {}
# if isinstance(G, nx.classes.graph.Graph):
# for n in range(G.number_of_nodes()):
# test = [x for x in nx.neighbors(G,n)]
# neighbors[n] = [(n, x, G[n][x]['weight']) for x in test]
# elif isinstance(G, np.ndarray):
# for n in range(len(G)):
# incident_row = G[n, :]
# edges = [i for i, e in enumerate(incident_row) if e > 0]
# neighbors[n] = [(n, x, G[n, x]) for x in edges]
# return neighbors
@staticmethod # Second method
def _findneighbors(G):
neighbors = {}
if isinstance(G, nx.classes.graph.Graph):
for n in range(G.number_of_nodes()):
neighbors[n] = list(nx.neighbors(G, n))
elif isinstance(G, np.ndarray):
for n in range(len(G)):
incident_row = G[n, :]
edges = [i for i, e in enumerate(incident_row) if e > 0]
neighbors[n] = edges
return neighbors
@staticmethod
def _getpop(G):
pop = np.zeros((1, G.number_of_nodes()))
i = 0
for n in G.nodes:
p = G.nodes[n]
if len(p) != 0:
pop[0, i] = p['Population']
else:
pop[0, i] = 0
i += 1
return pop
def _getedgelist(self, A):
E = sparse.triu(A)
edges = E.nonzero()
E_list = np.zeros((len(edges[1]), 2))
weights = []
i = 0
for e1, e2 in zip(edges[0], edges[1]):
E_list[i, :] = e1, e2
weights.append(A[e1, e2])
i += 1
self.E_list = E_list.astype('int')
self.weights = weights
def samplepop(self, per, seed=None):
rng = np.random.default_rng(seed)
return rng.choice(np.array(range(self.pop.shape[1])), int(per * self.pop.shape[1]), False, spl.normprobs(self.pop[0,:]))
def adj(self):
return er.Elist_Mtrx(self.E_list, self.weights)
def edgenum(self):
return len(self.weights)
def nodenum(self):
return self.graph.shape[0]
def effR(self, epsilon, method, tol=1e-10, precon=False):
return er.EffR(self.E_list, self.weights, epsilon, method, tol=tol, precon=precon)
def spl(self, q, effR, seed=None):
spl_net = spl.Spl_EffRSparse(n=self.graph.shape[0], E_list=self.E_list, weights=self.weights, q=q, effR=effR,
seed=seed)
E_list, weights = er.Mtrx_Elist(spl_net)
return Network(E_list, weights)
def uni(self, q, seed=None):
uni_net = spl.UniSampleSparse(n=self.graph.shape[0], E_list=self.E_list, weights=self.weights, q=q, seed=seed)
E_list, weights = er.Mtrx_Elist(uni_net)
return Network(E_list, weights)
def wts(self, q, seed=None):
wts_net = spl.WeightSparse(n=self.graph.shape[0], E_list=self.E_list, weights=self.weights, q=q, seed=seed)
E_list, weights = er.Mtrx_Elist(wts_net)
return Network(E_list, weights)
def thr(self, per):
E_list, weights = spl.Thresh(self.nodenum(), self.E_list, self.weights, per)
return Network(E_list, weights)
@classmethod
def tri(cls):
A = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]])
E_list, weights = er.Mtrx_Elist(A)
return Network(E_list, weights)