Skip to content

Functions for working with networks

This page describes functions contained in the network module. The functions are arranged by motivation, either from classic graph and network theory, or from topology.

Graph theory

These functions are classic graph theoretic functions.

centrality(self, sub_gids, kind = 'closeness', directed = False)

Compute a centrality of the graph. kind can be 'betweeness' or 'closeness'

Source code in src/connalysis/network/classic.py
59
60
61
62
63
64
def centrality(self, sub_gids, kind="closeness", directed=False):
    """Compute a centrality of the graph. `kind` can be 'betweeness' or 'closeness'"""
    if kind == "closeness":
        return self.closeness(sub_gids, directed)
    else:
        ValueError("Kind must be 'closeness'!")

closeness(adj, neuron_properties, directed = False)

Compute closeness centrality using sknetwork on all connected components or strongly connected component (if directed==True)

Source code in src/connalysis/network/classic.py
54
55
56
57
def closeness(adj, neuron_properties, directed=False):
    """Compute closeness centrality using sknetwork on all connected components or strongly connected
    component (if directed==True)"""
    return closeness_connected_components(adj, directed=directed)

closeness_connected_components(adj, neuron_properties = [], directed = False, return_sum = True)

Compute the closeness of each connected component of more than 1 vertex

Parameters:

Name Type Description Default
adj array_like

Adjacency matrix of the graph

required
directed bool

If True, will be computed using strongly connected components and directed closeness.

False
return_sum bool

If True, only one list will be returned, by summing over all the connected components.

True

Returns:

Type Description
array_like

A single array( if return_sum=True) or a list of arrays of shape n, containting closeness of vertices in that component, or 0 if the vertex is not in the component. Closeness cannot be zero otherwise.

Source code in src/connalysis/network/classic.py
 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
def closeness_connected_components(adj, neuron_properties=[], directed=False, return_sum=True):
    """Compute the closeness of each connected component of more than 1 vertex

    Parameters
    ----------
    adj : array_like
        Adjacency matrix of the graph
    directed : bool
        If `True`, will be computed using strongly connected components and directed closeness.
    return_sum : bool
        If `True`, only one list will be returned, by summing over all the connected components.


    Returns
    -------
    array_like
        A single array( if `return_sum=True`) or a list of arrays of shape `n`, containting closeness of vertices in that component, or 0 if the vertex is not in the component. Closeness cannot be zero otherwise.

    """
    import numpy as np
    from sknetwork.ranking import Closeness
    from scipy.sparse.csgraph import connected_components

    matrix=adj.toarray()
    if directed:
        n_comp, comp = connected_components(matrix, directed=True, connection="strong")
    else:
        n_comp, comp = connected_components(matrix, directed=False)
        matrix = matrix + matrix.T  # we need to make the matrix symmetric

    closeness = Closeness()  # if matrix is not symmetric automatically use directed
    n = matrix.shape[0]
    all_c = []
    for i in range(n_comp):
        c = np.zeros(n)
        idx = np.where(comp == i)[0]
        sub_mat = matrix[np.ix_(idx, idx)].tocsr()
        if sub_mat.getnnz() > 0:
            c[idx] = closeness.fit_transform(sub_mat)
            all_c.append(c)
    if return_sum:
        all_c = np.array(all_c)
        return np.sum(all_c, axis=0)
    else:
        return all_c

connected_components(adj, neuron_properties = [])

Returns a list of the size of the connected components of the underlying undirected graph on sub_gids, if None, compute on the whole graph

Source code in src/connalysis/network/classic.py
67
68
69
70
71
72
73
74
75
76
77
def connected_components(adj,neuron_properties=[]):
    """Returns a list of the size of the connected components of the underlying undirected graph on sub_gids,
    if None, compute on the whole graph"""
    import networkx as nx
    import numpy as np

    matrix=adj.toarray()
    matrix_und = np.where((matrix+matrix.T) >= 1, 1, 0)
    # TODO: Change the code from below to scipy implementation that seems to be faster!
    G = nx.from_numpy_matrix(matrix_und)
    return [len(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)]

core_number(adj, neuron_properties = [])

Returns k core of directed graph, where degree of a vertex is the sum of in degree and out degree

Source code in src/connalysis/network/classic.py
79
80
81
82
83
84
85
def core_number(adj, neuron_properties=[]):
    """Returns k core of directed graph, where degree of a vertex is the sum of in degree and out degree"""
    # TODO: Implement directed (k,l) core and k-core of underlying undirected graph (very similar to this)
    import networkx
    G = networkx.from_numpy_matrix(adj.toarray())
    # Very inefficient (returns a dictionary!). TODO: Look for different implementation
    return networkx.algorithms.core.core_number(G)

generate_degree_based_control(M, direction = 'efferent')

A shuffled version of a connectivity matrix that aims to preserve degree distributions. If direction = "efferent", then the out-degree is exactly preserved, while the in-degree is approximately preseved. Otherwise it's the other way around.

Source code in src/connalysis/network/classic.py
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
def generate_degree_based_control(M, direction="efferent"):
    """
    A shuffled version of a connectivity matrix that aims to preserve degree distributions.
    If direction = "efferent", then the out-degree is exactly preserved, while the in-degree is
    approximately preseved. Otherwise it's the other way around.
    """
    if direction == "efferent":
        M = M.tocsr()
        idxx = np.arange(M.shape[1])
        p_out = np.array(M.mean(axis=0))[0]
    elif direction == "afferent":
        M = M.tocsc()
        idxx = np.arange(M.shape[0])
        p_out = np.array(M.mean(axis=1))[:, 0]
    else:
        raise ValueError()

    for col in range(M.shape[1]):
        p = p_out.copy()
        p[col] = 0.0
        p = p / p.sum()
        a = M.indptr[col]
        b = M.indptr[col + 1]
        M.indices[a:b] = np.random.choice(idxx, b - a, p=p, replace=False)
    return M

Topology

These functions are topologically motivated.

at_weight_edges(weighted_adj, threshold, method = 'strength')

Returns thresholded network on edges :param method: distance returns edges with weight smaller or equal than thresh strength returns edges with weight larger or equal than thresh assumes csr format for weighted_adj

Source code in src/connalysis/network/topology.py
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
def at_weight_edges(weighted_adj, threshold, method="strength"):
    """ Returns thresholded network on edges
    :param method: distance returns edges with weight smaller or equal than thresh
                   strength returns edges with weight larger or equal than thresh
                   assumes csr format for weighted_adj"""
    data=weighted_adj.data
    data_thresh=np.zeros(data.shape)
    if method == "strength":
        data_thresh[data>=threshold]=data[data>=threshold]
    elif method == "distance":
        data_thresh[data<=threshold]=data[data<=threshold]
    else:
        raise ValueError("Method has to be 'strength' or 'distance'")
    adj_thresh=weighted_adj.copy()
    adj_thresh.data=data_thresh
    adj_thresh.eliminate_zeros()
    return adj_thresh

bedge_counts(adjacency, simplices = None, max_simplices = False, max_dim = -1, simplex_type = 'directed', **kwargs)

Count the sum number of edges per position on the subgraphs defined by the nodes of the simplices in simplices.

Parameters:

Name Type Description Default
adjacency (N,N)-array or sparse matrix

Adjacency matrix of a directed network. A non-zero entry adj[i,j] implies there is an edge from i to j. The matrix can be asymmetric, but must have 0 in the diagonal.

required
simplices series

Series of 2d-arrays indexed by dimension. Each array is of dimension (no. of simplices, dimension). Each row corresponds to a list of nodes on a simplex.

None
max_simplices bool

If False counts all simplices in adj. If True counts only maximal simplices i.e., simplex motifs that are not contained in higher dimensional ones.

False
max_dim int

Maximal dimension up to which simplex motifs are counted. The default max_dim = -1 counts all existing dimensions. Particularly useful for large or dense graphs.

-1
simplex_type 'directed'

Returns:

Type Description
series

pandas series with index dimensions values (dim+1, dim+1) arrays. The (i,j) entry counts the number of edges from node i to node j on all the subgraphs of adjacency on the nodes of the simplices listed. See notes.

Notes

Every directed \(k\)-simplex \([v_o, v_1, \ldots, v_k]\) defines as subgraph of the adjacency matrix, with edges \(v_i \to v_j\) whenever \(i\leq j\), but also possibly with ''reverse'' edges. One can represent this structure with a non-symmetric \((k+1, k+1)\)-matrix with 1's for every edge in the subgraph. The output of this function gives for each dimension the sum of all these matrices over all the simplices provided in simplices or over all the simplices in the adjacency matrix if none is provided. The lower triangular part of these matrices is therefore a metric of recurrence within simplices, or "higher dimensional recurrence". In particular, in dimension 1 it is the number of reciprocal edges in the network.

