monora/rgl

Unclear how to use bellman_ford_shortest_paths method

readyready15728 opened this issue · 2 comments

I'm trying to figure out how to use this method with no luck. I'm a bit new to Ruby but as far as I can tell AdjacencyGraph should mix in this method by virtue of inheriting from DirectedAdjacencyGraph and its mix-ins. Here is a session of me trying to make a trivial graph and then access the method:

[1] pry(main)> require 'rgl/adjacency'
=> true
[2] pry(main)> RGL::AdjacencyGraph
RGL::AdjacencyGraph
[2] pry(main)> g = RGL::AdjacencyGraph.new
=> #<RGL::AdjacencyGraph:0x000055820af89cd8 @edgelist_class=Set, @vertices_dict={}>
[3] pry(main)> g.add_edge(:a, :b)
=> #<Set: {:a}>
[4] pry(main)> g.add_edge(:b, :d)
=> #<Set: {:b}>
[5] pry(main)> g
=> #<RGL::AdjacencyGraph:0x000055820af89cd8 @edgelist_class=Set, @vertices_dict={:a=>#<Set: {:b}>, :b=>#<Set: {:a, :d}>, :d=>#<Set: {:b}>}>
[6] pry(main)> g.add_edge(:b, :c)
=> #<Set: {:b}>
[7] pry(main)> g.add_edge(:c, :e)
=> #<Set: {:c}>
[8] pry(main)> g.edges
=> [(a-b), (b-d), (b-c), (c-e)]
[9] pry(main)> g.bellman_ford_shortest_paths
NoMethodError: undefined method `bellman_ford_shortest_paths' for #<RGL::AdjacencyGraph:0x000055820af89cd8>
from (pry):9:in `__pry__'

I'm also not sure how edge_weights_map is specified.

AdjacencyGraph should mix in this method by virtue of inheriting from DirectedAdjacencyGraph

No, you have to require 'rgl/bellman_ford' explicitly. This will mixin the method into module Graph and therefore also into DirectedAdjacencyGraph.

I'm also not sure how edge_weights_map is specified.

The method bellman_ford_shortest_paths needs as first parameter a map which assigns each edge a weight, needed to compute the distance of paths (see https://www.rubydoc.info/github/monora/rgl/RGL/Graph:bellman_ford_shortest_paths)

Please have a look at the tests in bellman_ford_test.rb or try this:

2.6.3 :001 > require 'rgl/adjacency'
 => true 
2.6.3 :002 > require 'rgl/bellman_ford'
 => true
2.6.3 :003 > g = RGL::AdjacencyGraph[1,2, 1,3, 2,3, 2,4, 3,4]
 => #<RGL::AdjacencyGraph:0x000055b407ec4cb0 @edgelist_class=Set, @vertices_dict={1=>#<Set: {2, 3}>, 2=>#<Set: {1, 3, 4}>, 3=>#<Set: {1, 2, 4}>, 4=>#<Set: {2, 3}>}> 
2.6.3 :004 > edge_weights = {
        [1, 2] => 10,
        [1, 3] => 1,
        [2, 3] => 1,
        [2, 4] => 1,
        [3, 4] => 10
    }
2.6.3 :011 > g.bellman_ford_shortest_paths(edge_weights, 1)
 => {1=>[1], 2=>[1, 3, 2], 3=>[1, 3], 4=>[1, 3, 2, 4]} 

Excellent response. It would be nice if there was more example code showing more of the library's usage but until that and / or more documentation happens going through the test units seems like a useful approach.