DaveR
DaveR

Reputation: 2358

how to create a network with node and edges from nested data structure?

I have a nested data structure, in which each element can be either iterable or not. I would like to build a graph which transforms this nested data structure in a network (I thought of the networkx package for that). Each element is a Tuple with (ID, value) in which value can be an integer or an Iterable.

My final graph should look something like this, in which each arrow is like an edge to all the indented elements (i.e. mainbox1 is connected to bigbox2, smallbox3, mediumbox4)

mainbox1 --> 
            bigbox2 -->
                        mediumbox5
                        smallbox6
            smallbox3
            mediumbox4 -->
                        smallbox7

I struggle to create an algorithm that does what I want. I thought it should be recursive (add each item until there is no more nesting) but I did not succeed in writing the implementation.

This was my starting point.

import networkx as nx

example = [('mainbox1',[('bigbox2', [('mediumbox5'),
                                   ('smallbox6')]),
                        ('smallbox3'),
                        ('mediumbox4', ('smallbox7'))
                        ] )]

Upvotes: 0

Views: 408

Answers (1)

vx3r
vx3r

Reputation: 295

There is some problems with tuples in your example data. I made some corrections and this code works

import networkx as nx


def rec_make(g, root, nodes):
    for node in nodes:
        g.add_edge(root, node[0])

        if isinstance(node[1], list):
            rec_make(g, node[0], node[1])


def main():
    g = nx.Graph()

    example = [('mainbox1', [('bigbox2', [
        ('mediumbox5', 5),
        ('smallbox6', 6)
    ]), ('smallbox3', 3), ('mediumbox4', [
        ('smallbox7', 7)
    ])])]

    rec_make(g, example[0][0], example[0][1])

    print("Nodes in G: ", g.nodes())
    print("Edges in G: ", g.edges())

Your are getting exactly what you want:

Nodes in G:  ['mainbox1', 'bigbox2', 'mediumbox5', 'smallbox6', 'smallbox3', 'mediumbox4', 'smallbox7']
Edges in G:  [('mainbox1', 'bigbox2'), ('mainbox1', 'smallbox3'), ('mainbox1', 'mediumbox4'), ('bigbox2', 'mediumbox5'), ('bigbox2', 'smallbox6'), ('mediumbox4', 'smallbox7')]

Upvotes: 2

Related Questions