How to extract weights from SimpleWeightedEdge (from kruskal_mst)

I’m trying to figure out how to interact with a minimal spanning tree object returned by Graphs.kruskal_mst(). I just can’t figure out how to extract the resulting edge wights (or the edges).

Here’s a minimal code to show the issue:

using Distributions
using Graphs
using SimpleWeightedGraphs
using Distances

M = reshape(rand(Normal(), 100), 10, 10)
g = SimpleWeightedGraph(pairwise(Euclidean(), M, dims = 1))
my_mst = Graphs.kruskal_mst(g)

# when inspecting the object
julia> my_mst
9-element Vector{SimpleWeightedEdge{Int64, Float64}}:
 Edge 2 => 8 with weight 2.3668794009593306
 Edge 1 => 10 with weight 2.4514610105905223
 Edge 1 => 9 with weight 2.4717071330626306
 Edge 6 => 8 with weight 2.714304985226182
 Edge 3 => 9 with weight 3.507507419474672
 Edge 4 => 9 with weight 4.113153232605692
 Edge 1 => 7 with weight 4.1630221327329044

julia> my_mst[1]
Edge 2 => 8 with weight 2.3668794009593306

My goal here is just to get a vector of the edge weights. I’ve tried a bunch of thing, treating it as a dictionary, trying to convert it back to a graph, trying to extract the edges, but nothing works. I’m sure it’s a simple solution but I can’t track it down.

Hi there!
Don’t hesitate to ask the REPL for help, it is my best friend in such cases.

julia> typeof(my_mst[1])
SimpleWeightedEdge{Int64, Float64}

help?> SimpleWeightedEdge
search: SimpleWeightedEdge SimpleWeightedGraphEdge SimpleWeightedDiGraphEdge

  No documentation found.


  struct SimpleWeightedEdge{T<:Integer, U<:Real}


  src    :: T<:Integer
  dst    :: T<:Integer
  weight :: U<:Real

  Supertype Hierarchy

  SimpleWeightedEdge{T<:Integer, U<:Real} <: AbstractSimpleWeightedEdge{T<:Integer} <: AbstractEdge{T<:Integer} <: Any

julia> my_mst[1].weight

Spectacular. I’m not sure I would have understand the syntax even looking at the REPL. But this definitely will help for future issues. Thanks!

Glad that it solved your problem, don’t hesitate to mark the answer as a solution so that others know they don’t need to pile on :wink:
I deduced the solution by looking at the fields of the SimpleWeightedEdge type, which can be accessed with the object.field syntax. The help mode of the REPL, which I used to do that, can be accessed by typing ? as the first character

It’s generally considered bad practice to access internal fields directly, you should prefer the accessor weight(e::AbstractSimpleWeightedEdge). The documentation can probably be improved in this regard.

1 Like

Actually @JedPhillips maybe it would be better to mark the answer by @etienne_dg as the right solution