Source code in src/connalysis/network/topology.py
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
def bedge_counts(adjacency, simplices=None,
                 max_simplices = False, max_dim = -1, simplex_type = 'directed', ** kwargs):
    """Count the sum number of edges per position on the subgraphs defined by the nodes of the simplices in simplices.

        Parameters
        ----------
        adjacency : (N,N)-array or sparse matrix
            Adjacency matrix of a directed network.  A non-zero entry adj[i,j] implies there is an edge from i to j.
            The matrix can be asymmetric, but must have 0 in the diagonal.
        simplices : series
            Series  of 2d-arrays indexed by dimension.
            Each array is of dimension (no. of simplices, dimension).
            Each row corresponds to a list of nodes on a simplex.
        max_simplices : bool
            If False counts all simplices in adj.
            If True counts only maximal simplices i.e., simplex motifs that are not contained in higher dimensional ones.
        max_dim : int
            Maximal dimension up to which simplex motifs are counted.
            The default max_dim = -1 counts all existing dimensions.  Particularly useful for large or dense graphs.
        simplex_type: str
            See [simplex_counts](network.md#src.connalysis.network.topology.simplex_counts)

        Returns
        -------
        series
            pandas series with index dimensions values (dim+1, dim+1) arrays.  The (i,j) entry counts the number of edges
            from node i to node j on all the subgraphs of adjacency on the nodes of the simplices listed.  See notes.

        Notes
        -------
        Every directed $k$-simplex $[v_o, v_1, \\ldots, v_k]$ defines as subgraph of the adjacency matrix, with edges
        $v_i \\to v_j$ whenever $i\leq j$, but also possibly with ''reverse'' edges.  One can represent this structure
        with a non-symmetric $(k+1, k+1)$-matrix with `1`'s for every edge in the subgraph.  The output of this function
        gives for each dimension the sum of all these matrices over all the simplices provided in `simplices` or over
        all the simplices in the adjacency matrix if none is provided.  The lower triangular part of these matrices is
        therefore a metric of recurrence within simplices, or "higher dimensional recurrence".
        In particular, in dimension 1 it is the number of reciprocal edges in the network.
        """

    adj = adjacency

    if simplices is None:
        LOG.info("COMPUTE `bedge_counts(...)`: No argued simplices.")
        return bedge_counts(adj,
                            list_simplices_by_dimension(adj, max_simplices = max_simplices,
                                                        max_dim = max_dim, simplex_type = simplex_type, ** kwargs))
    else:
        LOG.info("COMPUTE `bedge_counts(...): for simplices: %s ", simplices.shape)

    dense = np.array(adjacency.toarray(), dtype=int)

    def subset_adj(simplex):
        return dense[simplex].T[simplex]

    def count_bedges(simplices_given_dim):
        """..."""
        try:
            d_simplices = simplices_given_dim.get_value()
        except AttributeError:
            d_simplices = simplices_given_dim

        if d_simplices is None or d_simplices.shape[1] == 1:
            return np.nan

        return (pd.DataFrame(d_simplices, columns=range(d_simplices.shape[1]))
                .apply(subset_adj, axis=1)
                .agg("sum"))

    return simplices.apply(count_bedges)

betti_counts(adj, node_properties = None, min_dim = 0, max_dim = [], simplex_type = 'directed', approximation = None, **kwargs)

Count betti counts of flag complex of adj. Type of flag complex is given by simplex_type.

Parameters:

Name Type Description Default
adj 2d (N,N)-array or sparse matrix

Adjacency matrix of a directed network. A non-zero entry adj[i,j] implies there is an edge from i to j. The matrix can be asymmetric, but must have 0 in the diagonal. Matrix will be cast to 0,1 entries so weights will be ignored.

required
node_properties data frame

Data frame of neuron properties in adj. Only necessary if used in conjunction with TAP or connectome utilities.

None
min_dim int

Minimal dimension from which betti counts are computed. The default min_dim = 0 (counting number of connected components).

0
max_dim int

Maximal dimension up to which simplex motifs are counted. The default max_dim = [] counts betti numbers up to the maximal dimension of the complex.

[]
simplex_type string

Type of flag complex to consider, given by the type of simplices it is built on. Possible types are:

’directed’ - directed simplices (directed flag complex)

’undirected’ - simplices in the underlying undirected graph (clique complex of the underlying undirected graph)

’reciprocal’ - simplices in the undirected graph of reciprocal connections (clique complex of the undirected graph of reciprocal connections.)

'directed'
approximation list of integers or None

Approximation parameter for the computation of the betti numbers. Useful for large networks. If None all betti numbers are computed exactly. Otherwise, min_dim must be 0 and approximation but be a list of positive integers or -1. The list approximation is either extended by -1 entries on the right or sliced from [0:max_dim+1] to obtain a list of length max_dim. Each entry of the list denotes the approximation value for the betti computation of that dimension if -1 approximation in that dimension is set to None.

If the approximation value at a given dimension is a flagser skips cells creating columns in the reduction matrix with more than a entries. This is useful for hard problems. For large, sparse networks a good value if often 100,00. If set to 1 that dimension will be virtually ignored. See [1]_

None

Returns:

Type Description
series

Betti counts indexed per dimension from min_dim to max_dim.

Raises:

Type Description
AssertionError

If adj has non-zero entries in the diagonal which can produce errors.

AssertionError

If adj is not square.

AssertionError

If approximation != None and min_dim != 0.

See Also

simplex_counts : A function that counts the simplices forming the complex from which bettis are count. Simplex types are described there in detail.

References

For details about the approximation algorithm see

..[1] D. Luetgehetmann, "Documentation of the C++ flagser library"; GitHub: luetge/flagser.

Source code in src/connalysis/network/topology.py
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
def betti_counts(adj, node_properties=None,
                 min_dim=0, max_dim=[], simplex_type='directed', approximation=None,
                 **kwargs):
    """Count betti counts of flag complex of adj.  Type of flag complex is given by simplex_type.

    Parameters
    ----------
    adj : 2d (N,N)-array or sparse matrix
        Adjacency matrix of a directed network.  A non-zero entry adj[i,j] implies there is an edge from i to j.
        The matrix can be asymmetric, but must have 0 in the diagonal.  Matrix will be cast to 0,1 entries so weights
        will be ignored.
    node_properties :  data frame
        Data frame of neuron properties in adj.  Only necessary if used in conjunction with TAP or connectome utilities.
    min_dim : int
        Minimal dimension from which betti counts are computed.
        The default min_dim = 0 (counting number of connected components).
    max_dim : int
        Maximal dimension up to which simplex motifs are counted.
        The default max_dim = [] counts betti numbers up to the maximal dimension of the complex.
    simplex_type : string
        Type of flag complex to consider, given by the type of simplices it is built on.
        Possible types are:

        ’directed’ - directed simplices (directed flag complex)

        ’undirected’ - simplices in the underlying undirected graph (clique complex of the underlying undirected graph)

        ’reciprocal’ - simplices in the undirected graph of reciprocal connections (clique complex of the
        undirected graph of reciprocal connections.)
    approximation : list of integers  or None
        Approximation parameter for the computation of the betti numbers.  Useful for large networks.
        If None all betti numbers are computed exactly.
        Otherwise, min_dim must be 0 and approximation but be a list of positive integers or -1.
        The list approximation is either extended by -1 entries on the right or sliced from [0:max_dim+1] to obtain
        a list of length max_dim.  Each entry of the list denotes the approximation value for the betti computation
        of that dimension if -1 approximation in that dimension is set to None.

        If the approximation value at a given dimension is `a` flagser skips cells creating columns in the reduction
        matrix with more than `a` entries.  This is useful for hard problems.  For large, sparse networks a good value
        if often `100,00`.  If set to `1` that dimension will be virtually ignored.  See [1]_

    Returns
    -------
    series
        Betti counts indexed per dimension from min_dim to max_dim.

    Raises
    ------
    AssertionError
        If adj has non-zero entries in the diagonal which can produce errors.
    AssertionError
        If adj is not square.
    AssertionError
        If approximation != None and min_dim != 0.

    See Also
    --------
    [simplex_counts](network.md#src.connalysis.network.topology.simplex_counts) :
    A function that counts the simplices forming the complex from which bettis are count.
    Simplex types are described there in detail.

    References
    ----------
    For details about the approximation algorithm see

    ..[1] D. Luetgehetmann, "Documentation of the C++ flagser library";
           [GitHub: luetge/flagser](https://github.com/luetge/flagser/blob/master/docs/documentation_flagser.pdf).

    """
    LOG.info("Compute betti counts for %s-type adjacency matrix and %s-type node properties",
             type(adj), type(node_properties))

    from pyflagser import flagser_unweighted

    #Checking matrix
    adj = sp.csr_matrix(adj).astype(bool).astype('int')
    assert np.count_nonzero(adj.diagonal()) == 0, 'The diagonal of the matrix is non-zero and this may lead to errors!'
    N, M = adj.shape
    assert N == M, 'Dimension mismatch. The matrix must be square.'
    assert not((not approximation is None) and (min_dim!=0)), \
        'For approximation != None, min_dim must be set to 0.  \nLower dimensions can be ignored by setting approximation to 1 on those dimensions'

    # Symmetrize matrix if simplex_type is not 'directed'
    if simplex_type == 'undirected':
        adj = sp.triu(underlying_undirected_matrix(adj))  # symmtrize and keep upper triangular only
    elif simplex_type == "reciprocal":
        adj = sp.triu(rc_submatrix(adj))  # symmtrize and keep upper triangular only
    #Computing bettis
    if max_dim==[]:
        max_dim=np.inf

    if approximation==None:
        LOG.info("Run without approximation")
        bettis = flagser_unweighted(adj, min_dimension=min_dim, max_dimension=max_dim,
                                    directed=True, coeff=2,
                                    approximation=None)['betti']
    else:
        assert (all([isinstance(item,int) for item in approximation])) # assert it's a list of integers
        approximation=np.array(approximation)
        bettis=[]

        #Make approximation vector to be of size max_dim
        if max_dim!=np.inf:
            if approximation.size-1 < max_dim:#Vector too short so pad with -1's
                approximation=np.pad(approximation,
                                     (0,max_dim-(approximation.size-1)),
                                     'constant',constant_values=-1)
            if approximation.size-1>max_dim:#Vector too long, select relevant slice
                approximation=approximation[0:max_dim+1]
            #Sanity check
            LOG.info("Correct dimensions for approximation: %s", approximation.size==max_dim+1)

        #Split approximation into sub-vectors of same value to speed up computation
        diff=approximation[1:]-approximation[:-1]
        slice_indx=np.array(np.where(diff!=0)[0])+1

        #Compute betti counts
        for dims_range in  np.split(np.arange(approximation.size),slice_indx):
            n=dims_range[0] #min dim for computation
            N=dims_range[-1] #max dim for computation
            a=approximation[n]
            if a==-1:
                a=None
            LOG.info("Run betti for dim range %s-%s with approximation %s", n,N,a)
            bettis=bettis+flagser_unweighted(adj, min_dimension=n, max_dimension=N,
                                             directed=True, coeff=2,
                                             approximation=a)['betti']

        if max_dim==np.inf:
            n=approximation.size #min dim for computation
            N=np.inf #max dim for computation
            a=None
            LOG.info("Run betti for dim range %s-%s with approximation %s",n,N,a)
            bettis=bettis+flagser_unweighted(adj, min_dimension=n, max_dimension=N,
                                             directed=True, coeff=2,
                                             approximation=a)['betti']

    return pd.Series(bettis, name="betti_count",
                     index=pd.Index(np.arange(min_dim, len(bettis)+min_dim), name="dim"))

