graph-tool: how to access properties?
Asked Answered
N

1

6

I would like to store instances of a class in a graph-tool graph, one object per node (or 'vertex' as graph-tool calls them). I am trying to use a vertex property as that seems to the be the way to do this.

class MyClass(object):
    def __init__(self, title):
        self.title = title

graph  = Graph()
my_obj = MyClass('some title')

vertex = graph.add_vertex()
vprop  = graph.new_vertex_property('object')
vprop[vertex] = my_obj

Now I would like to read my class objects back out, e.g. iterate over all nodes / vertices and print their titles:

for vertex in self.graph.vertices():
    # TODO: how to access titles ? this just prints
    # "<Vertex object with index '0' at 0xb1e4bac>"
    print repr(vertex) + '\n'

Also, how do I get a class object with a certain title back from the graph ? One way seems to be to create a vertex filter using graph.set_edge_filter(...) and apply that - which seems a pretty expensive operation considering all I want is to get one single object back. I really don't want to maintain my own object title / vertex index mapping as IMO, that is one of the tasks of the graph.

Am I missing something fundamental here ?

Nitrate answered 2/3, 2012 at 1:34 Comment(0)
T
5

In order to access the property values, you use the same syntax you used to set its value, i.e.,

    for vertex in graph.vertices():
        print vprop[vertex].title

will do what you want.

If you want to obtain vertices with a given property value, you have no option but to search for it in the graph. Remember that property values do not need to be unique, so there is no way to perform the reverse mapping in an inexpensive manner. Furthermore, there would need to be a reverse mapping for each property map, which would be expensive memory-wise. However, you could easily do this on your own with a dict object.

Throckmorton answered 9/4, 2012 at 13:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.