SiGhs 0.0.1__tar.gz

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.
sighs-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: SiGhs
3
+ Version: 0.0.1
4
+ Summary: A package for determining whether the difference between two graphs are significant
5
+ Home-page: https://github.com/wsloneker/SiGhs
6
+ Author: WhitneySloneker
7
+ Author-email: whitney_sloneker@brown.edu
8
+ License: >=3.13.5
9
+ Description-Content-Type: text/markdown
10
+ Requires-Dist: bokeh>=3.1.6
11
+ Requires-Dist: chromedriver>=2.24.1
12
+ Requires-Dist: geckodriver_autoinstaller>=0.1.0
13
+ Requires-Dist: graphviz>=0.21
14
+ Requires-Dist: igraph>=1.0.0
15
+ Requires-Dist: iqplot>=0.3.7
16
+ Requires-Dist: joblib>=1.4.2
17
+ Requires-Dist: matplotlib>=3.10.0
18
+ Requires-Dist: netlsd>=1.0.2
19
+ Requires-Dist: networkx>=3.10.0
20
+ Requires-Dist: numba>=0.62.1
21
+ Requires-Dist: numpy>=2.1.3
22
+ Requires-Dist: pandas>=2.2.3
23
+ Requires-Dist: pydot>=4.0.1
24
+ Requires-Dist: torch>=2.9.0
25
+ Requires-Dist: tqdm>=4.67.1
26
+ Requires-Dist: scipy>=1.16.3
27
+ Requires-Dist: seaborn>=0.13.2
28
+ Requires-Dist: selenium>=3.02
29
+ Requires-Dist: selenium_chrome>=0.0.29
30
+ Requires-Dist: selenium_firefox>=2.0.8
31
+ Requires-Dist: webdriver-manager>=4.0.2
32
+ Dynamic: author
33
+ Dynamic: author-email
34
+ Dynamic: description
35
+ Dynamic: description-content-type
36
+ Dynamic: home-page
37
+ Dynamic: license
38
+ Dynamic: requires-dist
39
+ Dynamic: summary
40
+
41
+ # SiGhs
42
+
43
+ We present SiGhs (SIgnificance of GrapH DifferenceS), a pipeline that allows users to determine whether the difference between two input networks is significant. Users are able to incorporate their own difference metrics, with Bagrow & Bollt's difference method [Network Portrait Divergence](https://appliednetsci.springeropen.com/articles/10.1007/s41109-019-0156-x) as the default, as this is a method that does not require node correspondence and has the most consistently high power and low false positive rates of metrics tested on graphs considered.
44
+
45
+ We take advantage of the non-parametric randomization test to determine the significance: determining whether the difference between the input networks is larger than (1 - n)% of differences between randomized networks where n is the chosen significance level (i. e. 0.05). We allow users to chose from a set of configuration models to randomize graphs (Chung-Lu, LRA, Stubmatching, Curveball, and Maximum Entropy based methods). The default randomization method chosen is Chung-Lu, as this method has the best tradeoff on power and false positive rates on our experiments.
46
+
47
+ Currently, this implementation focuses on undirected, unweighted graphs.
48
+
49
+ This work has been accepted to the Asilomar Conference on Signals, Systems, and Computers.
sighs-0.0.1/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # SiGhs
2
+
3
+ We present SiGhs (SIgnificance of GrapH DifferenceS), a pipeline that allows users to determine whether the difference between two input networks is significant. Users are able to incorporate their own difference metrics, with Bagrow & Bollt's difference method [Network Portrait Divergence](https://appliednetsci.springeropen.com/articles/10.1007/s41109-019-0156-x) as the default, as this is a method that does not require node correspondence and has the most consistently high power and low false positive rates of metrics tested on graphs considered.
4
+
5
+ We take advantage of the non-parametric randomization test to determine the significance: determining whether the difference between the input networks is larger than (1 - n)% of differences between randomized networks where n is the chosen significance level (i. e. 0.05). We allow users to chose from a set of configuration models to randomize graphs (Chung-Lu, LRA, Stubmatching, Curveball, and Maximum Entropy based methods). The default randomization method chosen is Chung-Lu, as this method has the best tradeoff on power and false positive rates on our experiments.
6
+
7
+ Currently, this implementation focuses on undirected, unweighted graphs.
8
+
9
+ This work has been accepted to the Asilomar Conference on Signals, Systems, and Computers.
@@ -0,0 +1,80 @@
1
+ from collections import defaultdict
2
+ import networkx as nx
3
+ # from https://github.com/hbj153/normlap/tree/master/normlap
4
+
5
+ class Formatter:
6
+
7
+ @staticmethod
8
+ def edgelist_to_neighborhood(br):
9
+ relation = defaultdict(set)
10
+ for nodeArr in br:
11
+ relation[nodeArr[0]].add(nodeArr[1])
12
+ relation[nodeArr[1]].add(nodeArr[0])
13
+ return relation
14
+
15
+ @staticmethod
16
+ def neighborhood_to_edgelist(N):
17
+ '''
18
+ neighborhood_to_edgelist(N)
19
+
20
+ Convert node pairs in neighborhood format to edgelist format.
21
+
22
+ Parameters
23
+ ----------
24
+ N: Input network in neighborhood formation. For example, N = {"A": {"B", "C"},"B":{"A"},"C":{"A"}}
25
+
26
+ Returns
27
+ -------
28
+ edgelist: Output network in edgelist format like [("A","B"),("B","C")]
29
+
30
+ '''
31
+ edgelist = []
32
+ for nodeArr in N.keys():
33
+ for neighbor in N[nodeArr]:
34
+ if (nodeArr,neighbor) not in edgelist and (neighbor,nodeArr) not in edgelist:
35
+ edgelist.append(tuple(sorted((nodeArr,neighbor))))
36
+ return sorted(edgelist)
37
+
38
+ @staticmethod
39
+ def neighborhood_to_adjacency(N):
40
+ '''
41
+ neighborhood_to_adjacency(N)
42
+
43
+ Convert network in neighborhood format to adjacency matrix format.
44
+
45
+ Parameters
46
+ ----------
47
+ N: Input network in neighborhood formation. For example, N = {"A": {"B", "C"},"B":{"A"},"C":{"A"}}
48
+
49
+ Returns
50
+ -------
51
+ nodelist: sorted nodelist corresponds to the adjacency matrix.
52
+ A: Output network in adjacency matrix function.
53
+ '''
54
+ nodelist = sorted(N.keys())
55
+ edgelist = Formatter.neighborhood_to_edgelist(N)
56
+ G = nx.from_edgelist(edgelist)
57
+ A = nx.to_numpy_matrix(G,nodelist=nodelist)
58
+ return nodelist,A
59
+
60
+ @staticmethod
61
+ def edgelist_to_adjacency(edgelist):
62
+ '''
63
+ edgelist_to_adjacency(edgelist)
64
+
65
+ Convert network in edgelist format to adjacency matrix format.
66
+
67
+ Parameters
68
+ ----------
69
+ N: Input network in edgelist formation.
70
+
71
+ Returns
72
+ -------
73
+ nodelist: sorted nodelist corresponds to the adjacency matrix.
74
+ A: Output network in adjacency matrix function.
75
+ '''
76
+ N = Formatter.edgelist_to_neighborhood(edgelist)
77
+ nodelist = sorted(N.keys())
78
+ G = nx.from_edgelist(edgelist)
79
+ A = nx.to_numpy_matrix(G,nodelist=nodelist)
80
+ return nodelist,A
@@ -0,0 +1,195 @@
1
+ from .Formatter import Formatter
2
+ import copy
3
+ import numpy as np
4
+ # from https://github.com/hbj153/normlap/tree/master/normlap
5
+
6
+ class Helper:
7
+
8
+ def covert2id(elist):
9
+ """covert2id Convert the nodes in given list to node_ids, return the mapping.
10
+
11
+ Parameters
12
+ ----------
13
+ elist1 : list(tuple)
14
+ The edge list of network 1.
15
+ elist2 : list(tuple)
16
+ The edge list of network 2.
17
+
18
+ Returns
19
+ -------
20
+ dict
21
+ id2node, node2id mapping.
22
+ """
23
+ id2node = {}
24
+ node2id = {}
25
+
26
+ nodes = set([node for pair in elist for node in pair])
27
+
28
+ for i, node in enumerate(nodes):
29
+ id2node[i] = node
30
+ node2id[node] = i
31
+
32
+ return id2node, node2id
33
+
34
+ def cal_node_degree(G):
35
+ '''
36
+ cal_node_degree(G)
37
+
38
+ Calculate the node degree for a given network.
39
+
40
+ Parameters
41
+ ----------
42
+ G: Network in neighborhood format like Gdict = {"A": {"B", "C"},"B":{"A"},"C":{"A"}} or edgelist format.
43
+
44
+ Returns
45
+ -------
46
+ degrees: A dictionary with node degrees of each node. Example: {'A': 2, 'B': 1, 'C': 1}
47
+ '''
48
+ if type(G)==list:
49
+ Gdict = Formatter.edgelist_to_neighborhood(G)
50
+ else:
51
+ Gdict = G
52
+ degrees = {}
53
+ for i in Gdict:
54
+ degrees[i]=len(Gdict[i])
55
+ return degrees
56
+
57
+ def dict_remove_self(dic):
58
+ """dict_remove_self remove the self-loops in the given neighborhood list
59
+
60
+ Parameters
61
+ ----------
62
+ dic : dict
63
+ The network represented in the neighborhood list format. e.g. {"A": ["B","C"]}
64
+
65
+ Returns
66
+ -------
67
+ dict
68
+ The network represented in the neighborhood list format without self-loop.
69
+ """
70
+ dic1 = copy.deepcopy(dic)
71
+ todeletes = []
72
+ for node in dic1:
73
+ if node in dic1[node]:
74
+ dic1[node].remove(node)
75
+ # if node only have self-loop, delete the node
76
+ if not dic1[node]:
77
+ todeletes.append(node)
78
+ for todelete in todeletes:
79
+ del dic1[todelete]
80
+ return dic1
81
+
82
+ def dict_values(dict1,keys):
83
+ '''
84
+ dict_values(dict1,keys)
85
+
86
+ Return the values by the order of a given key list. If the key is not in the dictionary, 0 is assigned for the given key.
87
+
88
+ Parameters
89
+ ----------
90
+ dict1: Dictionary.
91
+ keys: a list of keys.
92
+
93
+ Returns
94
+ -------
95
+ dict_value: The values of dictionart following the order of given keys.
96
+ '''
97
+ degrees = []
98
+ for cur_key in keys:
99
+ if cur_key in dict1.keys():
100
+ degrees.append(dict1[cur_key])
101
+ else:
102
+ degrees.append(0)
103
+ #return [dict1[cur_key] for cur_key in keys]
104
+ return degrees
105
+
106
+ def sort_elist(elist,strip=True,selfLink=False):
107
+ '''
108
+ strip: if True, the gene name will change from "YAL034W-A" to "YAL034WA"
109
+ selfLink: if False, self-interactions will be removed from the edgelist.
110
+ '''
111
+ if len(elist)==0 or type(elist[0][0])!=str: return list(set(sorted([tuple(sorted(x)) for x in elist])))
112
+
113
+ if strip==True:
114
+ res = list(set(sorted([tuple(sorted([x[0].replace("-",""),x[1].replace("-","")])) for x in elist])))
115
+ #res = list(set(sorted([tuple(sorted([x[0].split("-")[0],x[1].split("-")[0]])) for x in elist])))
116
+ else:
117
+ res = list(set(sorted([tuple(sorted(x)) for x in elist])))
118
+
119
+ if selfLink==False:
120
+ res = [pair for pair in res if pair[0]!=pair[1]]
121
+
122
+ return res
123
+
124
+ def count_overlap(elist1,elist2):
125
+ """count_overlap Conut the number of overlap between two list.
126
+
127
+ Parameters
128
+ ----------
129
+ elist1 : list(tuple)
130
+ The edgelist of network 1.
131
+ elist2 : list(tuple)
132
+ The edgelist of network 2.
133
+
134
+ Returns
135
+ -------
136
+ int
137
+ Number of overlap between the two networks.
138
+ """
139
+ return len(set(elist1).intersection(elist2))
140
+
141
+ def find_selfNodes(a1dict):
142
+ '''
143
+ Find nodes that have self-interations in a given dictionary.
144
+ '''
145
+ selfNodes = []
146
+ for node in a1dict:
147
+ if node in a1dict[node]:
148
+ selfNodes.append(node)
149
+ return selfNodes
150
+
151
+ def cal_score(ms,bs,bes,cs,ces):
152
+ """cal_score Calculate the normalized overlap score and its standard deviation.
153
+ f = (m-b)/(c-b)
154
+ m is constant
155
+
156
+ Parameters
157
+ ----------
158
+ ms : float or list
159
+ Observed overlap.
160
+ bs : float or list
161
+ Negative benchmark.
162
+ bes : float or list
163
+ Standard deviation of the negative benchmark.
164
+ cs : float or list
165
+ Positive benchmark.
166
+ ces : float or list
167
+ Standard deviation of the positive benchmark.
168
+
169
+ Returns
170
+ -------
171
+ float, float or list,list
172
+ scores,score_sigmas
173
+ """
174
+ '''
175
+
176
+ '''
177
+ scores = []
178
+ score_sigmas = []
179
+
180
+ # if pass integers
181
+ if type(ms)==int:
182
+ ms,bs,bes,cs,ces = [ms],[bs],[bes],[cs],[ces]
183
+
184
+ # if pass arrays
185
+ for m,b,be,c,ce in zip(ms,bs,bes,cs,ces):
186
+ if c-b != 0:
187
+ score = (m-b)/(c-b)
188
+ score_sigma = (1/(c-b)**2)*np.sqrt((m-c)**2*be**2+(b-c)**2*ce**2)
189
+ else:
190
+ score = None
191
+ score_sigma = None
192
+ scores.append(score)
193
+ score_sigmas.append(score_sigma)
194
+
195
+ return scores,score_sigmas
@@ -0,0 +1,293 @@
1
+ from .Helper import Helper
2
+ from .Formatter import Formatter
3
+ from .RandomNetwork import RandomNetwork
4
+ from .RandomSubnetwork import RandomSubnetwork
5
+ import numpy as np
6
+ import scipy
7
+
8
+ # @TODO: add function to generate random network based on the optimized alpha
9
+ # from https://github.com/hbj153/normlap/tree/master/normlap
10
+
11
+ class Pipeline:
12
+ """ Pipeline for comparing overlap between two networks.
13
+ This pipeline uses the default criterion for updating alphas as follows:
14
+ 1. The alphas for positive benchmark stop updating when the difference between the current and previous pos mean is less than 1.
15
+ 2. The alphas for negative benchmark stop updating when the difference between the current and previous neg mean is less than 1.
16
+ """
17
+
18
+ def __init__(self,elist1:list, elist2:list, poollist: list=None) -> None:
19
+ """__init__ initialize the pipeline
20
+
21
+ Parameters
22
+ ----------
23
+ elist1 : list
24
+ network1 in edge list format.
25
+ elist2 : list
26
+ network2 in edge list format.
27
+ poollist : list, optional
28
+ The pool of generating the instance, by default None, meaning the pool is the union of the two network.
29
+ """
30
+ # if the pool is not given
31
+ if poollist == None:
32
+ self.poollist = list(set(elist1).union(elist2))
33
+ else:
34
+ self.poollist = poollist
35
+
36
+ self.pos_iter = 1000
37
+ self.neg_iter = 1000
38
+
39
+ # convert node to node_ids
40
+ self.id2node, self.node2id = Helper.covert2id(self.poollist)
41
+ self.elist1 = [(self.node2id[node1],self.node2id[node2]) for node1,node2 in elist1]
42
+ self.elist2 = [(self.node2id[node1],self.node2id[node2]) for node1,node2 in elist2]
43
+ self.poollist = [(self.node2id[node1],self.node2id[node2]) for node1,node2 in self.poollist]
44
+
45
+ # convert to neighborhood
46
+ self.a1dict = Formatter.edgelist_to_neighborhood(self.elist1)
47
+ self.a2dict = Formatter.edgelist_to_neighborhood(self.elist2)
48
+
49
+ # observed overlap
50
+ self.obs = Helper.count_overlap(self.elist1, self.elist2)
51
+
52
+ self.pos_mean = None
53
+ self.neg_mean = None
54
+
55
+ def get_pos_instance(self, idx: int=0):
56
+ """get_pos_instance Generate an instance of positive benchmark.
57
+
58
+ Parameters
59
+ ----------
60
+ aelist : list, optional
61
+ The pool of generating the instance, by default None, meaning the pool is the union of the two network.
62
+ idx : int, optional
63
+ The index of the reference network, by default 0, meaning the instance has the same degree sequence with network1;
64
+ else, the instance has the same degree sequecne with network2.
65
+
66
+ Returns
67
+ -------
68
+ list(tuple)
69
+ An instance of the positive benchmark in egde list format.
70
+ """
71
+
72
+ ## positive benchmark
73
+ aelist = self.poollist
74
+ adict = Formatter.edgelist_to_neighborhood(aelist)
75
+ if idx==0:
76
+ alphas,_ = RandomSubnetwork.optimize_alpha(adict,self.a1dict,iters=self.pos_iter,probeNode=0)
77
+ P = RandomSubnetwork.cal_probability(aelist,self.elist1,alphas=alphas)
78
+ else:
79
+ alphas,_ = RandomSubnetwork.optimize_alpha(adict,self.a2dict,iters=self.pos_iter,probeNode=0)
80
+ P = RandomSubnetwork.cal_probability(aelist,self.elist2,alphas=alphas)
81
+ Gpos = RandomSubnetwork.construct_sample_network(P)
82
+ Gpos = [(self.id2node[node1],self.id2node[node2])for node1,node2 in Gpos]
83
+ return Gpos
84
+
85
+ def get_neg_instance(self, idx: int=0):
86
+ """get_neg_instance Generate an instance of negative benchmark.
87
+
88
+ Parameters
89
+ ----------
90
+ idx : int, optional
91
+ The index of the reference network, by default 0, meaning the instance has the same degree sequence with network1;
92
+ else, the instance has the same degree sequecne with network2.
93
+
94
+ Returns
95
+ -------
96
+ list(tuple)
97
+ An instance of the negative benchmark in egde list format.
98
+ """
99
+
100
+ ## negative benchmark
101
+ if idx==0:
102
+ alphas_zero = RandomNetwork.optimize_alpha(self.a1dict,iters=self.neg_iter)
103
+ selfNodes = Helper.find_selfNodes(self.a1dict)
104
+ Pij,nodelist = RandomNetwork.cal_Pij(alphas_zero,selfNodes)
105
+ else:
106
+ alphas_zero = RandomNetwork.optimize_alpha(self.a2dict,iters=self.neg_iter)
107
+ selfNodes = Helper.find_selfNodes(self.a2dict)
108
+ Pij,nodelist = RandomNetwork.cal_Pij(alphas_zero,selfNodes)
109
+ Gneg = RandomNetwork.construct_random_network(Pij,nodelist,selfNodes)
110
+ Gneg = [(self.id2node[node1],self.id2node[node2])for node1,node2 in Gneg]
111
+ return Gneg
112
+
113
+ def get_pos_benchmark(self, iters_start:int=1000, pos_change_limit=1, iter_spacing:int=1000, max_iterations:int=20000):
114
+ """get_pos_benchmark Generate the positive benchmark.
115
+
116
+ Parameters
117
+ ----------
118
+ iters_start : int, optional
119
+ The number of iterations to start with, by default 1000.
120
+ pos_change_limit : int, optional
121
+ The change limit for updating the number of iterations, by default 1.
122
+ iter_spacing : int, optional
123
+ The spacing between two iterations, by default 1000.
124
+ max_iterations : int, optional
125
+ The maximum number of iterations, by default 20000.
126
+
127
+ Returns
128
+ -------
129
+ pos_mean : float
130
+ The mean of the positive benchmark.
131
+ pos_sigma : float
132
+ The standard deviation of the positive benchmark.
133
+ """
134
+ self.pos1_mean, self.pos1_sigma, self.cur_iter_pos1 = RandomSubnetwork.optimize_pos(
135
+ self.elist1, self.elist2, iters_start=iters_start, pos_change_limit=pos_change_limit, iter_spacing=iter_spacing, max_iterations=max_iterations)
136
+ self.pos2_mean, self.pos2_sigma, self.cur_iter_pos2 = RandomSubnetwork.optimize_pos(
137
+ self.elist2, self.elist1, iters_start=iters_start, pos_change_limit=pos_change_limit, iter_spacing=iter_spacing, max_iterations=max_iterations)
138
+
139
+ # select the positive benchmark that is closer to the observed overlap
140
+ z1 = abs((self.obs - self.pos1_mean) / self.pos1_sigma)
141
+ z2 = abs((self.obs - self.pos2_mean) / self.pos2_sigma)
142
+
143
+ if z1 < z2:
144
+ self.pos_mean, self.pos_sigma = self.pos1_mean, self.pos1_sigma
145
+ else:
146
+ self.pos_mean, self.pos_sigma = self.pos2_mean, self.pos2_sigma
147
+
148
+ return self.pos_mean, self.pos_sigma
149
+
150
+ def get_neg_benchmark(self, iters_start:int=100, neg_change_limit=1, iter_spacing:int=1000, max_iterations:int=5000):
151
+ """get_neg_benchmark Generate the negative benchmark.
152
+
153
+ Parameters
154
+ ----------
155
+ iters_start : int, optional
156
+ The number of iterations to start with, by default 100.
157
+ neg_change_limit : int, optional
158
+ The change limit for updating the number of iterations, by default 1.
159
+ iter_spacing : int, optional
160
+ The spacing between two iterations, by default 1000.
161
+ max_iterations : int, optional
162
+ The maximum number of iterations, by default 5000.
163
+
164
+ Returns
165
+ -------
166
+ neg_mean : float
167
+ The mean of the negative benchmark.
168
+ neg_sigma : float
169
+ The standard deviation of the negative benchmark.
170
+ """
171
+ self.neg1_mean, self.neg1_sigma, self.cur_iter_neg1 = RandomNetwork.optimize_neg(
172
+ self.elist1, self.elist2, iters_start=iters_start, neg_change_limit=neg_change_limit, iter_spacing=iter_spacing, max_iterations=max_iterations)
173
+ self.neg2_mean, self.neg2_sigma, self.cur_iter_neg2 = RandomNetwork.optimize_neg(
174
+ self.elist2, self.elist1, iters_start=iters_start, neg_change_limit=neg_change_limit, iter_spacing=iter_spacing, max_iterations=max_iterations)
175
+
176
+ # select the negative benchmark that is closer to the observed overlap
177
+ z1 = abs((self.obs - self.neg1_mean) / self.neg1_sigma)
178
+ z2 = abs((self.obs - self.neg2_mean) / self.neg2_sigma)
179
+
180
+ if z1 < z2:
181
+ self.neg_mean, self.neg_sigma = self.neg1_mean, self.neg1_sigma
182
+ else:
183
+ self.neg_mean, self.neg_sigma = self.neg2_mean, self.neg2_sigma
184
+
185
+ return self.neg_mean, self.neg_sigma
186
+
187
+ def construct_pos_benchmark(self):
188
+ """
189
+ Note that this function is deprecated. Please use get_pos_benchmark instead.
190
+ construct_pos_benchmark Construct the positive benchmark for the given two networks.
191
+
192
+ Parameters
193
+ ----------
194
+ aelist : list, optional
195
+ The pool of generating the instance, by default None, meaning the pool is the union of the two network.
196
+
197
+ Returns
198
+ -------
199
+ float,float
200
+ pos_mean,pos_sigma
201
+ """
202
+ aelist = self.poollist
203
+ adict = Formatter.edgelist_to_neighborhood(aelist)
204
+
205
+ alphas1,_ = RandomSubnetwork.optimize_alpha(adict,self.a1dict,iters=self.pos_iter,probeNode=0)
206
+ alphas2,_ = RandomSubnetwork.optimize_alpha(adict,self.a2dict,iters=self.pos_iter,probeNode=0)
207
+ # average probability
208
+ P1 = RandomSubnetwork.cal_probability(aelist,self.elist1,alphas=alphas1)
209
+ P2 = RandomSubnetwork.cal_probability(aelist,self.elist2,alphas=alphas2)
210
+ # variance probability
211
+ Pv1 = {link: P1[link]*(1-P1[link]) for link in P1 }
212
+ Pv2 = {link: P2[link]*(1-P2[link]) for link in P2 }
213
+ # benchmarks
214
+ # one side
215
+ self.pos1_mean = sum([P1.get(link,0) for link in self.elist2])
216
+ self.pos1_sigma = np.sqrt(sum([Pv1.get(link,0) for link in self.elist2])) + 0.00001 # avoid zero
217
+ self.pos2_mean = sum([P2.get(link,0) for link in self.elist1])
218
+ self.pos2_sigma = np.sqrt(sum([Pv2.get(link,0) for link in self.elist1])) + 0.00001 # avoid zero
219
+ z1 = abs((self.obs - self.pos1_mean) / self.pos1_sigma)
220
+ z2 = abs((self.obs - self.pos2_mean) / self.pos2_sigma)
221
+
222
+ if z1<z2:
223
+ self.pos_mean, self.pos_sigma = self.pos1_mean,self.pos1_sigma
224
+ else:
225
+ self.pos_mean, self.pos_sigma = self.pos2_mean,self.pos2_sigma
226
+
227
+ return self.pos_mean, self.pos_sigma
228
+
229
+ def construct_neg_benchmark(self):
230
+ """
231
+ Note that this function is deprecated. Please use get_neg_benchmark instead.
232
+ """
233
+
234
+ # neg1
235
+ alphas1_neg = RandomNetwork.optimize_alpha(self.a1dict,iters=self.neg_iter)
236
+ # only calculate the links in the comparing network(a2elist). Other links will never overlap with the comparing network.
237
+ P1 = RandomSubnetwork.cal_probability(self.elist2,self.elist1,alphas1_neg)
238
+ Pv1 = {link: P1[link]*(1-P1[link]) for link in P1 }
239
+ # one side
240
+ self.neg1_mean = sum([P1.get(link,0) for link in self.elist2])
241
+ self.neg1_sigma = np.sqrt(sum([Pv1.get(link,0) for link in self.elist2])) + 0.00001 # avoid zero
242
+
243
+ # neg2
244
+ alphas2_neg = RandomNetwork.optimize_alpha(self.a2dict,iters=self.neg_iter)
245
+ # only calculate the links in the comparing network(a1elist). Other links will never overlap with the comparing network.
246
+ P2 = RandomSubnetwork.cal_probability(self.elist1,self.elist2,alphas2_neg)
247
+ Pv2 = {link: P2[link]*(1-P2[link]) for link in P2 }
248
+ # one side
249
+ self.neg2_mean = sum([P2.get(link,0) for link in self.elist1])
250
+ self.neg2_sigma = np.sqrt(sum([Pv2.get(link,0) for link in self.elist1])) + 0.00001 # avoid zero
251
+
252
+ z1 = abs((self.obs - self.neg1_mean) / self.neg1_sigma)
253
+ z2 = abs((self.obs - self.neg2_mean) / self.neg2_sigma)
254
+
255
+ if z1<z2:
256
+ self.neg_mean, self.neg_sigma = self.neg1_mean,self.neg1_sigma
257
+ else:
258
+ self.neg_mean, self.neg_sigma = self.neg2_mean,self.neg2_sigma
259
+
260
+ return self.neg_mean, self.neg_sigma
261
+
262
+ def plot(self):
263
+ pass
264
+
265
+ def show_results(self, printOn: bool=True):
266
+ if not self.pos_mean:
267
+ print("The get_pos_benchmark function has not been called yet. The results will be calculated based on default parameters.")
268
+ self.pos_mean, self.pos_sigma = self.get_pos_benchmark()
269
+ if not self.neg_mean:
270
+ print("The get_neg_benchmark function has not been called yet. The results will be calculated based on default parameters.")
271
+ self.neg_mean, self.neg_sigma = self.get_neg_benchmark()
272
+
273
+ self.neg_z = (self.obs-self.neg_mean)/self.neg_sigma if self.neg_sigma!=0 else np.nan
274
+ self.neg_p = scipy.stats.norm.sf(self.neg_z)
275
+ self.pos_z = (self.obs-self.pos_mean)/self.pos_sigma if self.pos_sigma!=0 else np.nan
276
+ self.pos_p = 1 - scipy.stats.norm.sf(self.pos_z)
277
+ self.normlap, self.normlap_sigma = Helper.cal_score(self.obs,self.neg_mean,self.neg_sigma,self.pos_mean,self.pos_sigma)
278
+ self.normlap, self.normlap_sigma = self.normlap[0], self.normlap_sigma[0]
279
+
280
+ labels = ["Observed overlap","Neg_mean","Neg_sigma","Neg_p","Pos_mean","Pos_sigma","Pos_p","Normlap","Normlap_sigma"]
281
+ res = [self.obs, self.neg_mean, self.neg_sigma, self.neg_p, self.pos_mean, self.pos_sigma, self.pos_p,self.normlap,self.normlap_sigma]
282
+ if printOn:
283
+ for label, num in zip(labels,res):
284
+ if num != np.nan or None:
285
+ print(label+': ', '%.2f'%num)
286
+ else:
287
+ print(label+': None')
288
+
289
+ return labels, res
290
+
291
+
292
+
293
+