bin_weigths(weights, n_bins = 10, return_bins = False)

Bins the np.array weights Input: np.array of floats, no of bins returns: bins, and binned data i.e. a np.array of the same shape as weights with entries the center value of its corresponding bin

Source code in src/connalysis/network/topology.py
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
def bin_weigths(weights, n_bins=10, return_bins=False):
    '''Bins the np.array weights
    Input: np.array of floats, no of bins
    returns: bins, and binned data i.e. a np.array of the same shape as weights with entries the center value of its corresponding bin
    '''
    tol = 1e-8 #to include the max value in the last bin
    min_weight = weights.min()
    max_weight = weights.max() + tol
    step = (max_weight - min_weight) / n_bins
    bins = np.arange(min_weight, max_weight + step, step)
    digits = np.digitize(weights, bins)

    weights = (min_weight + step / 2) + (digits - 1) * step
    return (weights, bins) if return_bins else weights

count_rc_edges_k_skeleton(simplex_list_at_dim, N, position = 'all', return_mat = False)

Count the edges and reciprocal edges in the simplex list provided. If the list is all the k (maximal)simplices of a directed flag complex, it is counting the number of edges and reciprocal edges of the its k-skeleton.

Parameters:

Name Type Description Default
simplex_list_at_dim

Array of dimension (no. of simplices, dimension). Each row corresponds to a list of nodes on a simplex indexed by the ordering given for all nodes in the graph

required
N

Number of nodes in original graph

required
position

Position of the edges to extract

'all': all edges of the simplex

'spine': edges along the spine of the simplex (only makes sense for directed simplices)

'all'

Returns:

Type Description
tuple of ints

Counts of (edges, reciprocal edges) in the simplex list

Raises:

Type Description
AssertionError

If N <= than an entry in the simplex list

Source code in src/connalysis/network/topology.py
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
def count_rc_edges_k_skeleton(simplex_list_at_dim, N, position="all", return_mat=False):
    """Count the edges and reciprocal edges in the simplex list provided.
    If the list is all the k (maximal)simplices of a directed flag complex, it is counting the number of
    edges and reciprocal edges of the its k-skeleton.

    Parameters
    ----------
    simplex_list_at_dim: 2d-array
        Array of dimension (no. of simplices, dimension).
        Each row corresponds to a list of nodes on a simplex indexed by the
        ordering given for all nodes in the graph
    N: int
        Number of nodes in original graph
    position: str
        Position of the edges to extract

        'all': all edges of the simplex

        'spine': edges along the spine of the simplex
        (only makes sense for directed simplices)

    Returns
    -------
    tuple of ints
        Counts of (edges, reciprocal edges) in the simplex list

    Raises
    ------
    AssertionError
        If N <= than an entry in the simplex list
    """

    assert N > np.max(simplex_list_at_dim), \
        "N must be larger than all the entries in the simplex list"

    mat = extract_submatrix_of_simplices(simplex_list_at_dim, N, position=position)
    edge_counts = mat.sum()
    rc_edge_counts = rc_submatrix(mat).sum()
    # Return mats?
    if return_mat == True:
        return edge_counts, rc_edge_counts, mat
    else:
        return edge_counts, rc_edge_counts

count_rc_edges_skeleta(adj = None, max_dim = -1, max_simplices = False, simplex_list = None, N = None, position = 'all', return_mats = False, **kwargs)

Count the edges and reciprocal edges in the k-skeleta of the directed flag complex of adj for all k<= max_dim. If simplex list are provided, it will compute the skeleta directly from these and not use adj.

Parameters:

Name Type Description Default
adj (N,N)-array or sparse matrix

Adjacency matrix of a directed network. A non-zero entry adj[i,j] implies there is an edge from i to j. The matrix can be asymmetric, but must have 0 in the diagonal.

None
max_simplices bool

If False counts all simplices in adj. If True counts only maximal simplices i.e., simplex motifs that are not contained in higher dimensional ones.

False
max_dim int

Maximal dimension up to which simplex motifs are counted. The default max_dim = -1 counts all existing dimensions. Particularly useful for large or dense graphs.

-1
simplex

Series 2d-arrays indexed by dimension. Each array is of dimension (no. of simplices, dimension). Each row corresponds to a list of nodes on a simplex. If provided adj will be ignored but N will be required.

required
N

Number of nodes in original graph.

None
position

Position of the edges to extract

'all': all edges of the simplex

'spine': edges along the spine of the simplex (only makes sense if simplices are directed)

'all'
return_mats bool

If True return the matrices of the underlying graphs of the k-skeleta as in get_k_skeleta_graph.

False

Returns:

Type Description
data frame, (dict)

data frame with index dimensions and columns number of (rc) edges in the corresponding skeleta if return_mats==True, also return the graphs of the k-skeleta as in get_k_skeleta_graph.

Raises:

Type Description
AssertionError

If neither adj nor simplex_list are provided

AssertionError

If N <= than an entry in the simplex list

Source code in src/connalysis/network/topology.py
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
def count_rc_edges_skeleta(adj=None, max_dim=-1, max_simplices=False,
                           simplex_list=None, N=None,
                           position="all", return_mats=False, **kwargs):
    # check max dim is consistent with simplex_list only used if adj is given and must be >0
    """Count the edges and reciprocal edges in the k-skeleta of the directed flag complex of adj for all
    k<= max_dim. If simplex list are provided, it will compute the skeleta directly from these and not use adj.

    Parameters
    ----------
    adj : (N,N)-array or sparse matrix
        Adjacency matrix of a directed network.  A non-zero entry adj[i,j] implies there is an edge from i to j.
        The matrix can be asymmetric, but must have 0 in the diagonal.
    max_simplices : bool
        If False counts all simplices in adj.
        If True counts only maximal simplices i.e., simplex motifs that are not contained in higher dimensional ones.
    max_dim : int
        Maximal dimension up to which simplex motifs are counted.
        The default max_dim = -1 counts all existing dimensions.  Particularly useful for large or dense graphs.
    simplex list: series
        Series 2d-arrays indexed by dimension.
        Each array is of dimension (no. of simplices, dimension).
        Each row corresponds to a list of nodes on a simplex.
        If provided adj will be ignored but N will be required.
    N: int
        Number of nodes in original graph.
    position: str
        Position of the edges to extract

        'all': all edges of the simplex

        'spine': edges along the spine of the simplex
        (only makes sense if simplices are directed)
    return_mats : bool
        If True return the matrices of the underlying graphs of the k-skeleta as in
        get_k_skeleta_graph.

    Returns
    -------
    data frame, (dict)
        data frame with index dimensions and columns number of (rc) edges in the corresponding skeleta
        if return_mats==True, also return the graphs of the k-skeleta as in get_k_skeleta_graph.

    Raises
    ------
    AssertionError
        If neither adj nor simplex_list are provided
    AssertionError
        If N <= than an entry in the simplex list
    """

    assert not (adj is None and simplex_list is None), "Either adj or simplex_list need to be provided"

    if (simplex_list is None):  # Compute simplex lists if not provided
        simplex_list = list_simplices_by_dimension(adj, node_properties=None,
                                                            max_simplices=max_simplices, max_dim=max_dim,
                                                            simplex_type='directed',
                                                            nodes=None, verbose=False, **kwargs)
        N = adj.shape[0]
    else:
        assert N > np.nanmax(simplex_list.explode().explode()), \
            "N must be larger than all the entries in the simplex list"

    # Extract 'k'-skeleton and count (rc-)edges
    dims = simplex_list.index[simplex_list.index != 0]  # Doesn't make sense to look at the 0-skeleton
    edge_counts = pd.DataFrame(index=dims, columns=["number_of_edges", "number_of_rc_edges", "rc/edges_percent"])
    if return_mats == True:
        skeleton_mats = {f'dimension_{dim}': None for dim in dims}
    print(dims)
    for dim in dims:
        if simplex_list[dim].size > 0:
            edges, rc_edges, mat = count_rc_edges_k_skeleton(simplex_list[dim], N,
                                                                      position=position, return_mat=True)
            edge_counts["number_of_edges"].loc[dim] = edges
            edge_counts["number_of_rc_edges"].loc[dim] = rc_edges
            edge_counts["rc/edges_percent"].loc[dim] = (rc_edges * 100) / edges
        else:
            edge_counts["number_of_edges"].loc[dim] = 0
        if return_mats == True:
            skeleton_mats[f'dimension_{dim}'] = mat
    if return_mats == True:
        return edge_counts, skeleton_mats
    else:
        return edge_counts

count_triads_fully_connected(adj, max_num_sampled = 5000000, return_normalized = False)

Counts the numbers of each triadic motif in the matrix adj.

Parameters:

Name Type Description Default
adj 2d-array

Adjacency matrix of a directed network.

required
max_num_sampled int

The maximal number of connected triads classified. If the number of connected triads is higher than that, only the specified number is sampled at random and classified. The final counts are extrapolated as (actual_num_triads/ max_num_sampled) * counts.

5000000
return_normalized bool

If True return the triad counts divided by the size of each isomorphism class. That is, the total counts divided by the following array:

\([6, 3, 3, 6, 6, 6, 2, 3, 6, 3, 3, 6, 1].\)

False

Returns:

Type Description
1d-array

The counts of the various triadic motifs in adj as ordered in Figure 5 [1]_.

Notes

Only connectected motifs are counted, i.e. motifs with less than 2 connections or only a single bidirectional connection are not counted. The connected motifs are ordered as in Figure 5 [1]_.

References

..[1] Gal, Eyal, et al. "Rich cell-type-specific network topology in neocortical microcircuitry." Nature neuroscience 20.7 (2017): 1004-1013.

