# How to set EdgeWeights in SpatialGraphDistribution?

I have a table of random geometric graphs

graphs = Table[
RandomGraph[
SpatialGraphDistribution[
RandomVariate[PoissonDistribution], 0.2]], {k, 1,
10}];


but I need the EdgeWeights of each graph to be the Euclidean distances between the vertices of the respective edge. At the moment they are all unity.

I tried using

graphs = SetProperty[#,
EdgeWeight -> EuclideanDistance @@@ EdgeList[#]] & /@ graphs;


but this obviously requires the vertex names to be position vectors. I also tried using

vertlist[graph_] :=
VertexCoordinates /. AbsoluteOptions[graph, VertexCoordinates]


with another function which threads over the edges, but it seems inelegant...

Is there a simpler way?

• Can you just set the VertexNames as VertexCoordinates via SetProperty, then again use SetProperty[#, EdgeWeight -> EuclideanDistance @@@ EdgeList[#]] & /@ graphs?
– apg
Mar 1, 2018 at 14:52
• If you want to replace the vertex names with the vertex coordinates, you could use VertexReplace[rg, Thread[VertexList[rg] -> GraphEmbedding[rg]]] Mar 1, 2018 at 15:55
• I'm thinking about what would be a good general way to deal with similar problems. I could extend IGraph/M with a new property operator IGEdgeVertexProp (not sure what's a good name...) which could be used as IGEdgeMap[Apply[EuclideanDistance], EdgeWeight -> IGEdgeVertexProp[VertexCoordinates], rg]. I'm not 100% happy with this though ... Any feedback is welcome. Mar 1, 2018 at 15:56

You could use something like this:

rg = RandomGraph[SpatialGraphDistribution[RandomVariate[PoissonDistribution], 0.2]]

dist = EuclideanDistance @@@
Map[PropertyValue[{rg, #}, VertexCoordinates] &, EdgeList[rg], {2}];

SetProperty[
rg,
EdgeWeight -> dist
]


An alternative solution is

Graph[rg,
EdgeWeight -> {edge_ :> Apply[EuclideanDistance]@Map[PropertyValue[{rg, #}, VertexCoordinates] &]@edge}
]


What seems to be unavoidable is to first create the graph and assign it to a variable, then refer back to that variable. This is a general "problem" with the current design of the graph framework. It's a problem in the sense that doing this feels un-Mathematica-like.

• Thank you, that should be fine.
– apg
Mar 1, 2018 at 15:35