Skip to content

Local

These are utility functions used to restrict analyses to neighborhoods.

neighborhood(adj, v, pre=True, post=True, include_center=True, return_neighbors=False)

Gets the neighborhood of v in adj

Parameters:

Name Type Description Default
adj sparse matrix or 2d array

The adjacency matrix of the graph

required
pre bool

If True compute the submatrix on the nodes mapping to v (the in-neighbors of v)

True
post bool

If True compute the submatrix on the nodes mapping to v (the out-neighbors of v)

True
include_center bool

If True include v in the neighborhood

True
return_neighbors bool

If True also return the indices in adj of the neighbors of v

False

Returns:

Type Description
matrix (sparse if adj is sparse)

If pre = post = True it returns the full neighbohood of v

If pre = True and post = Falseit returns the in-neighborhood of v

If pre = False and post = Trueit returns the out-neighborhood of v

If include_center = True, then v is the first indexed node in the matrix, else it is excluded

Source code in src/connalysis/network/local.py
 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
def neighborhood(adj, v, pre=True, post=True, include_center=True, return_neighbors=False):
    """Gets the neighborhood of v in adj
            Parameters
            ----------
            adj : sparse matrix or 2d array
                The adjacency matrix of the graph
            pre : bool
                If ``True`` compute the submatrix on the nodes mapping to v (the in-neighbors of v)
            post : bool
                If ``True`` compute the submatrix on the nodes mapping to v (the out-neighbors of v)
            include_center : bool
                If ``True`` include v in the neighborhood
            return_neighbors : bool
                If ``True`` also return the indices in adj of the neighbors of v

            Returns
            -------
            matrix (sparse if adj is sparse)
                If pre = post = ``True`` it returns the full neighbohood of v

                If pre = ``True`` and post = ``False``it returns the in-neighborhood of v

                If pre = ``False`` and post = ``True``it returns the out-neighborhood of v

                If include_center = ``True``, then v is the first indexed node in the matrix,
                else it is excluded
        """
    nb_df=neighborhood_indices(adj, pre=pre, post=post, all_nodes=False, centers=np.array([v]))
    if sp.issparse(adj): adj=adj.tocsr()
    nb_ind = nb_df.loc[v]
    if include_center:
        nb_ind = np.append(v, nb_ind)
    if return_neighbors:
        return submat_at_ind(adj, nb_ind), nb_ind
    else:
        return submat_at_ind(adj, nb_ind)

neighborhood_indices(M, pre=True, post=True, all_nodes=True, centers=None)

Computes the indices of the neighbors of the nodes listed in centers

Parameters:

Name Type Description Default
M sparse matrix or 2d array

The adjacency matrix of the graph

required
pre bool

If True compute the nodes mapping to the nodes in centers (the in-neighbors of the centers)

True
post bool

If True compute the nodes that the centers map to (the out-neighbors of the centers)

True
all_nodes bool

If True compute the neighbors of all nodes in M, if False compute only the neighbors of the nodes listed in centers

True
centers 1d-array

The indices of the nodes for which the neighbors need to be computed. This entry is ignored if all_nodes is True and required if all_nodes is False.

None

Returns:

Type Description
data frame

indices: range from 0 to M.shape[0] if all_nodes is set to True, otherwise centers.

values: the neighbors of each center in the indices.

Raises:

Type Description
AssertionError

If the matrix M is not square

AssertionError

If both pre and post are False

AssertionError

If all_nodes is False but centers are not provided