Source code in src/connalysis/network/topology.py
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
def count_triads_fully_connected(adj, max_num_sampled=5000000, return_normalized=False):
    """Counts the numbers of each triadic motif in the matrix adj.

    Parameters
    ----------
    adj : 2d-array
        Adjacency matrix of a directed network.
    max_num_sampled : int
        The maximal number of connected triads classified. If the number of
        connected triads is higher than that, only the specified number is sampled at random and
        classified. The final counts are extrapolated as (actual_num_triads/ max_num_sampled) * counts.
    return_normalized : bool
        If True return the triad counts divided by the size of each isomorphism class.  That is, the total counts
        divided by the following array:

        $[6, 3, 3, 6, 6, 6, 2, 3, 6, 3, 3, 6, 1].$

    Returns
    -------
    1d-array
        The counts of the various triadic motifs in adj as ordered in Figure 5 [1]_.

    Notes
    ------
    Only connectected motifs are counted, i.e. motifs with less than 2 connections or only a single bidirectional
    connection are not counted. The connected motifs are ordered as in Figure 5 [1]_.

    References
    -------

    ..[1] Gal, Eyal, et al.
    ["Rich cell-type-specific network topology in neocortical microcircuitry."](https://www.nature.com/articles/nn.4576)
    Nature neuroscience 20.7 (2017): 1004-1013.

    """

    # Functions to indetify triads
    def canonical_sort(M):
        """Sorts row/columns of the matrix adj using the lexicographical order of the
        tuple (out_degree, in_degree).

        Parameters
        ----------
        M : 2d-array
            Adjacency matrix of a directed network.

        Returns
        -------
        2d-array
            the matrix adj with rows/columns sorted
        """
        in_degree = np.sum(M, axis=0)
        out_degree = np.sum(M, axis=1)
        idx = np.argsort(-in_degree - 10 * out_degree)
        return M[:, idx][idx]

    def identify_motif(M):
        """
        Identifies the connected directed digraph on three nodes M as on in the full classification
        list given in the dictionary triad_dict.

        Parameters
        ----------
        M : array
            A (3,3) array describing a directed connected digraph on three nodes.

        Returns
        -------
        The index of the motif as indexed in the dictiroanry triad_dict which follows the
        ordering of Gal et al., 2017
        """
        triad_code = tuple(np.nonzero(canonical_sort(M).flatten())[0])
        return triad_dict[triad_code]

    # Finding and counting triads
    import time
    adj = adj.toarray()  # Casting to array makes finding triads an order of magnitude faster
    t0 = time.time()
    undirected_adj = underlying_undirected_matrix(adj).toarray()
    # Matrix with i,j entries number of undirected paths between i and j in adj
    path_counts = np.triu(undirected_adj @ undirected_adj, 1)
    connected_pairs = np.nonzero(path_counts)
    triads = set()
    print("Testing {0} potential triadic pairs".format(len(connected_pairs[0])))
    for x, y in zip(*connected_pairs):
        # zs = np.nonzero((undirected_adj.getrow(x).multiply(undirected_adj.getrow(y))).toarray()[0])[0]
        zs = np.nonzero(undirected_adj[x] & undirected_adj[y])[0]
        for z in zs:
            triads.add(tuple(sorted([x, y, z])))
    triads = list(triads)
    print("Time spent finding triads: {0}".format(time.time() - t0))
    print("Found {0} connected triads".format(len(triads)))
    t0 = time.time()
    counts = np.zeros(np.max(list(triad_dict.values())) + 1)
    sample_idx = np.random.choice(len(triads),
                                  np.minimum(max_num_sampled, len(triads)),
                                  replace=False)
    for idx in sample_idx:
        triad = triads[idx]
        motif_id = identify_motif(adj[:, triad][triad, :])
        counts[motif_id] += 1
    print("Time spent classifying triads: {0}".format(time.time() - t0))
    if return_normalized:
        return (((len(triads) / len(sample_idx)) * counts).astype(int)) / triad_combinations
    else:
        return (((len(triads) / len(sample_idx)) * counts).astype(int))

cross_col_k_in_degree(adj_cross, adj_source, max_simplices = False, threads = 1, max_dim = -1, **kwargs)

Compute generalized in-degree of nodes in adj_target from nodes in adj_source. The k-in-degree of a node v is the number of k-simplices in adj_source with all its nodes mapping to v through edges in adj_cross.

Parameters:

Name Type Description Default
adj_cross (n,m) array or sparse matrix

Matrix of connections from the nodes in adj_n to the target population. n is the number of nodes in adj_source and m is the number of nodes in adj_target. A non-zero entry adj_cross[i,j] implies there is an edge from i-th node of adj_source to the j-th node of adj_target.

required
adj_source (n, n)-array or sparse matrix

Adjacency matrix of the source network where n is the number of nodes in the source network. A non-zero entry adj_source[i,j] implies there is an edge from node i to j. The matrix can be asymmetric, but must have 0 in the diagonal.

required
max_simplices bool

If False counts all simplices. If True counts only maximal simplices.

False
max_dim int

Maximal dimension up to which simplex motifs are counted. The default max_dim = -1 counts all existing dimensions. Particularly useful for large or dense graphs.

-1

Returns:

Type Description
Data frame

Table of cross-k-in-degrees indexed by the m nodes in the target population.

Raises:

Type Description
AssertionError

If adj_source has non-zero entries in the diagonal which can produce errors.

Source code in src/connalysis/network/topology.py
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
def cross_col_k_in_degree(adj_cross, adj_source, max_simplices=False,
                          threads=1,max_dim=-1,**kwargs):
    #TODO: DO THE OUTDEGREE VERSION
    #TODO: Get participation directly from flagsercount via vertices to do?
    """Compute generalized in-degree of nodes in adj_target from nodes in adj_source.
    The k-in-degree of a node v is the number of k-simplices in adj_source with all its nodes mapping to v
    through edges in adj_cross.
    Parameters
    ----------
    adj_cross : (n,m) array or sparse matrix
        Matrix of connections from the nodes in adj_n to the target population.
        n is the number of nodes in adj_source and m is the number of nodes in adj_target.
        A non-zero entry adj_cross[i,j] implies there is an edge from i-th node of adj_source
        to the j-th node of adj_target.
    adj_source : (n, n)-array or sparse matrix
        Adjacency matrix of the source network where n is the number of nodes in the source network.
        A non-zero entry adj_source[i,j] implies there is an edge from node i to j.
        The matrix can be asymmetric, but must have 0 in the diagonal.
    max_simplices : bool
        If False counts all simplices.
        If True counts only maximal simplices.
    max_dim : int
        Maximal dimension up to which simplex motifs are counted.
        The default max_dim = -1 counts all existing dimensions.
        Particularly useful for large or dense graphs.

    Returns
    -------
    Data frame
        Table of cross-k-in-degrees indexed by the m nodes in the target population.

    Raises
    ------
    AssertionError
        If adj_source has non-zero entries in the diagonal which can produce errors.
    """
    adj_source=sp.csr_matrix(adj_source).astype('bool')
    adj_cross=sp.csr_matrix(adj_cross).astype('bool')
    assert np.count_nonzero(adj_source.diagonal()) == 0, \
    'The diagonal of the source matrix is non-zero and this may lead to errors!'
    assert adj_source.shape[0] == adj_source.shape[1], \
    'Dimension mismatch. The source matrix must be square.'
    assert adj_source.shape[0] == adj_cross.shape[0], \
    'Dimension mismatch. The source matrix and cross matrix must have the same number of rows.'

    n_source = adj_source.shape[0] #Size of the source population
    n_target = adj_cross.shape[1] #Size of the target population
    # Building a square matrix [[adj_source, adj_cross], [0,0]]
    adj=sp.bmat([[adj_source, adj_cross],
                 [sp.csr_matrix((n_target, n_source), dtype='bool'),
                  sp.csr_matrix((n_target, n_target), dtype='bool')]])
    # Transposing to restrict computation to ``source nodes'' in adj_target in flagsercount
    adj=adj.T
    nodes=np.arange(n_source, n_source+n_target) #nodes on target population
    slist=list_simplices_by_dimension(adj, max_simplices=max_simplices, max_dim=max_dim,nodes=nodes,
                                      simplex_type='directed',verbose=False,threads=threads,**kwargs)

    #Count participation as a source in transposed matrix i.e. participation as sink in the original
    cross_col_deg=pd.DataFrame(columns=slist.index[1:], index=nodes)
    for dim in slist.index[1:]:
        index,deg=np.unique(slist[dim][:,0],return_counts=True)
        cross_col_deg[dim].loc[index]=deg
    cross_col_deg=cross_col_deg.fillna(0)
    return cross_col_deg

extract_submatrix_of_simplices(simplex_list, N, position = 'all')

Generate binary submatrix of NxN matrix of edges in simplex list.

Parameters:

Name Type Description Default
simplex

Array of dimension (no. of simplices, dimension). Each row corresponds to a list of nodes on a simplex indexed by the order of the nodes in an NxN matrix.

required
N

Number of nodes in original graph defining the NxN matrix.

required
position

Position of the edges to extract

'all': all edges of the simplex

'spine': edges along the spine of the simplex (only makes sense for directed simplices)

'all'

Returns:

Type Description
csr bool matrix

Matrix with of shape (N,N) with entries True corresponding to edges in simplices.

Source code in src/connalysis/network/topology.py
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
def extract_submatrix_of_simplices(simplex_list, N, position="all"):
    """Generate binary submatrix of NxN matrix of edges in simplex list.

    Parameters
    ----------
    simplex list: 2d-array
        Array of dimension (no. of simplices, dimension).
        Each row corresponds to a list of nodes on a simplex
        indexed by the order of the nodes in an NxN matrix.
    N: int
        Number of nodes in original graph defining the NxN matrix.
    position: str
        Position of the edges to extract

        'all': all edges of the simplex

        'spine': edges along the spine of the simplex
        (only makes sense for directed simplices)

    Returns
    -------
    csr bool matrix
        Matrix with of shape (N,N) with entries `True` corresponding to edges in simplices.
    """
    if simplex_list.shape[0] == 0:
        return sp.csr_matrix((N, N), dtype=bool)  # no simplices in this dimension
    else:
        dim = simplex_list.shape[1] - 1
        edges_abstract = _generate_abstract_edges_in_simplices(dim,
                                                               position=position)  # abstract list of edges to extract from each simplex
        edges = np.unique(np.concatenate([simplex_list[:, edge] for edge in edges_abstract]), axis=0)
        return (sp.coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])), shape=(N, N))).tocsr().astype(bool)

