Search code examples
graphtypesjuliadirected-graph

Julia DiGraph with user-defined object as nodes


In Julia, I can easily create a graph using the very nicely written Graphs.jl library:

julia> using Graphs
julia> g = SimpleDiGraph(2)
{2, 0} directed simple Int64 graph
julia> add_edge!(g, 1,2)
true
julia> add_edge!(g, 2, 1)
true

However, I cannot seem to make the nodes anything other than integers. To wit, I would like to do something like this:

julia> using Graphs
julia> abstract type Foo end
julia> s = SimpleDiGraph(typeof(Foo)) # doesn't work.
julia> mutable struct Bar <: Foo
           b::Bool
       end
julia> mutable struct Baz <: Foo
           b::Bool
       end
julia> bar = Bar(true)
Bar(true)
julia> baz = Baz(false)
Baz(false)
julia> add_edge!(g, bar, baz) # Again, doesn't work.

How can I make the nodes a custom type?

Note: I have tried the following workaround, as it appears that only integral types are allowed in the nodes:

julia> add_edge!(g, Int64(pointer_from_objref(bar)), Int64(pointer_from_objref(baz)))

but this one, although not throwing an exception, returns false.


Solution

  • In the Graphs.jl tutorial, it is stated that "integers, and only integers, may be used for describing vertices." So my first goal is out of the question (although it may be possible in, say, MetaGraphs.jl). The recommendation is to use the integer value in the vertex as an index into a vector and store the objects in the vector.

    Moreover, as it is stated that the goal is to index into a vector, the integers must be contiguous, and hence my second idea of using the address of the object is also not feasible.

    However, using the graph to index into a vector is a perfectly acceptable solution for me.