-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction.py
More file actions
96 lines (85 loc) · 2.5 KB
/
function.py
File metadata and controls
96 lines (85 loc) · 2.5 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
# coding: utf-8
# In[ ]:
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 17 18:58:33 2019
@author: chendan
"""
import networkx as nx
import numpy as np
from scipy import linalg
#Compute the adjacency matrix and the Laplace matrix
def cal_AandL(G):
# Gets a sparse storage format for the network's adjacency matrix
edgelist = nx.adjacency_matrix(G)
# Get the adjacency matrix of network G (in two-dimensional array form)
A = np.array(edgelist.todense())
A_2 = np.dot(A, A)
# Diagonal matrix consisting of degrees of nodes
D = np.diag(np.diag(A_2))
L = D - A
return A, L
#========Calculation of density matrix=======
def cal_density_matrix1(H):
eig = linalg.eigvals(H)
Z = np.sum(eig)
p = (H/Z).real
return p
def cal_density_matrix2(beta,H):
eig = linalg.eigvals(H)
Z = np.sum(np.exp(-beta*eig), dtype=np.float64)
p = (linalg.expm(-beta*H)/Z).real
return p
#============================================
#=======Calculation of spectral entropy======
def cal_entropy1(H):
n = np.shape(H)[0]
nom = np.log2(n*1.0)
eig = linalg.eigvals(H).real
Z = np.sum(eig)
S1 = np.log2(Z)
S2 = 0.0
# Due to the calculation accuracy problem, the
# condition in Numpy is used to brush the elements
# less than or equal to 0 in eig and replace it with 1.
# In fact, the Laplace matrix has no eigenvalues less than 0.
eig[eig <= 0] = 1
'''
for i in range(len(eig)):
if eig[i] > 0:
S2 = S2 + eig[i]*np.log(eig[i])
'''
S2 = np.sum(eig*np.log(eig))
S = S1 - S2/(Z*np.log(2.0))
return S/nom
def cal_entropy2(beta,H):
n = np.shape(H)[0]
nom = np.log2(n*1.0)
eig = linalg.eigvals(H).real
Z = np.sum(np.exp(-beta*eig), dtype=np.float64)
S1 = np.log2(Z)
S2 = (np.sum(beta*eig*np.exp(-beta*eig), dtype=np.float64))/(Z*np.log(2.0))
S = S1 + S2
return S/nom
#============================================
#==Calculation of Jensen-Shannon divergence==
def cal_JSD(p1,p2):
rho = (p1 + p2)/2
eig1 = linalg.eigvals(p1).real
eig2 = linalg.eigvals(p2).real
eig = linalg.eigvals(rho).real
sp = 0.0
eig1[eig1 <= 0] = 1
eig2[eig2 <= 0] = 1
eig[eig <= 0] = 1
'''
for i in range(len(eig)):
if eig[i] > 0:
sp = sp + eig[i]*np.log2(eig[i])
'''
s1 = -np.sum(eig1*np.log2(eig1))
s2 = -np.sum(eig2*np.log2(eig2))
sp = -np.sum(eig*np.log2(eig))
DJS = sp - (s1 + s2)/2
return DJS
#============================================