filtered_simplex_counts(adj, node_properties = None, method = 'strength', binned = False, n_bins = 10, threads = 1, **kwargs)

Takes weighted adjancecy matrix returns data frame with filtered simplex counts where index is the weight method strength higher weights enter first, method distance smaller weights enter first

Source code in src/connalysis/network/topology.py
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
def filtered_simplex_counts(adj, node_properties=None, method="strength",
                            binned=False, n_bins=10, threads=1,
                            **kwargs):
    '''Takes weighted adjancecy matrix returns data frame with filtered simplex counts where index is the weight
    method strength higher weights enter first, method distance smaller weights enter first'''
    from tqdm import tqdm
    adj = adj.copy()
    if binned==True:
        adj.data = bin_weigths(adj.data, n_bins=n_bins)

    weights = filtration_weights(adj, node_properties, method)

#    TODO: 1. Prove that the following is executed in the implementation that follows.
#    TODO: 2. If any difference, update the implementation
#    TODO: 3. Remove the reference code.
#    n_simplices = dict.fromkeys(weights)
#    for weight in tqdm(weights[::-1],total=len(weights)):
#        adj = at_weight_edges(adj, threshold=weight, method=method)
#        n_simplices[weight] = simplex_counts(adj, threads=threads)

    m = method
    def filter_weight(w):
        adj_w = at_weight_edges(adj, threshold=w, method=m)
        return simplex_counts(adj_w, threads=threads)

    n_simplices = {w: filter_weight(w) for w in weights[::-1]}
    return pd.DataFrame.from_dict(n_simplices, orient="index").fillna(0).astype(int)

filtration_weights(adj, node_properties = None, method = 'strength')

Returns the filtration weights of a given weighted adjacency matrix. :param method: distance smaller weights enter the filtration first strength larger weights enter the filtration first

TODO: Should there be a warning when the return is an empty array because the matrix is zero?

Source code in src/connalysis/network/topology.py
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
def filtration_weights(adj, node_properties=None, method="strength"):
    """
    Returns the filtration weights of a given weighted adjacency matrix.
    :param method: distance smaller weights enter the filtration first
                   strength larger weights enter the filtration first

    TODO: Should there be a warning when the return is an empty array because the matrix is zero?
    """
    if method == "strength":
        return np.unique(adj.data)[::-1]

    if method == "distance":
        return np.unique(adj.data)

    raise ValueError("Method has to be 'strength' or 'distance'")

get_all_simplices_from_max(max_simplices)

Takes the list of maximal simplices are returns the list of all simplices.

Parameters:

Name Type Description Default
max_simplices list

A list of lists of tuples. Where max_simplices[k] is a list of the 0 dimensional maximal simplices, where each simplex is a tuple of the vertices of the simplex

required

Returns:

Type Description
list

A list of lists of tuples. Of the same format as the inputted list but now contains all simplices.

Source code in src/connalysis/network/topology.py
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
def get_all_simplices_from_max(max_simplices):
    """Takes the list of maximal simplices are returns the list of all simplices.

        Parameters
        ----------
        max_simplices : list
            A list of lists of tuples. Where max_simplices[k] is a list of the 0 dimensional maximal simplices,
            where each simplex is a tuple of the vertices of the simplex

        Returns
        -------
        list
            A list of lists of tuples. Of the same format as the inputted list but now contains all simplices.
        """
    simplices = list(max_simplices)
    for k in range(len(max_simplices)-1,0,-1):
        print(max_simplices[k])
        for simplex in simplices[k]:
            for s in range(k,-1,-1):
                x = tuple(simplex[:s]+simplex[s+1:])
                if x not in simplices[k-1]:
                    simplices[k-1].append(x)

    return simplices

get_k_skeleta_graph(adj = None, max_simplices = False, dimensions = None, simplex_type = 'directed', simplex_list = None, N = None, position = 'all', **kwargs)

Return the edges of the (maximal) k-skeleton of the flag complex of adj for all k<= max_dim in the position determined by position. If simplex list are provided, it will compute the edges directly from these and not use adj, in which case N (the number of rows and columns of adj) is required. If simplex lists are not provided they will be calculated with for the flag complex whose type is determined by simplex_type as for simplex_counts.

Parameters:

Name Type Description Default
adj (N,N)-array or sparse matrix

Adjacency matrix of a directed network. A non-zero entry adj[i,j] implies there is an edge from i to j. The matrix can be asymmetric, but must have 0 in the diagonal.

None
max_simplices bool

If False counts all simplices in adj. If True counts only maximal simplices i.e., simplex motifs that are not contained in higher dimensional ones.

False
dimensions list of ints

Dimensions k for which the k-skeleta is computed, if None all dimensions are computed.

None
simplex_type string

Type of simplex to consider if computed from adj:

’directed’ - directed simplices

’undirected’ - simplices in the underlying undirected graph

’reciprocal’ - simplices in the undirected graph of reciprocal connections

'directed'
simplex

Series 2d-arrays indexed by dimension. Each array is of dimension (no. of simplices, dimension). Each row corresponds to a list of nodes on a simplex. If provided adj will be ignored but N will be required.

required
N

Number of nodes in original graph.

None
position

Position of the edges to extract

'all': all edges of the simplex

'spine': edges along the spine of the simplex (only makes sense if simplices are directed)

'all'

Returns:

Type Description
dict

Dictionary with keys dimensions and values boolean (N,N) matrices with entries True corresponding to edges in (maximal) simplices of that dimension.

Raises:

Type Description
AssertionError

If neither adj nor simplex_list are provided

AssertionError

If N <= than an entry in the simplex list

AssertionError

If a dimension is required that is not an index in the simplex list

Notes

In order to list k-simplices and thus the k-skeleton, flagsercount needs to list all lower dimensional simplices anyhow.

Source code in src/connalysis/network/topology.py
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
def get_k_skeleta_graph(adj=None, max_simplices=False, dimensions=None, simplex_type='directed',
                        simplex_list=None, N=None, position="all",
                        **kwargs):
    # Choose only some dimensions???
    # check max dim is consistent with simplex_list only used if adj is given and must be >0
    # adj only used is simplex list is none
    # Add requirement to give adj is direction is undirected and multiply adj by mat!!!
    """Return the edges of the (maximal) k-skeleton of the flag complex of adj for all k<= max_dim in the position determined
    by position.
    If simplex list are provided, it will compute the edges directly from these and not use adj,
    in which case N (the number of rows and columns of adj) is required.
    If simplex lists are not provided they will be calculated with for the flag complex whose type is determined by
    simplex_type as for simplex_counts.

    Parameters
    ----------
    adj : (N,N)-array or sparse matrix
        Adjacency matrix of a directed network.  A non-zero entry adj[i,j] implies there is an edge from i to j.
        The matrix can be asymmetric, but must have 0 in the diagonal.
    max_simplices : bool
        If False counts all simplices in adj.
        If True counts only maximal simplices i.e., simplex motifs that are not contained in higher dimensional ones.
    dimensions : list of ints
        Dimensions `k` for which the `k`-skeleta is computed, if None all dimensions are computed.
    simplex_type : string
        Type of simplex to consider if computed from adj:

        ’directed’ - directed simplices

        ’undirected’ - simplices in the underlying undirected graph

        ’reciprocal’ - simplices in the undirected graph of reciprocal connections
    simplex list: series
        Series 2d-arrays indexed by dimension.
        Each array is of dimension (no. of simplices, dimension).
        Each row corresponds to a list of nodes on a simplex.
        If provided adj will be ignored but N will be required.
    N: int
        Number of nodes in original graph.
    position: str
        Position of the edges to extract

        'all': all edges of the simplex

        'spine': edges along the spine of the simplex
        (only makes sense if simplices are directed)

    Returns
    -------
    dict
        Dictionary with keys dimensions and values boolean (N,N) matrices with entries `True`
        corresponding to edges in (maximal) simplices of that dimension.

    Raises
    ------
    AssertionError
        If neither adj nor simplex_list are provided
    AssertionError
        If N <= than an entry in the simplex list
    AssertionError
        If a dimension is required that is not an index in the simplex list

    Notes
    ------
    In order to list k-simplices and thus the k-skeleton, flagsercount needs to list all lower
    dimensional simplices anyhow.

    """

    assert not (adj is None and simplex_list is None), "Either adj or simplex_list need to be provided"

    if dimensions == None:
        max_dim = -1
    else:
        max_dim = np.max(np.array(dimensions))

    if (simplex_list is None):  # Compute simplex lists if not provided
        simplex_list = list_simplices_by_dimension(adj, node_properties=None,
                                                   max_simplices=max_simplices, max_dim=max_dim,
                                                   simplex_type=simplex_type,
                                                   nodes=None, verbose=False, **kwargs)
        N = adj.shape[0]
    else:
        assert isinstance(N, int), 'If simplex list are provide N must be provided'
        assert N > np.nanmax(simplex_list.explode().explode()), \
            "N must be larger than all the entries in the simplex list"
        assert (dimensions == None) or np.isin(dimensions, simplex_list.index).all(), \
            f'Some requested dimensions={dimensions} are not in the simplex lists index={simplex_list.index.to_numpy()}'
    # Extract 'k'-skeleton
    dims = simplex_list.index[simplex_list.index != 0]  # Doesn't make sense to look at the 0-skeleton
    if dimensions != None:
        dims = dims[np.isin(dims, dimensions)]
    skeleton_mats = {f'dimension_{dim}': None for dim in dims}
    for dim in dims:
        mat = extract_submatrix_of_simplices(simplex_list[dim], N, position=position)
        if simplex_type in ('undirected', 'reciprocal'):
            mat = (mat + mat.T).astype(bool)
        skeleton_mats[f'dimension_{dim}'] = mat
    return skeleton_mats

