JosephD
JosephD

Reputation: 319

Setting default property value in graph_tool

I need to count how many times a given condition (e.g., "ACondition") is satisfied for each vertex in a graph. To do so, I need to make sure that the vertex property is initialized to zero, which I do explicitly. See the code below.

# Instantiates the graph object and the vertex property. 
import graph_tool.all as gt
g1 = gt.Graph()
g1.vp.AProperty = g1.new_vertex_property("int32_t")

# Sets the vertex property to zero (prior to counting).
for v1 in g1.vertices():
    g1.vp.AProperty[v1] = 0

# Counts the number of times "ACondition" is satisfied for each vertex.
for v1 in g1.vertices():
    if(ACondition == True):
        g1.vp.AProperty[v1] += 1

Is there a way to specify a default value of a property so that I don't need to set its initial value explicitly (i.e, the second block of code above)?

Upvotes: 0

Views: 419

Answers (1)

arekolek
arekolek

Reputation: 9611

new_vertex_property accepts a single value or a sequence that will be used to initialize the property: g1.new_vertex_property("int32_t", 0)


I'm not sure why you say you "need to make sure that the vertex property is initialized to zero", because if you don't provide a default, it will be initialized to zero anyway:

>>> g = gt.Graph()
>>> g.add_vertex(10)
>>> g.new_vertex_property('int').a
PropertyArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)

If the property is a truth value, you should use bool instead.

You can also use sum and get_array() to count satisfied properties.

import graph_tool.all as gt
g = gt.Graph()

# Initialize property foo with False value
g.vp['foo'] = g.new_vertex_property('bool')

# How many vertices satisfy property foo
sum(g.vp['foo'].a)

Upvotes: 1

Related Questions