Source code in src/connalysis/network/local.py
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
def neighborhood_indices(M, pre=True, post=True, all_nodes=True, centers=None):
    """Computes the indices of the neighbors of the nodes listed in centers

        Parameters
        ----------
        M : sparse matrix or 2d array
            The adjacency matrix of the graph
        pre : bool
            If ``True`` compute the nodes mapping to the nodes in centers (the in-neighbors of the centers)
        post : bool
            If ``True`` compute the nodes that the centers map to (the out-neighbors of the centers)
        all_nodes : bool
            If ``True`` compute the neighbors of all nodes in M, if ``False`` compute only the neighbors of the nodes
            listed in centers
        centers : 1d-array
            The indices of the nodes for which the neighbors need to be computed.  This entry is ignored if
            all_nodes is ``True`` and required if all_nodes is ``False``.

        Returns
        -------
        data frame
            indices: range from 0 to ``M.shape[0]`` if all_nodes is set to ``True``, otherwise centers.

            values: the neighbors of each center in the indices.

        Raises
        ------
        AssertionError
            If the matrix M is not square
        AssertionError
            If both pre and post are ``False``
        AssertionError
            If all_nodes is ``False`` but centers are not provided

    """
    assert M.shape[0] == M.shape[1], "The matrix is not square"
    assert np.logical_or(pre, post), "At least one of the pre/post parameters must be True"
    if all_nodes: centers = np.arange(M.shape[0])
    assert centers is not None, "If all_nodes == False and array of centers must be provided"

    M = M.tocoo() if sp.issparse(M) else sp.coo_matrix(M)

    base_df = pd.DataFrame({"row": M.row, "col": M.col})
    idxx = pd.Index(centers, name="center")
    nb_df = pd.Series([[]] * centers.shape[0], index=idxx, name="neighbors")
    # Restriction to requested centers
    if not all_nodes: res_df = base_df.apply(lambda _x: np.isin(_x, centers))

    if post:
        df = base_df[res_df['row']] if not all_nodes else base_df
        new_df = df.rename(columns={"row": "center", "col": "neighbors"}).groupby("center")["neighbors"].apply(list)
        nb_df = nb_df.combine(new_df, np.union1d, fill_value=[])
    if pre:
        df = base_df[res_df['col']] if not all_nodes else base_df
        new_df = df.rename(columns={"col": "center", "row": "neighbors"}).groupby("center")["neighbors"].apply(list)
        nb_df = nb_df.combine(new_df, np.union1d, fill_value=[])
    return nb_df.apply(lambda _x: _x.astype(int))

neighborhood_of_set(M, node_set, pre=True, post=True, include_centers=True, return_neighbors=False)

Gets the neighborhood of the nodes in node_set

Parameters:

Name Type Description Default
M sparse matrix or 2d array

The adjacency matrix of the graph

required
node_set array

The indices of the nodes of which the neighborhood will be computed

required
pre bool

If True compute the submatrix on the nodes mapping to node_set (the in-neighbors of node_set)

True
post bool

If True compute the submatrix on the nodes that node_set maps to (the out-neighbors of node_set)

True
include_center bool

If True include node_set in the graph

required
return_neighbors bool

If True also return the indices in M of the neighbors of node_set

False

Returns:

Type Description
matrix (sparse if M is sparse)

If pre = post = True it returns the full neighbohood of node_set

If pre = True and post = Falseit returns the in-neighborhood of node_set

If pre = False and post = Trueit returns the out-neighborhood of node_set

Source code in src/connalysis/network/local.py
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
def neighborhood_of_set(M, node_set, pre=True, post=True, include_centers=True, return_neighbors=False):
    """Gets the neighborhood of the nodes in node_set
            Parameters
            ----------
            M : sparse matrix or 2d array
                The adjacency matrix of the graph
            node_set : array
                The indices of the nodes of which the neighborhood will be computed
            pre : bool
                If ``True`` compute the submatrix on the nodes mapping to node_set (the in-neighbors of node_set)
            post : bool
                If ``True`` compute the submatrix on the nodes that node_set maps to (the out-neighbors of node_set)
            include_center : bool
                If ``True`` include node_set in the graph
            return_neighbors : bool
                If ``True`` also return the indices in M of the neighbors of node_set

            Returns
            -------
            matrix (sparse if M is sparse)
                If pre = post = ``True`` it returns the full neighbohood of node_set

                If pre = ``True`` and post = ``False``it returns the in-neighborhood of node_set

                If pre = ``False`` and post = ``True``it returns the out-neighborhood of node_set
    """
    nodes=neighborhood_of_set_indices(M, node_set, pre, post)
    if include_centers:
        nodes=np.unique(np.concatenate([node_set, nodesA]))
    if isinstance(M, sp.coo_matrix): M=M.tocsr()
    # Slicing in different ways depending on matrix type
    if isinstance(M, np.ndarray): nbd= M[np.ix_(nodes, nodes)]
    if isinstance(M, sp.csr_matrix): nbd= M[nodes].tocsc()[:, nodes]
    if isinstance(M, sp.csc_matrix): nbd= M[:,nodes].tocsr()[nodes]
    if return_neighbors: return nbd, nodes
    else: return nbd

neighborhood_of_set_indices(M, node_set, pre=True, post=True)

Computes the indices of the neighbors of the nodes in node_set

Parameters:

Name Type Description Default
M sparse matrix or 2d array

The adjacency matrix of the graph

required
pre bool

If True compute the nodes mapping to the nodes in node_set (the in-neighbors of the node_set)

True
post bool

If True compute the nodes that the centers map to node_set (the out-neighbors of the node_set)

True
node_set 1d-array

The indices of the nodes for which the neighbors need to be computed.

required

Returns:

Type Description
array

indices of the neighbhors of node_set

Raises:

Type Description
AssertionError

If both pre and post are False

Source code in src/connalysis/network/local.py
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
def neighborhood_of_set_indices(M, node_set, pre=True, post=True):
    """Computes the indices of the neighbors of the nodes in node_set

            Parameters
            ----------
            M : sparse matrix or 2d array
                The adjacency matrix of the graph
            pre : bool
                If ``True`` compute the nodes mapping to the nodes in node_set (the in-neighbors of the node_set)
            post : bool
                If ``True`` compute the nodes that the centers map to node_set (the out-neighbors of the node_set)
            node_set : 1d-array
                The indices of the nodes for which the neighbors need to be computed.

            Returns
            -------
            array
                indices of the neighbhors of node_set

            Raises
            ------
            AssertionError
                If both pre and post are ``False``
    """
    assert np.logical_or(pre, post), "At least one of the pre/post parameters must be True"
    return np.unique(np.concatenate(neighborhood_indices(M,pre=pre,post=post,all_nodes=False,centers=node_set).values))

neighbourhood(v, matrix)

Computes the matrix induced by the neighbours of v in graph with adjacency matrix matrix

Parameters:

Name Type Description Default
v int

the index of the vertex

required
matrix matrix

the adjacency matrix of the graph

required

Returns:

Type Description
matrix

the adjaceny matrix of the neighbourhood of v in matrix

Source code in src/connalysis/network/local.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
def neighbourhood(v, matrix): #Previous name # def tribe(v, matrix):
    # TODO: Needs to be deleted
    """Computes the matrix induced by the neighbours of v in graph with adjacency matrix matrix

    Parameters
    ----------
    v : int
        the index of the vertex
    matrix : matrix
        the adjacency matrix of the graph

    Returns
    -------
    matrix
        the adjaceny matrix of the neighbourhood of v in matrix
    """
    #print(matrix.getformat())
    nhbd = neighbours(v, matrix)
    return matrix[np.ix_(nhbd,nhbd)]

neighbours(v, matrix)

Computes the neighbours of v in graph with adjacency matrix matrix

Parameters:

Name Type Description Default
v int

the index of the vertex

required
matrix matrix

the adjacency matrix of the graph

required

Returns:

Type Description
list

the list of neighbours of v in matrix

Source code in src/connalysis/network/local.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def neighbours(v, matrix):
    #TODO: Delete redundant
    """Computes the neighbours of v in graph with adjacency matrix matrix

    Parameters
    ----------
    v : int
        the index of the vertex
    matrix : matrix
        the adjacency matrix of the graph

    Returns
    -------
    list
        the list of neighbours of v in matrix
    """
    neighbours = np.unique(np.concatenate((np.nonzero(matrix[v])[0],np.nonzero(np.transpose(matrix)[v])[0])))
    neighbours.sort(kind='mergesort')
    return np.concatenate((np.array([v]),neighbours))

properties_at_neighborhoods(adj, func_config, pre=True, post=True, include_center=True, all_nodes=True, centers=None)

Computes the properties in func_config on the neighborhoods of the centers within adj

Parameters:

Name Type Description Default
adj sparse matrix or 2d array

The adjacency matrix of the graph

required
func_config dict

Configuration dictionary of functions to be computed on neihgborhoods

required
pre bool

If True include the nodes mapping to the nodes in centers

True
post bool

If True include the nodes that the centers map to

True
include_center bool

If True include the centers

True
all_nodes bool

If True compute func on the neighborhoods of all nodes in adj,

If False compute it only the neighborhoods of the nodes listed in centers

True
centers 1d-array

The indices of the nodes to consider. This entry is ignored if all_nodes is True and required if all_nodes is False.

None

Returns:

Type Description
dict

keys: keys of func_config

values: dict with

keys: range from 0 to ``M.shape[0]`` if all_nodes is set to ``True``, otherwise centers