in_degree_from_pop(adj, source_pop, max_simplices = False, threads = 1, max_dim = -1, **kwargs)

Compute generalized in-degree of nodes source_pop onto the rest of the nodes in adj.

Parameters:

Name Type Description Default
adj

Adjacency matrix of a directed network. A non-zero entry adj[i,j] implies there is an edge from i to j. The matrix can be asymmetric, but must have 0 in the diagonal.

required
source_pop
required
max_simplices bool

If False counts all simplices. If True counts only maximal simplices.

False
max_dim int

Maximal dimension up to which simplex motifs are counted. The default max_dim = -1 counts all existing dimensions. Particularly useful for large or dense graphs.

-1

Returns:

Type Description
Data frame

Table of k-in-degrees from source_pop indexed by the target population.

Raises:

Type Description
AssertionError

If adj restricted to source_pop has non-zero entries in the diagonal which can produce errors.

Source code in src/connalysis/network/topology.py
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
def in_degree_from_pop(adj, source_pop, max_simplices=False,threads=1, max_dim=-1, ** kwargs):
    # TODO: DO THE OUTDEGREE VERSION
    # TODO: Get participation directly from flagsercount via vertices to do?
    """Compute generalized in-degree of nodes source_pop onto the rest of the nodes in adj.
    Parameters
    ----------
    adj: 2d (N,N)-array or sparse matrix
        Adjacency matrix of a directed network.  A non-zero entry adj[i,j] implies there is an edge from i to j.
        The matrix can be asymmetric, but must have 0 in the diagonal.
    source_pop: list of indices of the source population, must be a subset of ``np.arange(0, adj.shape[0])``
    max_simplices : bool
        If False counts all simplices.
        If True counts only maximal simplices.
    max_dim : int
        Maximal dimension up to which simplex motifs are counted.
        The default max_dim = -1 counts all existing dimensions.
        Particularly useful for large or dense graphs.

    Returns
    -------
    Data frame
        Table of k-in-degrees from source_pop indexed by the target population.

    Raises
    ------
    AssertionError
        If adj restricted to source_pop has non-zero entries in the diagonal which can produce errors.
    """
    adj=adj.tocsr()
    source_pop = np.sort(source_pop)
    target_pop = np.setdiff1d(np.arange(adj.shape[0]), source_pop)
    adj_source = adj[np.ix_(source_pop, source_pop)]
    adj_cross = adj[np.ix_(source_pop, target_pop)]
    degs=cross_col_k_in_degree(adj_cross, adj_source,
                                 max_simplices=max_simplices,threads=threads, max_dim=max_dim, **kwargs)
    degs.index=target_pop
    return degs

list_simplices_by_dimension(adj, node_properties = None, max_simplices = False, max_dim = -1, nodes = None, verbose = False, simplex_type = 'directed', **kwargs)

List all simplex motifs in the network adj.

Parameters:

Name Type Description Default
adj 2d (N,N)-array or sparse matrix

Adjacency matrix of a directed network. A non-zero entry adj[i,j] implies there is an edge from i to j. The matrix can be asymmetric, but must have 0 in the diagonal.

required
node_properties data frame

Data frame of neuron properties in adj. Only necessary if used in conjunction with TAP or connectome utilities.

None
max_simplices bool

If False counts all simplices in adj. If True counts only maximal simplices i.e., simplex motifs that are not contained in higher dimensional ones.

False
max_dim int

Maximal dimension up to which simplex motifs are counted. The default max_dim = -1 counts all existing dimensions. Particularly useful for large or dense graphs.

-1
simplex_type string

Type of simplex to consider:

’directed’ - directed simplices

’undirected’ - simplices in the underlying undirected graph

’reciprocal’ - simplices in the undirected graph of reciprocal connections

'directed'
nodes 1d array or None(default)

Restrict to list only the simplices whose source node is in nodes. If None list all simplices

None

Returns:

Type Description
series

Simplex lists indexed per dimension. The dimension k entry is a (no. of k-simplices, k+1)-array is given, where each row denotes a simplex.

Raises:

Type Description
AssertionError

If adj has non-zero entries in the diagonal which can produce errors.

AssertionError

If adj is not square.

AssertionError

If nodes is not a subarray of np.arange(N)

See Also

simplex_counts : A function that counts the simplices instead of listing them and has descriptions of the simplex types.

Source code in src/connalysis/network/topology.py
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
def list_simplices_by_dimension(adj, node_properties=None, max_simplices=False,max_dim=-1,nodes=None,
                                verbose=False, simplex_type='directed', **kwargs):
    """List all simplex motifs in the network adj.
    Parameters
    ----------
    adj : 2d (N,N)-array or sparse matrix
        Adjacency matrix of a directed network.  A non-zero entry adj[i,j] implies there is an edge from i to j.
        The matrix can be asymmetric, but must have 0 in the diagonal.
    node_properties :  data frame
        Data frame of neuron properties in adj.  Only necessary if used in conjunction with TAP or connectome utilities.
    max_simplices : bool
        If False counts all simplices in adj.
        If True counts only maximal simplices i.e., simplex motifs that are not contained in higher dimensional ones.
    max_dim : int
        Maximal dimension up to which simplex motifs are counted.
        The default max_dim = -1 counts all existing dimensions.  Particularly useful for large or dense graphs.
    simplex_type : string
        Type of simplex to consider:

        ’directed’ - directed simplices

        ’undirected’ - simplices in the underlying undirected graph

        ’reciprocal’ - simplices in the undirected graph of reciprocal connections
    nodes : 1d array or None(default)
        Restrict to list only the simplices whose source node is in nodes.  If None list all simplices

    Returns
    -------
    series
        Simplex lists indexed per dimension.  The dimension k entry is a (no. of k-simplices, k+1)-array
        is given, where each row denotes a simplex.

    Raises
    ------
    AssertionError
        If adj has non-zero entries in the diagonal which can produce errors.
    AssertionError
        If adj is not square.
    AssertionError
        If nodes is not a subarray of np.arange(N)

    See Also
    --------
    simplex_counts : A function that counts the simplices instead of listing them and has descriptions of the
    simplex types.
    """
    LOG.info("COMPUTE list of %ssimplices by dimension", "max-" if max_simplices else "")

    import pyflagsercount

    adj=sp.csr_matrix(adj)
    assert np.count_nonzero(adj.diagonal()) == 0, 'The diagonal of the matrix is non-zero and this may lead to errors!'
    N, M = adj.shape
    assert N == M, 'Dimension mismatch. The matrix must be square.'
    if not nodes is None:
        assert np.isin(nodes,np.arange(N)).all(), "nodes must be a subarray of the nodes of the matrix"

    #Symmetrize matrix if simplex_type is not 'directed'
    if simplex_type=='undirected':
        adj=sp.triu(underlying_undirected_matrix(adj)) #symmtrize and keep upper triangular only
    elif simplex_type=="reciprocal":
        adj=sp.triu(rc_submatrix(adj)) #symmtrize and keep upper triangular only

    n_threads = kwargs.get("threads", kwargs.get("n_threads", 1))


    # Only the simplices that have sources stored in this temporary file will be considered
    if not nodes is None:
        import tempfile
        import os
        tmp_file = tempfile.NamedTemporaryFile(delete=False)
        vertices_todo = tmp_file.name + ".npy"
        np.save(vertices_todo, nodes, allow_pickle=False)
    else:
        vertices_todo=''

    #Generate simplex_list
    original=pyflagsercount.flagser_count(adj, max_simplices=max_simplices,threads=n_threads,max_dim=max_dim,
                                      vertices_todo=vertices_todo, return_simplices=True)['simplices']

    #Remove temporary file
    if not nodes is None:
        os.remove(vertices_todo)

    #Format output
    max_dim = len(original)
    dims = pd.Index(np.arange(max_dim), name="dim")
    simplices = pd.Series(original, name="simplices", index=dims).apply(np.array)
    #When counting all simplices flagser doesn't list dim 0 and 1 because they correspond to vertices and edges
    if not max_simplices:
        if nodes is None:
            nodes=np.arange(0, N)
        coom = adj.tocoo()
        simplices[0] = np.reshape(nodes, (nodes.size, 1))
        mask=np.isin(coom.row,nodes)
        simplices[1] = np.stack([coom.row[mask], coom.col[mask]]).T
    return simplices

node_degree(adj, node_properties = None, direction = None, weighted = False, **kwargs)

Compute degree of nodes in network adj

Parameters:

Name Type Description Default
adj 2d array or sparse matrix

Adjacency matrix of the directed network. A non-zero entry adj[i,j] implies there is an edge from i to j of weight adj[i,j].

required
node_properties data frame

Data frame of neuron properties in adj. Only necessary if used in conjunction with TAP or connectome utilities.

None
direction string or tuple of strings

Direction for which to compute the degree

'IN' - In degree

'OUT'- Out degree

None or ('IN', 'OUT') - Total degree i.e. IN+OUT

None

Returns:

Type Description
series or data frame

Raises:

Type Description
Warning

If adj has non-zero entries in the diagonal

AssertionError

If direction is invalid

