在 graph_tool 中设置默认值 属性

Setting default property value in graph_tool

我需要计算图中每个顶点满足给定条件(例如,"ACondition")的次数。为此,我需要确保顶点 属性 被初始化为零,我明确地这样做了。请参阅下面的代码。

# 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

有没有办法指定 属性 的默认值,这样我就不需要明确设置它的初始值(即上面的第二个代码块)?

new_vertex_property 接受将用于初始化 属性 的单个值或序列:g1.new_vertex_property("int32_t", 0)


我不确定你为什么说你"need to make sure that the vertex property is initialized to zero",因为如果你不提供默认值,它无论如何都会被初始化为零:

>>> 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)

如果属性是一个真值,你应该用bool代替。

您还可以使用 sum and get_array() 来计算满意的属性。

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)