knodes 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- knodes/__init__.py +1 -0
- knodes/centralities_nx.py +140 -0
- knodes/gauss.py +705 -0
- knodes/generate.py +33 -0
- knodes/hybrid.py +379 -0
- knodes/lowrank.py +731 -0
- knodes/spectral_deflation.py +333 -0
- knodes-0.1.0.dist-info/METADATA +297 -0
- knodes-0.1.0.dist-info/RECORD +11 -0
- knodes-0.1.0.dist-info/WHEEL +5 -0
- knodes-0.1.0.dist-info/top_level.txt +1 -0
knodes/gauss.py
ADDED
|
@@ -0,0 +1,705 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from math import sqrt
|
|
3
|
+
from scipy.sparse.linalg import eigsh
|
|
4
|
+
from scipy.sparse import csc_matrix
|
|
5
|
+
from scipy.sparse.csgraph import connected_components
|
|
6
|
+
from scipy.linalg import norm, eigh_tridiagonal
|
|
7
|
+
from typing import Literal, Optional, Tuple, Dict, Any, Union
|
|
8
|
+
from time import perf_counter
|
|
9
|
+
import logging
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
logging.basicConfig(level=logging.INFO)
|
|
13
|
+
|
|
14
|
+
def expm_eig(T: np.ndarray, mu: float = 0.0) -> float:
|
|
15
|
+
"""
|
|
16
|
+
Compute u * exp(T) * u', where T is the Lanczos tridiagonal matrix
|
|
17
|
+
|
|
18
|
+
:param T: tridiagonal Lanczos matrix
|
|
19
|
+
:param mu: spectral shift parameter
|
|
20
|
+
:return: the computed exponent
|
|
21
|
+
"""
|
|
22
|
+
eigvals, V = np.linalg.eigh(T)
|
|
23
|
+
exp_vals = np.exp(eigvals - mu)
|
|
24
|
+
return float(np.sum((V[0, :] ** 2) * exp_vals))
|
|
25
|
+
|
|
26
|
+
def res(T: np.ndarray, alpha: float) -> float:
|
|
27
|
+
"""
|
|
28
|
+
Computes the resolvent (I - alpha*T)^(-1) using spectral decomposition and
|
|
29
|
+
taking advantage of the structure of T (tridiagonal).
|
|
30
|
+
|
|
31
|
+
:param T: Lanczos tridiagonal matrix
|
|
32
|
+
:param alpha: spectral shift parameter (must satisfy 0 < alpha < 1/lambda_max(T))
|
|
33
|
+
:return: (I - alpha*T)^(-1)
|
|
34
|
+
"""
|
|
35
|
+
d = np.diag(T)
|
|
36
|
+
e = np.diag(T, k=-1)
|
|
37
|
+
eigvals, V = eigh_tridiagonal(d, e)
|
|
38
|
+
|
|
39
|
+
diag_elements = 1 / (1 - alpha * eigvals)
|
|
40
|
+
return float(np.sum((V[0, :] ** 2) * diag_elements))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def opolyval(alfa: np.ndarray, beta: np.ndarray, beta0: float, x: float) -> Tuple[float, float]:
|
|
44
|
+
"""
|
|
45
|
+
Computes orthonormal Lanczos polynomials p_k(x) and p_{k-1}(x) via three-term recurrence.
|
|
46
|
+
Used in Gauss-Radau quadrature to evaluate the modified diagonal coefficient for the prescribed node theta.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
alfa (np.ndarray): Diagonal Lanczos coefficients [alpha_0, ..., alpha_{k-1}].
|
|
50
|
+
beta (np.ndarray): Subdiagonal Lanczos coefficients [beta_0, beta_1, ..., beta_k] (where beta_0 is the initial norm).
|
|
51
|
+
beta0 (float): Initial norm ||u||_2 used to normalize the zero-th polynomial p_0(x) = 1 / beta_0.
|
|
52
|
+
x (float): Evaluation point (typically the estimated upper bound theta on the largest eigenvalue).
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
Tuple[float, float]: (p, p1) where p is p_k(x) and p1 is p_{k-1}(x).
|
|
56
|
+
"""
|
|
57
|
+
p1 = 1.0 / beta0
|
|
58
|
+
p = (x - alfa[0]) / beta[0]
|
|
59
|
+
|
|
60
|
+
# starting from second element
|
|
61
|
+
for k in range(1, len(alfa)):
|
|
62
|
+
p0 = p1
|
|
63
|
+
p1 = p
|
|
64
|
+
p = ((x - alfa[k]) * p1 - beta[k-1] * p0) / beta[k]
|
|
65
|
+
|
|
66
|
+
return float(p), float(p1)
|
|
67
|
+
|
|
68
|
+
def gauss_exp(A: Union[csc_matrix, np.ndarray], u: np.ndarray, theta: Optional[float] = None, opts: Optional[Dict[str, Any]] = None) -> Tuple[float, int]:
|
|
69
|
+
"""
|
|
70
|
+
Computes the bilinear form u' * exp(A) * u using Gauss and Gauss-Radau quadrature rules via Lanczos iteration.
|
|
71
|
+
|
|
72
|
+
Parameters:
|
|
73
|
+
A (Union[csc_matrix, np.ndarray]): Graph adjacency matrix (sparse CSC or dense ndarray).
|
|
74
|
+
u (np.ndarray): Starting vector for the Lanczos algorithm.
|
|
75
|
+
theta (Optional[float]): Upper bound estimate of the largest eigenvalue lambda_max(A).
|
|
76
|
+
If None, computed via eigsh(A, k=1, which='LA').
|
|
77
|
+
opts (Optional[Dict[str, Any]]): Dictionary of algorithmic parameters:
|
|
78
|
+
- "gauss_tol": Stopping tolerance for quadrature convergence |gr - g| / 2 (default: 1e-3).
|
|
79
|
+
- "gausstau": Breakdown threshold for Lanczos beta coefficient (default: 1e-10).
|
|
80
|
+
- "gauss_max_iterations": Maximum Lanczos iterations allowed (default: 100).
|
|
81
|
+
- "gauss_largest_eigenvalue": Explicit spectral shift parameter mu (default: theta).
|
|
82
|
+
- "gaussreorth": Reorthogonalization method (0: none, 1: MGS, 2: CGS, 3: double CGS).
|
|
83
|
+
- "gaussmgs": Boolean, whether to use Modified Gram-Schmidt in main step (default: True).
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
Tuple[float, int]:
|
|
87
|
+
- fval: Approximated quadrature value u' * exp(A) * u.
|
|
88
|
+
- info: Number of Lanczos iterations performed until convergence or max iterations.
|
|
89
|
+
"""
|
|
90
|
+
# default options
|
|
91
|
+
default_opts = {
|
|
92
|
+
"gauss_tol": 1e-3,
|
|
93
|
+
"gausstau": 1e-10,
|
|
94
|
+
"gauss_max_iterations": 100,
|
|
95
|
+
"gauss_largest_eigenvalue": None, # if None then default is theta
|
|
96
|
+
"gaussreorth": 0, # 0: no, 1: MGS, 2: CGS, 3: Double CGS
|
|
97
|
+
"gaussmgs": True # True for using MGS in the main step
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if opts is None:
|
|
101
|
+
opts = {}
|
|
102
|
+
# options merge
|
|
103
|
+
options = {**default_opts, **opts}
|
|
104
|
+
|
|
105
|
+
# handling theta
|
|
106
|
+
if theta is None:
|
|
107
|
+
# if not given, the largest eigenvalue is computed
|
|
108
|
+
# 'LA' = Largest Algebraic
|
|
109
|
+
t0 = perf_counter()
|
|
110
|
+
theta = eigsh(A, k=1, which='LA', return_eigenvectors=False)[0]
|
|
111
|
+
print(f"Tempo eigsh: {perf_counter() - t0:.4f} s")
|
|
112
|
+
|
|
113
|
+
# Use options["gauss_largest_eigenvalue"] if explicitly set (even if 0.0), otherwise use theta
|
|
114
|
+
mu = theta if options["gauss_largest_eigenvalue"] is None else options["gauss_largest_eigenvalue"]
|
|
115
|
+
|
|
116
|
+
# making sure that u is a column vector
|
|
117
|
+
u = np.array(u, dtype=np.float64).ravel()
|
|
118
|
+
m = u.shape[0]
|
|
119
|
+
|
|
120
|
+
# matrix-vector product operator
|
|
121
|
+
A_csr = A.tocsr()
|
|
122
|
+
mvprod = lambda x: A_csr.dot(x)
|
|
123
|
+
|
|
124
|
+
beta = norm(u)
|
|
125
|
+
sqrt_eps = np.sqrt(np.finfo(float).eps)
|
|
126
|
+
|
|
127
|
+
# max iterations number, (the max number of iterations can't be larger than the number of rows of the matrix A)
|
|
128
|
+
max_n = min(options["gauss_max_iterations"], m)
|
|
129
|
+
|
|
130
|
+
if options["gaussreorth"]: Q = np.zeros((m, max_n + 1))
|
|
131
|
+
|
|
132
|
+
T = np.zeros((max_n + 1, max_n + 1))
|
|
133
|
+
alf = np.zeros(max_n)
|
|
134
|
+
bet = np.zeros(max_n + 1)
|
|
135
|
+
bet[0] = beta
|
|
136
|
+
|
|
137
|
+
q_0 = np.zeros_like(u)
|
|
138
|
+
q = u / beta
|
|
139
|
+
|
|
140
|
+
if options["gaussreorth"]: Q[:, 0] = q.ravel()
|
|
141
|
+
|
|
142
|
+
dif = 1000.0
|
|
143
|
+
g = 0.0
|
|
144
|
+
gr = 0.0 # g with an additional step
|
|
145
|
+
|
|
146
|
+
# Lanczos loop
|
|
147
|
+
i = 0
|
|
148
|
+
t0 = perf_counter()
|
|
149
|
+
while (dif > options["gauss_tol"] * abs(g)) and (i < max_n):
|
|
150
|
+
|
|
151
|
+
# compute the product between the adjacency matrix and the vector
|
|
152
|
+
|
|
153
|
+
v = mvprod(q)
|
|
154
|
+
# local orthogonalization
|
|
155
|
+
if options["gaussmgs"]:
|
|
156
|
+
v -= beta * q_0
|
|
157
|
+
alfa = float(q.dot(v))
|
|
158
|
+
v -= alfa * q
|
|
159
|
+
else:
|
|
160
|
+
alfa = float(q.dot(v))
|
|
161
|
+
v -= beta * q_0 - alfa * q
|
|
162
|
+
|
|
163
|
+
# global re-orthogonalization
|
|
164
|
+
if options["gaussreorth"]:
|
|
165
|
+
# Q[:, :i+1] previous vectors
|
|
166
|
+
v_flat = v.ravel()
|
|
167
|
+
|
|
168
|
+
reorth_type = options["gaussreorth"]
|
|
169
|
+
|
|
170
|
+
if reorth_type == 1: # MGS
|
|
171
|
+
for j in range(i + 1):
|
|
172
|
+
q_j = Q[:, j]
|
|
173
|
+
proj = np.dot(v_flat, q_j)
|
|
174
|
+
v_flat -= proj * q_j
|
|
175
|
+
v = v_flat.reshape(-1, 1)
|
|
176
|
+
elif reorth_type == 2: # CGS
|
|
177
|
+
Q_curr = Q[:, :i+1]
|
|
178
|
+
v_flat -= Q_curr @ (Q_curr.T @ v_flat)
|
|
179
|
+
v = v_flat.reshape(-1, 1)
|
|
180
|
+
|
|
181
|
+
elif reorth_type == 3: # Double CGS
|
|
182
|
+
Q_curr = Q[:, :i+1]
|
|
183
|
+
c = Q_curr.T @ v_flat
|
|
184
|
+
v_flat -= Q_curr @ c
|
|
185
|
+
if norm(c) > sqrt_eps: # second step if necessary
|
|
186
|
+
c1 = Q_curr.T @ v_flat
|
|
187
|
+
v_flat -= Q_curr @ c1
|
|
188
|
+
v = v_flat.reshape(-1, 1)
|
|
189
|
+
|
|
190
|
+
# update of beta
|
|
191
|
+
beta = sqrt(v.dot(v))
|
|
192
|
+
q_0 = q # save current q for the next step
|
|
193
|
+
|
|
194
|
+
# Check breakdown
|
|
195
|
+
if beta < options["gausstau"]:
|
|
196
|
+
# Breakdown: exact convergence
|
|
197
|
+
T[i, i] = alfa
|
|
198
|
+
# compute exponential
|
|
199
|
+
g = expm_eig(T[:i+1, :i+1], mu)
|
|
200
|
+
gr = g
|
|
201
|
+
break
|
|
202
|
+
else:
|
|
203
|
+
q = v / beta
|
|
204
|
+
|
|
205
|
+
if options["gaussreorth"]:
|
|
206
|
+
Q[:, i+1] = q.ravel()
|
|
207
|
+
|
|
208
|
+
# save Lanczos coefficients
|
|
209
|
+
alf[i] = alfa
|
|
210
|
+
bet[i+1] = beta # bet[0] is the initial norm, bet[1] is beta_1, etc.
|
|
211
|
+
|
|
212
|
+
# --- Gauss Quadrature ---
|
|
213
|
+
|
|
214
|
+
# computing orthogonal polynomials for the missing node
|
|
215
|
+
# alf and bet are passed to the current iteration
|
|
216
|
+
# In Matlab: opolyval(alf(1:i),bet(2:i+1),1,theta)
|
|
217
|
+
# Python slicing: alf[:i+1], bet[1:i+2]
|
|
218
|
+
pm, pm1 = opolyval(alf[:i+1], bet[1:i+2], 1.0, theta)
|
|
219
|
+
# alfk1 (extra node for the extended quadrature)
|
|
220
|
+
# alfk1 = theta - bet(i+1)*(pm1/pm)
|
|
221
|
+
# bet[i+1] corresponds to the beta just calculated
|
|
222
|
+
alfk1 = theta - beta * (pm1 / pm)
|
|
223
|
+
|
|
224
|
+
# building extended T (tridiagonal matrix)
|
|
225
|
+
|
|
226
|
+
T[i, i] = alfa
|
|
227
|
+
T[i, i+1] = beta
|
|
228
|
+
T[i+1, i] = beta
|
|
229
|
+
T[i+1, i+1] = alfk1 # new node for the estimate
|
|
230
|
+
|
|
231
|
+
# estimate the integral with T_k
|
|
232
|
+
g = expm_eig(T[:i+1, :i+1], mu)
|
|
233
|
+
|
|
234
|
+
# estimate the integral with T_{k + 1}
|
|
235
|
+
gr = expm_eig(T[:i+2, :i+2], mu)
|
|
236
|
+
|
|
237
|
+
dif = abs(gr - g) / 2.0
|
|
238
|
+
|
|
239
|
+
i += 1
|
|
240
|
+
print(f"Tempo fine ciclo: {perf_counter() - t0:.4f} s")
|
|
241
|
+
# final result
|
|
242
|
+
# fval = bet(1)^2 * (gr + g)/2
|
|
243
|
+
# bet[0] is the initial norm of u
|
|
244
|
+
fval = (bet[0]**2) * (gr + g) / 2.0
|
|
245
|
+
info = i
|
|
246
|
+
|
|
247
|
+
e_mu = np.exp(mu)
|
|
248
|
+
if np.isfinite(e_mu):
|
|
249
|
+
fval = e_mu * fval
|
|
250
|
+
else:
|
|
251
|
+
print(f"Warning: Result is scaled by exp({mu:.2e})")
|
|
252
|
+
|
|
253
|
+
return fval, info # return the final value, iterations
|
|
254
|
+
|
|
255
|
+
# usage example:
|
|
256
|
+
# A = np.array([[2., -1.], [-1., 2.]])
|
|
257
|
+
# u = np.array([1., 0.])
|
|
258
|
+
# val, steps = gaussexp(A, u, theta=3.0)
|
|
259
|
+
# print(val, steps)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def gauss_res(A: Union[csc_matrix, np.ndarray], u: np.ndarray, rho: float, alpha: float, opts: Optional[Dict[str, Any]] = None) -> Tuple[float, int]:
|
|
265
|
+
"""
|
|
266
|
+
Computes the resolvent bilinear form u' * (I - alpha * A)^(-1) * u using Gauss and Gauss-Radau quadrature.
|
|
267
|
+
|
|
268
|
+
Parameters:
|
|
269
|
+
A (Union[csc_matrix, np.ndarray]): Graph adjacency matrix (sparse CSC or dense ndarray).
|
|
270
|
+
u (np.ndarray): Starting vector for the Lanczos algorithm.
|
|
271
|
+
rho (float): Upper bound estimate on the largest eigenvalue lambda_max(A) (spectral radius).
|
|
272
|
+
alpha (float): Resolvent parameter (attenuation factor), must satisfy 0 < alpha < 1 / rho.
|
|
273
|
+
opts (Optional[Dict[str, Any]]): Dictionary of algorithmic parameters:
|
|
274
|
+
- "gauss_tol": Stopping tolerance for quadrature convergence |gr - g| / 2 (default: 1e-3).
|
|
275
|
+
- "gausstau": Breakdown threshold for Lanczos beta coefficient (default: 1e-10).
|
|
276
|
+
- "gauss_max_iterations": Maximum Lanczos iterations allowed (default: 100).
|
|
277
|
+
- "gaussreorth": Reorthogonalization method (0: none, 1: MGS, 2: CGS, 3: double CGS).
|
|
278
|
+
- "gaussmgs": Boolean, whether to use Modified Gram-Schmidt in main step (default: True).
|
|
279
|
+
|
|
280
|
+
Returns:
|
|
281
|
+
Tuple[float, int]:
|
|
282
|
+
- fval: Approximated quadrature value u' * (I - alpha * A)^(-1) * u.
|
|
283
|
+
- info: Number of Lanczos iterations performed.
|
|
284
|
+
"""
|
|
285
|
+
# default options
|
|
286
|
+
default_opts = {
|
|
287
|
+
"gauss_tol": 1e-3,
|
|
288
|
+
"gausstau": 1e-10,
|
|
289
|
+
"gauss_max_iterations": 100,
|
|
290
|
+
"gaussreorth": 0, # 0: no, 1: MGS, 2: CGS, 3: Double CGS
|
|
291
|
+
"gaussmgs": True # True for using MGS in the main step
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
opts = opts or {}
|
|
295
|
+
# options merge
|
|
296
|
+
options = {**default_opts, **opts}
|
|
297
|
+
|
|
298
|
+
# Validate alpha is in valid range
|
|
299
|
+
if not (0 < alpha < 1 / rho):
|
|
300
|
+
raise ValueError(f"alpha must be in (0, {1/rho:.6f}), got {alpha}")
|
|
301
|
+
|
|
302
|
+
# theta is used in the polynomial approximation (set to largest eigenvalue)
|
|
303
|
+
theta = rho
|
|
304
|
+
|
|
305
|
+
# making sure that u is a column vector
|
|
306
|
+
u = np.array(u, dtype=np.float64).ravel()
|
|
307
|
+
m = u.shape[0]
|
|
308
|
+
|
|
309
|
+
# matrix-vector product operator
|
|
310
|
+
A_csr = A.tocsr()
|
|
311
|
+
mvprod = lambda x: A_csr.dot(x)
|
|
312
|
+
|
|
313
|
+
beta = norm(u)
|
|
314
|
+
sqrt_eps = np.sqrt(np.finfo(float).eps)
|
|
315
|
+
|
|
316
|
+
# max iterations number, (the max number of iterations can't be larger than the number of rows of the matrix A)
|
|
317
|
+
max_n = min(options["gauss_max_iterations"], m)
|
|
318
|
+
|
|
319
|
+
if options["gaussreorth"]: Q = np.zeros((m, max_n + 1))
|
|
320
|
+
|
|
321
|
+
T = np.zeros((max_n + 1, max_n + 1))
|
|
322
|
+
alf = np.zeros(max_n)
|
|
323
|
+
bet = np.zeros(max_n + 1)
|
|
324
|
+
bet[0] = beta
|
|
325
|
+
|
|
326
|
+
q_0 = np.zeros_like(u)
|
|
327
|
+
q = u / beta
|
|
328
|
+
|
|
329
|
+
if options["gaussreorth"]: Q[:, 0] = q.ravel()
|
|
330
|
+
|
|
331
|
+
dif = 1000.0
|
|
332
|
+
g = 0.0
|
|
333
|
+
gr = 0.0 # g with an additional step
|
|
334
|
+
|
|
335
|
+
# Lanczos loop
|
|
336
|
+
i = 0
|
|
337
|
+
while (dif > options["gauss_tol"] * abs(g)) and (i < max_n):
|
|
338
|
+
|
|
339
|
+
# compute the product between the adjacency matrix and the
|
|
340
|
+
v = mvprod(q)
|
|
341
|
+
|
|
342
|
+
# local orthogonalization
|
|
343
|
+
if options["gaussmgs"]:
|
|
344
|
+
v -= beta * q_0
|
|
345
|
+
alfa = float(q.dot(v))
|
|
346
|
+
v -= alfa * q
|
|
347
|
+
else:
|
|
348
|
+
alfa = float(q.dot(v))
|
|
349
|
+
v -= beta * q_0 - alfa * q
|
|
350
|
+
|
|
351
|
+
# global re-orthogonalization
|
|
352
|
+
if options["gaussreorth"]:
|
|
353
|
+
# Q[:, :i+1] previous vectors
|
|
354
|
+
v_flat = v.ravel()
|
|
355
|
+
|
|
356
|
+
reorth_type = options["gaussreorth"]
|
|
357
|
+
|
|
358
|
+
if reorth_type == 1: # MGS
|
|
359
|
+
for j in range(i + 1):
|
|
360
|
+
q_j = Q[:, j]
|
|
361
|
+
proj = np.dot(v_flat, q_j)
|
|
362
|
+
v_flat -= proj * q_j
|
|
363
|
+
v = v_flat.reshape(-1, 1)
|
|
364
|
+
|
|
365
|
+
elif reorth_type == 2: # CGS
|
|
366
|
+
Q_curr = Q[:, :i+1]
|
|
367
|
+
v_flat -= Q_curr @ (Q_curr.T @ v_flat)
|
|
368
|
+
v = v_flat.reshape(-1, 1)
|
|
369
|
+
|
|
370
|
+
elif reorth_type == 3: # Double CGS
|
|
371
|
+
Q_curr = Q[:, :i+1]
|
|
372
|
+
c = Q_curr.T @ v_flat
|
|
373
|
+
v_flat -= Q_curr @ c
|
|
374
|
+
if norm(c) > sqrt_eps: # second step if necessary
|
|
375
|
+
c1 = Q_curr.T @ v_flat
|
|
376
|
+
v_flat -= Q_curr @ c1
|
|
377
|
+
v = v_flat.reshape(-1, 1)
|
|
378
|
+
|
|
379
|
+
# update of beta
|
|
380
|
+
beta = sqrt(v.dot(v))
|
|
381
|
+
q_0 = q # save current q for the next step
|
|
382
|
+
|
|
383
|
+
# Check breakdown
|
|
384
|
+
if beta < options["gausstau"]:
|
|
385
|
+
# Breakdown: exact convergence
|
|
386
|
+
T[i, i] = alfa
|
|
387
|
+
# compute exponential
|
|
388
|
+
T_sub = T[:i+1, :i+1]
|
|
389
|
+
g = res(T_sub, alpha)
|
|
390
|
+
gr = g
|
|
391
|
+
break
|
|
392
|
+
else:
|
|
393
|
+
q = v / beta
|
|
394
|
+
|
|
395
|
+
if options["gaussreorth"]:
|
|
396
|
+
Q[:, i+1] = q.ravel()
|
|
397
|
+
|
|
398
|
+
# save Lanczos coefficients
|
|
399
|
+
alf[i] = alfa
|
|
400
|
+
bet[i+1] = beta # bet[0] is the initial norm, bet[1] is beta_1, etc.
|
|
401
|
+
|
|
402
|
+
# --- Gauss Quadrature ---
|
|
403
|
+
|
|
404
|
+
# computing orthogonal polynomials for the missing node
|
|
405
|
+
# alf and bet are passed to the current iteration
|
|
406
|
+
# In Matlab: opolyval(alf(1:i),bet(2:i+1),1,theta)
|
|
407
|
+
# Python slicing: alf[:i+1], bet[1:i+2]
|
|
408
|
+
|
|
409
|
+
pm, pm1 = opolyval(alf[:i+1], bet[1:i+2], 1.0, theta)
|
|
410
|
+
|
|
411
|
+
# alfk1 (extra node for the extended quadrature)
|
|
412
|
+
# alfk1 = theta - bet(i+1)*(pm1/pm)
|
|
413
|
+
# bet[i+1] corresponds to the beta just calculated
|
|
414
|
+
alfk1 = theta - beta * (pm1 / pm)
|
|
415
|
+
|
|
416
|
+
# building extended T (tridiagonal matrix)
|
|
417
|
+
|
|
418
|
+
T[i, i] = alfa
|
|
419
|
+
T[i, i+1] = beta
|
|
420
|
+
T[i+1, i] = beta
|
|
421
|
+
T[i+1, i+1] = alfk1 # new node for the estimate
|
|
422
|
+
|
|
423
|
+
# estimate the integral with T_k
|
|
424
|
+
g = res(T[:i+1, :i+1], alpha)
|
|
425
|
+
|
|
426
|
+
# estimate the integral with T_{k + 1}
|
|
427
|
+
gr = res(T[:i+2, :i+2], alpha)
|
|
428
|
+
|
|
429
|
+
dif = abs(gr - g) / 2.0
|
|
430
|
+
|
|
431
|
+
i += 1
|
|
432
|
+
|
|
433
|
+
# final result
|
|
434
|
+
# fval = bet(1)^2 * (gr + g)/2
|
|
435
|
+
# bet[0] is the initial norm of u
|
|
436
|
+
fval = (bet[0]**2) * (gr + g) / 2.0
|
|
437
|
+
info = i
|
|
438
|
+
|
|
439
|
+
return fval, info # return the final value and the number of iterations
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def sgcengauss(A: csc_matrix,
|
|
443
|
+
fun_name: Literal["exp", "res"] = "exp",
|
|
444
|
+
nnodes: int = 1,
|
|
445
|
+
opts: Optional[Dict[str, Any]] = None) -> Tuple[np.ndarray, np.ndarray, bool, np.ndarray, np.ndarray]:
|
|
446
|
+
"""
|
|
447
|
+
Computes subgraph centrality for all nodes in the network via Gauss quadrature and extracts the top K-nodes.
|
|
448
|
+
For each node i, evaluates the bilinear form e_i' * f(A) * e_i where f is exp(A) or the resolvent (I - alpha*A)^(-1).
|
|
449
|
+
|
|
450
|
+
Parameters:
|
|
451
|
+
A (csc_matrix): Graph adjacency matrix (column sparse and symmetric).
|
|
452
|
+
fun_name (Literal["exp", "res"]): Function type: "exp" for exponential subgraph centrality,
|
|
453
|
+
"res" for resolvent subgraph centrality. Defaults to "exp".
|
|
454
|
+
nnodes (int): Number of top K-nodes to identify (defaults to 1).
|
|
455
|
+
opts (Optional[Dict[str, Any]]): Dictionary of algorithmic options:
|
|
456
|
+
- "gauss_tol": Stopping tolerance for quadrature error estimation (default: 1e-3).
|
|
457
|
+
- "gauss_max_iterations": Maximum Lanczos iterations per node (default: 200).
|
|
458
|
+
- "gauss_largest_eigenvalue": Upper bound on lambda_max(A) (default: computed via eigsh).
|
|
459
|
+
- "alpha": Resolvent parameter (required if fun_name == "res", must satisfy 0 < alpha < 1/lambda_max).
|
|
460
|
+
|
|
461
|
+
Returns:
|
|
462
|
+
Tuple[np.ndarray, np.ndarray, bool, np.ndarray, np.ndarray]:
|
|
463
|
+
- k_nodes (np.ndarray): Indices of the top K-nodes sorted by decreasing score.
|
|
464
|
+
- k_sgc (np.ndarray): Subgraph centrality scores of the top K-nodes.
|
|
465
|
+
- flag (bool): True if at least one node reached gauss_max_iterations without meeting gauss_tol.
|
|
466
|
+
- iters (np.ndarray): Number of matrix-vector products (iterations) performed for each node in the network.
|
|
467
|
+
- allsg (np.ndarray): Subgraph centrality scores computed for all nodes in the network.
|
|
468
|
+
"""
|
|
469
|
+
if opts is None:
|
|
470
|
+
opts = {}
|
|
471
|
+
|
|
472
|
+
gauss_tol = opts.get("gauss_tol", 1e-3)
|
|
473
|
+
gauss_max_iterations = opts.get("gauss_max_iterations", 200)
|
|
474
|
+
gauss_largest_eigenvalue = opts.get("gauss_largest_eigenvalue", eigsh(A, k=1, which='LA', return_eigenvectors=False)[0])
|
|
475
|
+
alpha = opts.get("alpha", 0.0)
|
|
476
|
+
|
|
477
|
+
logger.info(f"Starting sgcengauss: nnodes = {nnodes}, options = {opts}")
|
|
478
|
+
|
|
479
|
+
n = A.shape[0]
|
|
480
|
+
|
|
481
|
+
allsg = np.zeros(n)
|
|
482
|
+
iters = np.zeros(n)
|
|
483
|
+
ei = np.zeros(n)
|
|
484
|
+
|
|
485
|
+
info = 0
|
|
486
|
+
|
|
487
|
+
theta = gauss_largest_eigenvalue
|
|
488
|
+
if fun_name == 'res' and not (0 < alpha < 1 / theta):
|
|
489
|
+
raise ValueError(f"alpha must be in (0, {1/theta:.6f}), got {alpha}")
|
|
490
|
+
|
|
491
|
+
for i in range(n):
|
|
492
|
+
ei[i] = 1
|
|
493
|
+
t0 = perf_counter()
|
|
494
|
+
allsg[i], iters[i] = gauss_exp(A, ei, theta, opts) if fun_name == "exp" else gauss_res(A, ei, theta, alpha, opts)
|
|
495
|
+
ei[i] = 0
|
|
496
|
+
info += 1 if iters[i] >= gauss_max_iterations else 0
|
|
497
|
+
logger.info(f"matrix-vector products, maxn, node, elapsed time: {iters[i]}, {gauss_max_iterations}, {i}, {perf_counter() - t0:.4f}")
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
indx = np.argsort(allsg)[::-1]
|
|
501
|
+
allsg = allsg[indx]
|
|
502
|
+
|
|
503
|
+
k_nodes = indx[:nnodes]
|
|
504
|
+
k_sgc = allsg[:nnodes]
|
|
505
|
+
|
|
506
|
+
logger.info("gauss function completed")
|
|
507
|
+
|
|
508
|
+
return k_nodes, k_sgc, info > 0, iters, allsg
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def commgauss(A: csc_matrix,
|
|
512
|
+
i: int,
|
|
513
|
+
fun_name: Literal["exp", "res"] = "exp",
|
|
514
|
+
nnodes: int = 1,
|
|
515
|
+
opts: Optional[Dict[str, Any]] = None) -> Tuple[np.ndarray, np.ndarray, bool, np.ndarray, np.ndarray]:
|
|
516
|
+
"""
|
|
517
|
+
Computes communicability between target node i and all other nodes via Gauss quadrature and polarization identity.
|
|
518
|
+
Extracts the connected component of node i for numerical stability.
|
|
519
|
+
|
|
520
|
+
Parameters:
|
|
521
|
+
A (csc_matrix): Graph adjacency matrix (column sparse and symmetric).
|
|
522
|
+
i (int): Index of the target node (0-based) to which communicability is measured.
|
|
523
|
+
fun_name (Literal["exp", "res"]): Function type: "exp" for exponential communicability [exp(A)]_{ij},
|
|
524
|
+
"res" for resolvent communicability [(I - alpha*A)^(-1)]_{ij}. Defaults to "exp".
|
|
525
|
+
nnodes (int): Number of top K-nodes to identify with highest communicability to node i (defaults to 1).
|
|
526
|
+
opts (Optional[Dict[str, Any]]): Algorithmic options dictionary:
|
|
527
|
+
- "gauss_tol": Stopping tolerance for quadrature (default: 1e-3).
|
|
528
|
+
- "gauss_max_iterations": Maximum Lanczos iterations per node evaluation (default: 200).
|
|
529
|
+
- "gauss_largest_eigenvalue": Upper bound on lambda_max of the connected component (default: computed via eigsh).
|
|
530
|
+
- "alpha": Resolvent parameter (required if fun_name == "res", must satisfy 0 < alpha < 1/lambda_max).
|
|
531
|
+
|
|
532
|
+
Returns:
|
|
533
|
+
Tuple[np.ndarray, np.ndarray, bool, np.ndarray, np.ndarray]:
|
|
534
|
+
- k_nodes (np.ndarray): Indices of the top K-nodes (in original network indices) sorted by decreasing communicability with node i.
|
|
535
|
+
- k_comm (np.ndarray): Communicability scores of the top K-nodes.
|
|
536
|
+
- flag (bool): True if at least one evaluation reached gauss_max_iterations.
|
|
537
|
+
- iters_original (np.ndarray): Number of matrix-vector products performed for each node in the network (0 for nodes outside the component).
|
|
538
|
+
- allcomm_original (np.ndarray): Communicability values to node i for all nodes in the network.
|
|
539
|
+
"""
|
|
540
|
+
if i < 0 or i >= A.shape[0]:
|
|
541
|
+
raise ValueError(f"node {i} not found, must be in the range [0, {A.shape[0]})")
|
|
542
|
+
|
|
543
|
+
if np.sum(A[:, i]) == 0:
|
|
544
|
+
raise ValueError(f"node {i + 1} is not connected to any other node (degree 0).")
|
|
545
|
+
|
|
546
|
+
# extracting connected component
|
|
547
|
+
n_components, labels = connected_components(csgraph=A, directed=False, return_labels=True)
|
|
548
|
+
target_label = labels[i]
|
|
549
|
+
component_mask = (labels == target_label)
|
|
550
|
+
original_indices = np.where(component_mask)[0]
|
|
551
|
+
|
|
552
|
+
A_sub = A[component_mask, :][:, component_mask]
|
|
553
|
+
local_i = np.where(original_indices == i)[0][0]
|
|
554
|
+
n_sub = A_sub.shape[0]
|
|
555
|
+
|
|
556
|
+
if n_sub == 1:
|
|
557
|
+
logger.warning(f"the connected component of node {i} contains only the node itself.")
|
|
558
|
+
return np.array([]), np.array([]), False, np.array([]), np.array([])
|
|
559
|
+
|
|
560
|
+
logger.info(f"Extracted isolated network: {n_sub} nodes (original: {A.shape[0]} nodes).")
|
|
561
|
+
|
|
562
|
+
if opts is None:
|
|
563
|
+
opts = {}
|
|
564
|
+
|
|
565
|
+
gauss_tol = opts.get("gauss_tol", 1e-3)
|
|
566
|
+
gauss_max_iterations = opts.get("gauss_max_iterations", 200)
|
|
567
|
+
# Compute largest eigenvalue of A_sub instead of A
|
|
568
|
+
gauss_largest_eigenvalue = opts.get("gauss_largest_eigenvalue", eigsh(A_sub, k=1, which='LA', return_eigenvectors=False)[0])
|
|
569
|
+
alpha = opts.get("alpha", 0.0)
|
|
570
|
+
logger.info(alpha)
|
|
571
|
+
|
|
572
|
+
logger.info(f"Starting commgauss: nnodes = {nnodes}, options = {opts}")
|
|
573
|
+
|
|
574
|
+
allcomm_local = np.zeros(n_sub)
|
|
575
|
+
iters_local = np.zeros(n_sub)
|
|
576
|
+
y_local = np.zeros(n_sub)
|
|
577
|
+
|
|
578
|
+
info = 0
|
|
579
|
+
|
|
580
|
+
theta = gauss_largest_eigenvalue
|
|
581
|
+
logger.info(theta)
|
|
582
|
+
if fun_name == 'res' and not (0 < alpha < 1 / theta):
|
|
583
|
+
raise ValueError(f"alpha must be in (0, {1/theta:.6f}), got {alpha}")
|
|
584
|
+
|
|
585
|
+
y_local[local_i] = 1
|
|
586
|
+
for j in range(n_sub):
|
|
587
|
+
t0 = perf_counter()
|
|
588
|
+
if j == local_i:
|
|
589
|
+
allcomm_local[j], iters_local[j] = gauss_exp(A_sub, y_local, theta, opts) if fun_name == "exp" else gauss_res(A_sub, y_local, theta, alpha, opts)
|
|
590
|
+
else:
|
|
591
|
+
y_local[j] = 1
|
|
592
|
+
allcomm1, iters1 = gauss_exp(A_sub, y_local/np.sqrt(2), theta, opts) if fun_name == "exp" else gauss_res(A_sub, y_local/np.sqrt(2), theta, alpha, opts)
|
|
593
|
+
iters_local[j] = iters1
|
|
594
|
+
y_local[j] = -1
|
|
595
|
+
allcomm2, iters2 = gauss_exp(A_sub, y_local/np.sqrt(2), theta, opts) if fun_name == "exp" else gauss_res(A_sub, y_local/np.sqrt(2), theta, alpha, opts)
|
|
596
|
+
iters_local[j] += iters2
|
|
597
|
+
allcomm_local[j] = 0.5 * (allcomm1 - allcomm2)
|
|
598
|
+
y_local[j] = 0
|
|
599
|
+
info += 1 if iters_local[j] >= gauss_max_iterations else 0
|
|
600
|
+
logger.info(f"matrix-vector products, maxn, node, elapsed time: {iters_local[j]}, {gauss_max_iterations}, {original_indices[j]}, {perf_counter() - t0:.4f}")
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
indx_local = np.argsort(allcomm_local)[::-1]
|
|
604
|
+
allcomm_sorted = allcomm_local[indx_local]
|
|
605
|
+
|
|
606
|
+
k_local_indices = indx_local[:nnodes]
|
|
607
|
+
k_comm = allcomm_sorted[:nnodes]
|
|
608
|
+
|
|
609
|
+
# mapping to original matrix
|
|
610
|
+
k_nodes = original_indices[k_local_indices]
|
|
611
|
+
allcomm_original = np.zeros(A.shape[0])
|
|
612
|
+
allcomm_original[original_indices] = allcomm_local
|
|
613
|
+
iters_original = np.zeros(A.shape[0])
|
|
614
|
+
iters_original[original_indices] = iters_local
|
|
615
|
+
|
|
616
|
+
logger.info("commgauss function completed")
|
|
617
|
+
|
|
618
|
+
return k_nodes, k_comm, info > 0, iters_original, allcomm_original
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
def stconvgauss(A: csc_matrix,
|
|
622
|
+
fun_name: Literal["exp", "res"] = "exp",
|
|
623
|
+
nnodes: int = 1,
|
|
624
|
+
opts: Optional[Dict[str, Any]] = None) -> Tuple[np.ndarray, np.ndarray, bool, np.ndarray, np.ndarray]:
|
|
625
|
+
"""
|
|
626
|
+
Computes starting convenience for all nodes in the network via Gauss quadrature and extracts the top K-nodes.
|
|
627
|
+
Starting convenience represents total communicability from node i to the entire network: e_i' * f(A) * 1.
|
|
628
|
+
|
|
629
|
+
Parameters:
|
|
630
|
+
A (csc_matrix): Graph adjacency matrix (column sparse and symmetric).
|
|
631
|
+
fun_name (Literal["exp", "res"]): Function type: "exp" for exponential starting convenience,
|
|
632
|
+
"res" for resolvent starting convenience. Defaults to "exp".
|
|
633
|
+
nnodes (int): Number of top K-nodes to identify (defaults to 1).
|
|
634
|
+
opts (Optional[Dict[str, Any]]): Algorithmic options dictionary:
|
|
635
|
+
- "gauss_tol": Stopping tolerance for quadrature (default: 1e-3).
|
|
636
|
+
- "gauss_max_iterations": Maximum Lanczos iterations per node (default: 200).
|
|
637
|
+
- "gauss_largest_eigenvalue": Upper bound on lambda_max(A) (default: computed via eigsh).
|
|
638
|
+
- "alpha": Resolvent parameter (required if fun_name == "res", must satisfy 0 < alpha < 1/lambda_max).
|
|
639
|
+
|
|
640
|
+
Returns:
|
|
641
|
+
Tuple[np.ndarray, np.ndarray, bool, np.ndarray, np.ndarray]:
|
|
642
|
+
- k_nodes (np.ndarray): Indices of the top K-nodes sorted by decreasing starting convenience.
|
|
643
|
+
- k_stconv (np.ndarray): Starting convenience scores of the top K-nodes.
|
|
644
|
+
- flag (bool): True if at least one evaluation reached gauss_max_iterations.
|
|
645
|
+
- iters (np.ndarray): Number of matrix-vector products performed for each node in the network.
|
|
646
|
+
- allstconv (np.ndarray): Starting convenience scores computed for all nodes in the network.
|
|
647
|
+
"""
|
|
648
|
+
if opts is None:
|
|
649
|
+
opts = {}
|
|
650
|
+
|
|
651
|
+
gauss_tol = opts.get("gauss_tol", 1e-3)
|
|
652
|
+
gauss_max_iterations = opts.get("gauss_max_iterations", 200)
|
|
653
|
+
gauss_largest_eigenvalue = opts.get("gauss_largest_eigenvalue", eigsh(A, k=1, which='LA', return_eigenvectors=False)[0])
|
|
654
|
+
alpha = opts.get("alpha", 0.0)
|
|
655
|
+
|
|
656
|
+
n = A.shape[0]
|
|
657
|
+
|
|
658
|
+
logger.info(f"Starting stconvgauss: nnodes = {nnodes}, options = {opts}")
|
|
659
|
+
|
|
660
|
+
if n == 1:
|
|
661
|
+
logger.warning("the network has only 1 node, returning trivial result")
|
|
662
|
+
return np.array([0]), np.array([1.0]), False, np.array([0]), np.array([1.0])
|
|
663
|
+
|
|
664
|
+
allstconv = np.zeros(n)
|
|
665
|
+
allstconv1 = 0.0
|
|
666
|
+
allstconv2 = 0.0
|
|
667
|
+
iters = np.zeros(n)
|
|
668
|
+
y = np.ones(n)
|
|
669
|
+
|
|
670
|
+
info = 0
|
|
671
|
+
|
|
672
|
+
theta = gauss_largest_eigenvalue
|
|
673
|
+
if fun_name == 'res' and not (0 < alpha < 1 / theta):
|
|
674
|
+
raise ValueError(f"alpha must be in (0, {1/theta:.6f}), got {alpha}")
|
|
675
|
+
|
|
676
|
+
np3 = n + 3
|
|
677
|
+
nm1 = n - 1
|
|
678
|
+
|
|
679
|
+
for i in range(n):
|
|
680
|
+
y[i] = 2
|
|
681
|
+
t0 = perf_counter()
|
|
682
|
+
|
|
683
|
+
allstconv1, inf = gauss_exp(A, y/np.sqrt(np3), theta, opts) if fun_name == "exp" else gauss_res(A, y/np.sqrt(np3), theta, alpha, opts)
|
|
684
|
+
iters[i] = inf
|
|
685
|
+
|
|
686
|
+
y[i] = 0
|
|
687
|
+
|
|
688
|
+
allstconv2, inf = gauss_exp(A, y/np.sqrt(nm1), theta, opts) if fun_name == "exp" else gauss_res(A, y/np.sqrt(nm1), theta, alpha, opts)
|
|
689
|
+
allstconv[i] = (np3 * allstconv1 - nm1 * allstconv2) / 4
|
|
690
|
+
iters[i] += inf
|
|
691
|
+
|
|
692
|
+
info += 1 if iters[i] >= gauss_max_iterations else 0
|
|
693
|
+
y[i] = 1
|
|
694
|
+
logger.info(f"matrix-vector products, maxn, node, elapsed time: {iters[i]}, {gauss_max_iterations}, {i}, {perf_counter() - t0:.4f}")
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
indx = np.argsort(allstconv)[::-1]
|
|
698
|
+
allstconv = allstconv[indx]
|
|
699
|
+
|
|
700
|
+
k_nodes = indx[:nnodes]
|
|
701
|
+
k_stconv = allstconv[:nnodes]
|
|
702
|
+
|
|
703
|
+
logger.info("gauss function completed")
|
|
704
|
+
|
|
705
|
+
return k_nodes, k_stconv, info > 0, iters, allstconv
|