Search code examples
pythongraphnodestensoredge-list

Converting tensors to edgelists


So i have a .mat file which consists of some tensors and i have to convert these tensors into another file with extension .edgelist with 2 columns, one representing the node1 and the other column separated by a space with the first one should consist of the node2 (Python code)

This is the tensor (:,:,1) =

Columns 1 through 18

     0    0.0176    0.1474         0    0.1179    0.2053    0.1075    0.1579    0.1890    0.0372    0.1620    0.1454    0.1484    0.1464    0.1164    0.1656    0.0936    0.1256
0.0176         0    0.1651    0.0176    0.1355    0.2229    0.1251    0.1755    0.2066    0.0548    0.1796    0.1630    0.1660    0.1640    0.1340    0.1832    0.1112    0.1432
0.1474    0.1651         0    0.1474    0.0296    0.0578    0.0399    0.0105    0.0416    0.1103    0.0146    0.0020    0.0010    0.0010    0.0310    0.0182    0.0539    0.0219
     0    0.0176    0.1474         0    0.1179    0.2053    0.1075    0.1579    0.1890    0.0372    0.1620    0.1454    0.1484    0.1464    0.1164    0.1656    0.0936    0.1256

Desired output

1 32
1 22
1 20
1 18
1 14
1 13
1 12
1 11
1 9
1 8
1 7
1 6
1 5
1 4
1 3
1 2
2 31
2 22
2 20
2 18
2 14
2 8
2 4
2 3
3 14
3 9
3 10
3 33
3 29
3 28
3 8
3 4
4 14
4 13
4 8
5 11
5 7

Solution

  • So basically, all you have to do is build a simple python code. Our tensor matrix with 35x35 dimension (frontal view of a tensor) consist of 35 nodes and each decimal number is the weight of the connection between two nodes. So as long as the there is 0 weight means that two nodes are not connected to each other. So based on these facts we create an edge-list file which corresponds to 2 columns (node1_index node2_index)

    def adj_to_edgelist(input_filename,output_filename,delimiter):
    A=pd.read_csv(input_filename,delimiter=delimiter,index_col=0)
    List=[]
    for source in A.index.values:
        for target in A.index.values:
            #List.append((target,source,A[source][target]))
            #if we want to write the weight of edges we write the above line of code
            List.append((target,source,"\n"))
            print("\n")
    with open(output_filename, "w") as f:
        writer = csv.writer(f)
        writer.writerows(List)
    return List