Source code in src/connalysis/network/topology.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
192
193
194
195
def node_degree(adj, node_properties=None, direction=None, weighted=False, **kwargs):
    """Compute degree of nodes in network adj
    Parameters
    ----------
    adj : 2d array or sparse matrix
        Adjacency matrix of the directed network.  A non-zero entry adj[i,j] implies there is an edge from i to j
        of weight adj[i,j].
    node_properties : data frame
        Data frame of neuron properties in adj. Only necessary if used in conjunction with TAP or connectome utilities.
    direction : string or tuple of strings
        Direction for which to compute the degree

        'IN' - In degree

        'OUT'- Out degree

        None or ('IN', 'OUT') - Total degree i.e. IN+OUT

    Returns
    -------
    series or data frame

    Raises
    ------
    Warning
        If adj has non-zero entries in the diagonal
    AssertionError
        If direction is invalid
    """
    assert not direction or direction in ("IN", "OUT") or tuple(direction) == ("IN", "OUT"),\
        f"Invalid `direction`: {direction}"

    if not isinstance(adj, np. ndarray):
        matrix = adj.toarray()
    else:
        matrix=adj.copy()
    if not weighted:
        matrix=matrix.astype('bool')
    if np.count_nonzero(np.diag(matrix)) != 0:
        logging.warning('The diagonal is non-zero!  This may cause errors in the analysis')
    index = pd.Series(range(matrix.shape[0]), name="node")
    series = lambda array: pd.Series(array, index)
    in_degree = lambda: series(matrix.sum(axis=0))
    out_degree = lambda: series(matrix.sum(axis=1))

    if not direction:
        return in_degree() + out_degree()

    if tuple(direction) == ("IN", "OUT"):
        return pd.DataFrame({"IN": in_degree(), "OUT": out_degree()})

    if tuple(direction) == ("OUT", "IN"):
        return pd.DataFrame({"OUT": out_degree(), "IN": in_degree()})

    return in_degree() if direction == "IN" else out_degree()

node_k_degree(adj, node_properties = None, direction = ('IN', 'OUT'), max_dim = -1, **kwargs)

Compute generalized degree of nodes in network adj. The k-(in/out)-degree of a node v is the number of k-simplices with all its nodes mapping to/from the node v.

Parameters:

Name Type Description Default
adj 2d array or sparse matrix

Adjacency matrix of the directed network. A non-zero entry adj[i,j] implies there is an edge from i to j of weight adj[i,j]. The matrix can be asymmetric, but must have 0 in the diagonal.

required
node_properties dataframe

Data frame of neuron properties in adj. Only necessary if used in conjunction with TAP or connectome utilities.

None
direction string

Direction for which to compute the degree

'IN' - In degree

'OUT'- Out degree

(’IN’, ’OUT’) - both

('IN', 'OUT')
max_dim int

Maximal dimension for which to compute the degree max_dim >=2 or -1 in which case it computes all dimensions.

-1

Returns:

Type Description
data frame

Table of of k-(in/out)-degrees

Raises:

Type Description
Warning

If adj has non-zero entries in the diagonal which are ignored in the analysis

AssertionError

If direction is invalid

AssertionError

If not max_dim >1

Notes

Note that the k-in-degree of a node v is the number of (k+1) simplices the node v is a sink of. Dually, the k-out-degree of a node v is the number of (k+1) simplices the node v is a source of.

Source code in src/connalysis/network/topology.py
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
234
235
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
def node_k_degree(adj, node_properties=None, direction=("IN", "OUT"), max_dim=-1, **kwargs):
    #TODO: Generalize from one population to another
    """Compute generalized degree of nodes in network adj.  The k-(in/out)-degree of a node v is the number of
    k-simplices with all its nodes mapping to/from the node v.
    Parameters
    ----------
    adj : 2d array or sparse matrix
        Adjacency matrix of the directed network.  A non-zero entry adj[i,j] implies there is an edge from i to j
        of weight adj[i,j].  The matrix can be asymmetric, but must have 0 in the diagonal.
    node_properties : dataframe
        Data frame of neuron properties in adj.  Only necessary if used in conjunction with TAP or connectome utilities.
    direction : string
        Direction for which to compute the degree

        'IN' - In degree

        'OUT'- Out degree

        (’IN’, ’OUT’) - both
    max_dim : int
        Maximal dimension for which to compute the degree max_dim >=2 or -1 in
        which case it computes all dimensions.

    Returns
    -------
    data frame
        Table of of k-(in/out)-degrees

    Raises
    ------
    Warning
        If adj has non-zero entries in the diagonal which are ignored in the analysis
    AssertionError
        If direction is invalid
    AssertionError
        If not max_dim >1

    Notes
    -----
    Note that the k-in-degree of a node v is the number of (k+1) simplices the node v is a sink of.
    Dually, the k-out-degree of a node v is the number of (k+1) simplices the node v is a source of.
    """
    matrix = sp.csr_matrix(adj)
    assert (max_dim > 1) or (max_dim==-1), "max_dim should be >=2"
    assert direction in ("IN", "OUT") or tuple(direction) == ("IN", "OUT"), \
        f"Invalid `direction`: {direction}"
    if np.count_nonzero(matrix.diagonal()) != 0:
        logging.warning('The diagonal is non-zero!  Non-zero entries in the diagonal will be ignored.')
    import pyflagsercount
    flagser_out = pyflagsercount.flagser_count(matrix, return_simplices=True, max_dim=max_dim)
    max_dim_possible = len(flagser_out['cell_counts']) - 1
    if max_dim==-1:
        max_dim = max_dim_possible
    elif max_dim > max_dim_possible:
        logging.warning("The maximum dimension selected is not attained")
        max_dim = max_dim_possible
    if (max_dim <= 1) and (max_dim!=-1):
        print("There are no simplices of dimension 2 or higher")
    else:
        index = pd.Series(range(matrix.shape[0]), name="node")
        generalized_degree = pd.DataFrame(index=index)
        for dim in np.arange(2, max_dim + 1):
            if "OUT" in direction:
                # getting source participation across dimensions
                x, y = np.unique(np.array(flagser_out['simplices'][dim])[:, 0], return_counts=True)
                generalized_degree[f'{dim}_out_degree'] = pd.Series(y, index=x)
            if "IN" in direction:
                # getting sink participation across dimensions
                x, y = np.unique(np.array(flagser_out['simplices'][dim])[:, dim], return_counts=True)
                generalized_degree[f'{dim}_in_degree'] = pd.Series(y, index=x)
        return generalized_degree.fillna(0)

node_participation(adj, node_properties = None, max_simplices = False, threads = 1, max_dim = -1, simplex_type = 'directed', **kwargs)

Compute the number of simplex motifs in the network adj each node is part of. See simplex_counts for details.

Parameters:

Name Type Description Default
adj 2d array or sparse matrix

Adjacency matrix of the directed network. A non-zero entry adj[i,j] implies there is an edge from i to j. The matrix can be asymmetric, but must have 0 in the diagonal.

required
node_properties dataframe

Data frame of neuron properties in adj. Only necessary if used in conjunction with TAP or connectome utilities.

None
max_simplices bool

If False (default) counts all simplices in adj. If True counts only maximal simplices i.e., simplex motifs that are not contained in higher dimensional ones.

False
max_dim int

Maximal dimension up to which simplex motifs are counted. The default max_dim = -1 counts all existing dimensions. Particularly useful for large or dense graphs.

-1
simplex_type string

Type of simplex to consider:

’directed’ - directed simplices

’undirected’ - simplices in the underlying undirected graph

’reciprocal’ - simplices in the undirected graph of reciprocal connections

'directed'

Returns:

Type Description
data frame

Indexed by the nodes in adj and with columns de dimension for which node participation is counted

Raises:

Type Description
AssertionError

If adj has non-zero entries in the diagonal which can produce errors.

AssertionError

If adj is not square.

Source code in src/connalysis/network/topology.py
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
def node_participation(adj, node_properties=None, max_simplices=False,
                       threads=1,max_dim=-1,simplex_type='directed',**kwargs):
    """Compute the number of simplex motifs in the network adj each node is part of.
    See simplex_counts for details.
    Parameters
    ----------
    adj : 2d array or sparse matrix
        Adjacency matrix of the directed network.  A non-zero entry adj[i,j] implies there is an edge from i to j.
        The matrix can be asymmetric, but must have 0 in the diagonal.
    node_properties : dataframe
        Data frame of neuron properties in adj.  Only necessary if used in conjunction with TAP or connectome utilities.
    max_simplices : bool
        If False (default) counts all simplices in adj.
        If True counts only maximal simplices i.e., simplex motifs that are not contained in higher dimensional ones.
    max_dim : int
        Maximal dimension up to which simplex motifs are counted.
        The default max_dim = -1 counts all existing dimensions.  Particularly useful for large or dense graphs.
    simplex_type : string
        Type of simplex to consider:

        ’directed’ - directed simplices

        ’undirected’ - simplices in the underlying undirected graph

        ’reciprocal’ - simplices in the undirected graph of reciprocal connections

    Returns
    -------
    data frame
        Indexed by the nodes in adj and with columns de dimension for which node participation is counted

    Raises
    -------
    AssertionError
        If adj has non-zero entries in the diagonal which can produce errors.
    AssertionError
        If adj is not square.
    """

    adj=sp.csr_matrix(adj).astype('bool')
    assert np.count_nonzero(adj.diagonal()) == 0, 'The diagonal of the matrix is non-zero and this may lead to errors!'
    N, M = adj.shape
    assert N == M, 'Dimension mismatch. The matrix must be square.'


    #Symmetrize matrix if simplex_type is not 'directed'
    if simplex_type=='undirected':
        adj=sp.triu(underlying_undirected_matrix(adj)) #symmtrize and keep upper triangular only
    elif simplex_type=="reciprocal":
        adj=sp.triu(rc_submatrix(adj)) #symmtrize and keep upper triangular only

    flagser_counts = _flagser_counts(adj, count_node_participation=True, threads=threads,
                                     max_simplices=max_simplices, max_dim=max_dim)
    return flagser_counts["node_participation"]

normalized_simplex_counts(adj, node_properties = None, max_simplices = False, threads = 1, max_dim = -1, **kwargs)

Compute the ratio of directed/undirected simplex counts normalized to be between 0 and 1. See simplex_counts and undirected_simplex_counts for details.

Parameters:

Name Type Description Default
adj 2d array or sparse matrix

Adjacency matrix of the directed network. A non-zero entry adj[i,j] implies there is an edge from i to j of weight adj[i,j]. The matrix can be asymmetric, but must have 0 in the diagonal.

required
node_properties dataframe

Data frame of neuron properties in adj. Only necessary if used in conjunction with TAP or connectome utilities.