values: the output of ``func`` in each neighborhood of the nodes in centers
Source code in src/connalysis/network/local.py
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
def properties_at_neighborhoods(adj, func_config, pre=True, post=True, include_center=True,
                                all_nodes=True, centers=None):
    """Computes the properties in func_config on the neighborhoods of the centers within adj

            Parameters
            ----------
            adj : sparse matrix or 2d array
                The adjacency matrix of the graph
            func_config : dict
                Configuration dictionary of functions to be computed on neihgborhoods
            pre : bool
                If ``True`` include the nodes mapping to the nodes in centers
            post : bool
                If ``True`` include the nodes that the centers map to
            include_center : bool
                If ``True`` include the centers
            all_nodes : bool
                If ``True`` compute func on the neighborhoods of all nodes in adj,

                If ``False`` compute it only the neighborhoods of the nodes listed in centers
            centers : 1d-array
                The indices of the nodes to consider.  This entry is ignored if
                all_nodes is ``True`` and required if all_nodes is ``False``.

            Returns
            -------
            dict
                keys: keys of func_config

                values: dict with

                    keys: range from 0 to ``M.shape[0]`` if all_nodes is set to ``True``, otherwise centers

                    values: the output of ``func`` in each neighborhood of the nodes in centers
    """
    nb_df = neighborhood_indices(adj, pre=pre, post=post, all_nodes=all_nodes, centers=centers)
    if sp.issparse(adj): adj = adj.tocsr()  # TODO: Add warning of format?
    nbhd_values = {key: {} for key in func_config.keys()}
    for center in nb_df.index:
        nb_ind = nb_df.loc[center]
        if include_center: nb_ind = np.append(center, nb_ind)
        nbhd = submat_at_ind(adj, nb_ind)
        for key in func_config.keys():
            nbhd_values[key][center] = func_config[key]['function'](nbhd, **func_config[key]['kwargs'])
    return nbhd_values

property_at_neighborhoods(adj, func, pre=True, post=True, include_center=True, all_nodes=True, centers=None, **kwargs)

Computes the property func on the neighborhoods of the centers within adj

Parameters:

Name Type Description Default
adj sparse matrix or 2d array

The adjacency matrix of the graph

required
func function

Function computing a network theoretic property e.g., degree or simplex counts

required
pre bool

If True include the nodes mapping to the nodes in centers

True
post bool

If True include the nodes that the centers map to

True
include_center bool

If True include the centers

True
all_nodes bool

If True compute func on the neighborhoods of all nodes in adj,

If False compute it only the neighborhoods of the nodes listed in centers

True
centers 1d-array

The indices of the nodes to consider. This entry is ignored if all_nodes is True and required if all_nodes is False.

None

Returns:

Type Description
dict

keys: range from 0 to M.shape[0] if all_nodes is set to True, otherwise centers

values: the output of func in each neighborhood of the nodes in centers

Source code in src/connalysis/network/local.py
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
def property_at_neighborhoods(adj, func, pre=True, post=True,include_center=True,
                             all_nodes=True, centers=None, **kwargs):
    """Computes the property func on the neighborhoods of the centers within adj

            Parameters
            ----------
            adj : sparse matrix or 2d array
                The adjacency matrix of the graph
            func : function
                Function computing a network theoretic property e.g., degree or simplex counts
            pre : bool
                If ``True`` include the nodes mapping to the nodes in centers
            post : bool
                If ``True`` include the nodes that the centers map to
            include_center : bool
                If ``True`` include the centers
            all_nodes : bool
                If ``True`` compute func on the neighborhoods of all nodes in adj,

                If ``False`` compute it only the neighborhoods of the nodes listed in centers
            centers : 1d-array
                The indices of the nodes to consider.  This entry is ignored if
                all_nodes is ``True`` and required if all_nodes is ``False``.

            Returns
            -------
            dict
                keys: range from 0 to ``M.shape[0]`` if all_nodes is set to ``True``, otherwise centers

                values: the output of ``func`` in each neighborhood of the nodes in centers
    """
    nb_df=neighborhood_indices(adj, pre=pre, post=post, all_nodes=all_nodes, centers=centers)
    if sp.issparse(adj): adj=adj.tocsr()# TODO: Add warning of format!
    nbhd_values={}
    for center in nb_df.index:
        nb_ind = nb_df.loc[center]
        if include_center: nb_ind=np.append(center, nb_ind)
        nbhd=submat_at_ind(adj, nb_ind)
        #nbhd_values.loc[center]=func(nbhd, kwargs)
        nbhd_values[center]=func(nbhd, **kwargs)
    return nbhd_values

submat_at_ind(M, ind)

Computes the submatrix of M on the nondes indexed by ind

Parameters:

Name Type Description Default
M matrix

the adjacency matrix of the graph

required
ind 1d-array

the indices on which to slice the matrix M

required

Returns:

Type Description
matrix

the adjaceny matrix of the submatrix of M on the nodes in ind

Source code in src/connalysis/network/local.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def submat_at_ind(M, ind):
    """Computes the submatrix of M on the nondes indexed by ind

    Parameters
    ----------
    M : matrix
        the adjacency matrix of the graph
    ind : 1d-array
        the indices on which to slice the matrix M

    Returns
    -------
    matrix
        the adjaceny matrix of the submatrix of M on the nodes in ind
    """
    if sp.issparse(M): M=M.tocsr()
    return  M[ind][:, ind]