Everything is connected
Railway lines, friendships, links between web pages, paths in a wood: much of the world is things and the connections between them. Mathematics calls that a graph – the nodes are the things, the edges the connections. In Python, NetworkX is the best-known library for them, and networkx.rb brings it to Ruby; Athitya Kumar started it, and today it belongs to SciRuby.
Our graph is a piece of the Swiss rail network. Every edge gets a weight, weight: the travel time in minutes, roughly.
install_gem "networkx"
require "networkx"
rail = NetworkX::Graph.new
# from, to, travel time in minutes (roughly)
[["Zurich", "Bern", 56], ["Zurich", "Basel", 53], ["Bern", "Basel", 55],
["Zurich", "Lucerne", 41], ["Bern", "Lucerne", 60], ["Basel", "Lucerne", 60],
["Bern", "Lausanne", 66], ["Lausanne", "Geneva", 36], ["Bern", "Brig", 64],
["Lausanne", "Brig", 90], ["Zurich", "St. Gallen", 64], ["Zurich", "Chur", 75],
["Lucerne", "Lugano", 112], ["Zurich", "Lugano", 115]].each do |from, to, minutes|
rail.add_edge(from, to, weight: minutes)
end
[rail.number_of_nodes, rail.number_of_edges]10 towns, 14 lines. add_edge creates the nodes too, if they do not exist yet. An edge has no direction here: Bern to Basel takes as long as the way back.
Where can you go straight from Bern? neighbours gives the neighbours with the data of their edge:
rail.neighbours("Bern")Now the real question: what is the fastest way from Geneva to St. Gallen? Trying everything would be tedious – even this small network has many ways. In 1956 the computer scientist Edsger Dijkstra found a clever way to do it: from the start, the town that can be reached soonest is always settled next, and its neighbours are worked out anew from there. dijkstra_path gives the way, dijkstra_path_length how long it takes:
journey = NetworkX.dijkstra_path(rail, "Geneva", "St. Gallen")
time = NetworkX.dijkstra_path_length(rail, "Geneva", "St. Gallen")
[journey, time]Via Lausanne, Bern and Zurich, 222 minutes. A map shows it better. Rubyvis from the last lesson draws one: every line a line with two points, every town a dot with its name. The lines of the fastest way turn orange:
install_gem "rubyvis"
require "rubyvis"
# where the towns roughly are: kilometres east, north
where = { "Geneva" => [500, 118], "Lausanne" => [538, 152], "Brig" => [642, 130],
"Bern" => [600, 200], "Basel" => [611, 267], "Lucerne" => [666, 211],
"Zurich" => [683, 248], "St. Gallen" => [746, 254], "Chur" => [759, 191],
"Lugano" => [717, 96] }
x = Rubyvis::Scale.linear(490, 770).range(10, 360)
y = Rubyvis::Scale.linear(90, 275).range(10, 240)
on_the_way = journey.each_cons(2).map(&:sort)
map = Rubyvis::Panel.new do
width 430
height 250
rail.edges.each do |a, b|
line do
data [a, b]
left { |town| x.scale(where[town][0]) }
bottom { |town| y.scale(where[town][1]) }
stroke_style(on_the_way.include?([a, b].sort) ? "#e8722a" : "#ccc")
line_width 4
end
end
dot do
data where.keys
left { |town| x.scale(where[town][0]) }
bottom { |town| y.scale(where[town][1]) }
fill_style "white"
stroke_style "#333"
label(anchor: "right").text { |town| town }
end
end
show_image map, alt: "The rail network, the fastest way from Geneva to St. Gallen in orange"On the way, Dijkstra works out the times to all towns, and singlesource_dijkstra_path_length returns them all – the travel times from Bern, the nearest town first:
NetworkX.singlesource_dijkstra_path_length(rail, "Bern")And if a line is closed? remove_edge takes it out of the network, and Dijkstra looks for another way. At the end of the cell, add_edge puts the line back, so that the other cells keep the whole network:
rail.remove_edge("Bern", "Lausanne") # the line is closed
detour = NetworkX.dijkstra_path(rail, "Geneva", "St. Gallen")
time = NetworkX.dijkstra_path_length(rail, "Geneva", "St. Gallen")
rail.add_edge("Bern", "Lausanne", weight: 66) # and open again
[detour, time]The detour goes via Brig and costs 88 minutes more. One more question that network planners ask: which lines are needed at the least to keep all the towns connected – with as few minutes of track as possible? The answer is called a minimum spanning tree:
backbone = NetworkX.minimum_spanning_tree(rail)
total = backbone.edges(data: true).sum { |_from, _to, data| data[:weight] }
[backbone.number_of_edges, total]9 lines for 10 towns – one fewer than towns, as in every tree: one line more would make a loop somewhere, one fewer would leave a town on its own.
gem install networkx – plain Ruby. networkx.rb knows much more: breadth-first and depth-first search, cycles, cliques, PageRank (how Google once weighed web pages) and flows through networks. Directed graphs, where an edge goes one way only, you build with NetworkX::DiGraph. The travel times here are rounded and leave out changing trains. networkx.rb comes under the MIT licence.
wood and let Dijkstra work it out: the way in path, how long it takes in minutes in minutes.install_gem "networkx"
require "networkx"
# Chunky's paths in the wood, in minutes:
# den - stream 4, den - clearing 7, stream - clearing 2,
# stream - henhouse 9, clearing - henhouse 5
wood = NetworkX::Graph.new
# path = ... (the fastest way from the den to the henhouse)
# minutes = ... (how long it takes)