Friday, 24 September 2021

Construct graph connectivity matrices in COO format

I have faced the following subtask while working with graph data:

I need to construct graph connectivity matrices in COO format for graphs with several fully-connected components from arrays of "border" indices.

As an example, given array

borders = [0, 2, 5]

the resulting COO matrix should be

coo_matrix = [[0, 0, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4],
              [0, 1, 0, 1, 2, 3, 4, 2, 3, 4, 2, 3, 4]].

That is, borders array contains ranges of nodes that should form fully-connected subgraphs (starting index included and ending index excluded).

I came up with the following algorithm, but I suspect that the perfomance could be improved:

import numpy as np

def get_coo(borders):

    edge_list = []
    for s, e in zip(borders, borders[1:]):
        
        # create fully-connected subgraph
        arr = np.arange(s, e)
        t = np.array(np.meshgrid(arr, arr)).T.reshape(-1, 2)
        t = t.T

        edge_list.append(t)

    edge_list = np.concatenate(edge_list, axis=1)

    return edge_list

I feel there may be a faster solution, maybe using some numpy vectorized operations.

Does anyone have any ideas?



from Construct graph connectivity matrices in COO format

No comments:

Post a Comment