None
max_simplices bool

If False counts all simplices in adj. If True counts only maximal simplices i.e., simplex motifs that are not contained in higher dimensional ones.

False
max_dim int

Maximal dimension up to which simplex motifs are counted. The default max_dim = -1 counts all existing dimensions. Particularly useful for large or dense graphs.

-1

Returns:

Type Description
panda series

Normalized simplex counts

Raises:

Type Description
AssertionError

If adj has non-zero entries in the diagonal which can produce errors.

Notes

Maybe we should say why we choose this metric

Source code in src/connalysis/network/topology.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def normalized_simplex_counts(adj, node_properties=None,
                   max_simplices=False, threads=1,max_dim=-1,
                   **kwargs):
    """Compute the ratio of directed/undirected simplex counts normalized to be between 0 and 1.
    See simplex_counts and undirected_simplex_counts for details.
    Parameters
    ----------
    adj : 2d array or sparse matrix
        Adjacency matrix of the directed network.  A non-zero entry adj[i,j] implies there is an edge from i to j
        of weight adj[i,j].  The matrix can be asymmetric, but must have 0 in the diagonal.
    node_properties : dataframe
        Data frame of neuron properties in adj.  Only necessary if used in conjunction with TAP or connectome utilities.
    max_simplices : bool
        If False counts all simplices in adj.
        If True counts only maximal simplices i.e., simplex motifs that are not contained in higher dimensional ones.
    max_dim : int
        Maximal dimension up to which simplex motifs are counted.
        The default max_dim = -1 counts all existing dimensions.  Particularly useful for large or dense graphs.

    Returns
    -------
    panda series
        Normalized simplex counts

    Raises
    ------
    AssertionError
        If adj has non-zero entries in the diagonal which can produce errors.

    Notes
    -----
    Maybe we should say why we choose this metric"""

    from scipy.special import factorial
    denominator=simplex_counts(adj, node_properties=node_properties,max_simplices=max_simplices,
                                          threads=threads,max_dim=max_dim,simplex_type='undirected', **kwargs).to_numpy()
    #Global maximum dimension since every directed simplex has an underlying undirected one of the same dimension
    max_dim_global=denominator.size
    #Maximum number of possible directed simplices for each undirected simplex across dimensions
    max_possible_directed=np.array([factorial(i+1) for i in np.arange(max_dim_global)])
    denominator=np.multiply(denominator, max_possible_directed)
    numerator=simplex_counts(adj, node_properties=node_properties,max_simplices=max_simplices,
                             threads=threads,max_dim=max_dim,simple_type='directed', **kwargs).to_numpy()
    numerator=np.pad(numerator, (0, max_dim_global-len(numerator)), 'constant', constant_values=0)
    return _series_by_dim(np.divide(numerator,denominator)[1:],name="normalized_simplex_counts",
                          index=np.arange(1,max_dim_global), name_index="dim")

rc_submatrix(adj)

Returns the symmetric submatrix of reciprocal connections of adj

Parameters:

Name Type Description Default
adj 2d array or sparse matrix

Adjacency matrix of the directed network. A non-zero entry adj[i,j] implies there is an edge from i to j.

required

Returns:

Type Description
sparse matrix

symmetric matrix of the same dtype as adj of reciprocal connections

Source code in src/connalysis/network/topology.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def rc_submatrix(adj):
    """Returns the symmetric submatrix of reciprocal connections of adj
    Parameters
    ----------
    adj : 2d array or sparse matrix
        Adjacency matrix of the directed network.  A non-zero entry adj[i,j] implies there is an edge from i to j.

    Returns
    -------
    sparse matrix
        symmetric matrix of the same dtype as adj of reciprocal connections
    """
    adj=sp.csr_matrix(adj)
    if np.count_nonzero(adj.diagonal()) != 0:
        logging.warning('The diagonal is non-zero and this may lead to errors!')
    mask=adj.copy().astype('bool')
    mask=(mask.multiply(mask.T))
    mask.eliminate_zeros
    return adj.multiply(mask).astype(adj.dtype)

simplex_counts(adj, node_properties = None, max_simplices = False, threads = 1, max_dim = -1, simplex_type = 'directed', **kwargs)

Compute the number of simplex motifs in the network adj.

Parameters:

Name Type Description Default
adj 2d array or sparse matrix

Adjacency matrix of the directed network. A non-zero entry adj[i,j] implies there is an edge from i to j of weight adj[i,j]. The matrix can be asymmetric, but must have 0 in the diagonal.

required
node_properties dataframe

Data frame of neuron properties in adj. Only necessary if used in conjunction with TAP or connectome utilities.

None
max_simplices bool

If False counts all simplices in adj. If True counts only maximal simplices i.e., simplex motifs that are not contained in higher dimensional ones.

False
max_dim int

Maximal dimension up to which simplex motifs are counted. The default max_dim = -1 counts all existing dimensions. Particularly useful for large or dense graphs.

-1
simplex_type

Type of simplex to consider (See Notes):

’directed’ - directed simplices

’undirected’ - simplices in the underlying undirected graph

’reciprocal’ - simplices in the undirected graph of reciprocal connections

'directed'

Returns:

Type Description
series

simplex counts

Raises:

Type Description
AssertionError

If adj has non-zero entries in the diagonal which can produce errors.

AssertionError

If adj is not square.

Notes

A directed simplex of dimension k in adj is a set of (k+1) nodes which are all to all connected in a feedforward manner. That is, they can be ordered from 0 to k such that there is an edge from i to j whenever i < j.

An undirected simplex of dimension k in adj is a set of (k+1) nodes in adj which are all to all connected. That is, they are all to all connected in the underlying undirected graph of adj. In the literature this is also called a (k+1)-clique of the underlying undirected graph.

A reciprocal simplex of dimension k in adj is a set of (k+1) nodes in adj which are all to all reciprocally connected. That is, they are all to all connected in the undirected graph of reciprocal connections of adj. In the literature this is also called a (k+1)-clique of the undirected graph of reciprocal connections.

Source code in src/connalysis/network/topology.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def simplex_counts(adj, node_properties=None,max_simplices=False,
                   threads=1,max_dim=-1, simplex_type='directed', **kwargs):
    """Compute the number of simplex motifs in the network adj.
    Parameters
    ----------
    adj : 2d array or sparse matrix
        Adjacency matrix of the directed network.  A non-zero entry adj[i,j] implies there is an edge from i to j
        of weight adj[i,j].  The matrix can be asymmetric, but must have 0 in the diagonal.
    node_properties : dataframe
        Data frame of neuron properties in adj.  Only necessary if used in conjunction with TAP or connectome utilities.
    max_simplices : bool
        If False counts all simplices in adj.
        If True counts only maximal simplices i.e., simplex motifs that are not contained in higher dimensional ones.
    max_dim : int
        Maximal dimension up to which simplex motifs are counted.
        The default max_dim = -1 counts all existing dimensions.  Particularly useful for large or dense graphs.
    simplex_type: string
        Type of simplex to consider (See Notes):

        ’directed’ - directed simplices

        ’undirected’ - simplices in the underlying undirected graph

        ’reciprocal’ - simplices in the undirected graph of reciprocal connections

    Returns
    -------
    series
        simplex counts

    Raises
    ------
    AssertionError
        If adj has non-zero entries in the diagonal which can produce errors.
    AssertionError
        If adj is not square.

    Notes
    -----
    A directed simplex of dimension k in adj is a set of (k+1) nodes which are all to all connected in a feedforward manner.
    That is, they can be ordered from 0 to k such that there is an edge from i to j whenever i < j.

    An undirected simplex of dimension k in adj is a set of (k+1) nodes in adj which are all to all connected.  That is, they
    are all to all connected in the underlying undirected graph of adj.  In the literature this is also called a (k+1)-clique
    of the underlying undirected graph.

    A reciprocal simplex of dimension k in adj is a set of (k+1) nodes in adj which are all to all reciprocally connected.
    That is, they are all to all connected in the undirected graph of reciprocal connections of adj.  In the literature this is
    also called a (k+1)-clique of the undirected graph of reciprocal connections.
    """
    adj=sp.csr_matrix(adj)
    assert np.count_nonzero(adj.diagonal()) == 0, 'The diagonal of the matrix is non-zero and this may lead to errors!'
    N, M = adj.shape
    assert N == M, 'Dimension mismatch. The matrix must be square.'


    #Symmetrize matrix if simplex_type is not 'directed'
    if simplex_type=='undirected':
        adj=sp.triu(underlying_undirected_matrix(adj)) #symmtrize and keep upper triangular only
    elif simplex_type=="reciprocal":
        adj=sp.triu(rc_submatrix(adj)) #symmtrize and keep upper triangular only

    flagser_counts = _flagser_counts(adj, threads=threads, max_simplices=max_simplices, max_dim=max_dim)
    if max_simplices:
        return flagser_counts["max_simplex_counts"]
    else:
        return flagser_counts["simplex_counts"]

underlying_undirected_matrix(adj)

Returns the symmetric matrix of undirected connections of adj.

Parameters:

Name Type Description Default
adj 2d array or sparse matrix

Adjacency matrix of the directed network. A non-zero entry in adj[i][j] implies there is an edge from vertex i to vertex j.

required

Returns:

Type Description
sparse boolean matrix

Corresponding to the symmetric underlying undirected graph

Source code in src/connalysis/network/topology.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def underlying_undirected_matrix(adj):
    """Returns the symmetric matrix of undirected connections of `adj`.
    Parameters
    ----------
    adj : 2d array or sparse matrix
        Adjacency matrix of the directed network.  A non-zero entry in `adj[i][j]` implies there is an edge from vertex `i` to vertex `j`.

    Returns
    -------
    sparse boolean matrix
        Corresponding to the symmetric underlying undirected graph
    """
    adj=sp.csr_matrix(adj)
    if np.count_nonzero(adj.diagonal()) != 0:
        logging.warning('The diagonal is non-zero and this may lead to errors!')
    return (adj+adj.T).astype('bool')