I am looking for a way to either get or set a vertex property for all vertices of the graph at once. The two functions will be:
getVertexProp[g_?GraphQ, prop_] := ...
setVertexProp[g_?GraphQ, prop_, values_] := ...
getVertexProp
must return a list of values. Each value corresponds to the respective vertex in VertexList[g]
. When one particular vertex does not have this property, the list must contain Missing["Nonexistent"]
.
setVertexProp
must set a property when given a similar list.
Requirements
The functions must work with any property, either built-in or custom. getVertexProperty
should work even if a property is set only for some of the vertices.
I suggest testing the implementation at least with:
- Properties
VertexWeight
,VertexStyle
, and"foo"
. - The two graphs
g1 = RandomGraph[{10,20}]
andg2 = Graph[VertexList[g1], EdgeList[g1]]
. - Setting the same property twice on both graphs above (to test overwriting).
Example implementation
getVertexProp[g_?GraphQ, prop_] :=
Replace[PropertyValue[{g, #}, prop], $Failed -> Missing["Nonexistent"]] & /@ VertexList[g]
setVertexProp[g_?GraphQ, prop_, values_] :=
If[
Length[values] =!= VertexCount[g],
$Failed,
Fold[SetProperty[{#1, #2[[1]]}, prop -> #2[[2]]] &, g, Transpose[{VertexList[g], values}]]
]
I am looking for an implementation that performs better than these.
Benchmark:
g = ExampleData[{"NetworkGraph", "BipartiteDiseasomeNetwork"}];
values = getVertexProp[g, "Type"]; // RepeatedTiming
(* {0.0080, Null} *)
setVertexProp[g, "Foo", values]; // AbsoluteTiming
(* {15.3572, Null} *)
getVertexProp
is fine, but there is a potential for speedup. Compare these two methods of retrieving edge properties:
rg = RandomGraph[{1000, 10000}, EdgeCapacity -> RandomReal[1, 10000]];
PropertyValue[{rg, #}, EdgeWeight -> EdgeCapacity] & /@ EdgeList[rg]; // RepeatedTiming
(* {0.040, Null} *)
WeightedAdjacencyMatrix[rg]["NonzeroValues"]; // RepeatedTiming
(* {0.0000189, Null} *)
Unfortunately, this implementation of setVertexProp
is unusably slow.
A different implementation could special-case each type of graph property, but this is ugly and error-prone.