JWS
JWS

Reputation: 335

Using graph generator with a custom class as node

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

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

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

And here I create a single agent, which I would like to use as a node instead of integers:

from agents import Agent
agent = Agent()

I wonder if the answer to this involves creating a network and then relabeling the nodes with nx.relabel_nodes().

Upvotes: 3

Views: 723

Answers (1)

johntellsall
johntellsall

Reputation: 15170

Networkx seems to really want to use IDs, not concrete 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>]

Upvotes: 5

Related Questions