Using a graph generator with a custom class as node

I would like to use some built in graph generators but with a custom python class as nodes instead of integers. What's the best approach for this? Should I add a custom class as an attribute?

For example, here I am generating a complete graph with integers as nodes:

import networkx as nx
K_5 = nx.complete_graph(5)

      

And here I am creating a single agent that I would like to use as node instead of integers:

from agents import Agent
agent = Agent()

      

Interestingly, the answer to this question has to do with creating the network and then reworking the nodes with nx.relabel_nodes()

.

+3


source to share


1 answer


Networkx seems to really want to use IDs and not specific objects. However, your idea is correct - we can use relabel_nodes()

to convert numbers to object instances.

Demo:

Source



import networkx as nx

class Agent(object):
    def __init__(self, id):
        self.id = id
    def __repr__(self):
        return '<Agent #{}>'.format(self.id)


g = nx.complete_graph(5)
print g.nodes()

nx.relabel_nodes(g, mapping=Agent, copy=False)
print g.nodes()

      

Output

[0, 1, 2, 3, 4]

[<Agent #1>, <Agent #3>, <Agent #0>, <Agent #4>, <Agent #2>]

      

+4


source







All Articles