Find and Select Shortest Paths

A frequent need in graph exploration is to identify (and perhaps select) all the nodes on the shortest path between two nodes. This recipe shows how to do that.

This example uses a shortest path algorithm from the RBGL ('Boost') library. igraph provides an algorithm too, but it is awkard to use until some changes planned for its next release. [Paul Shannon, 3 May 2011]

Take these steps:
  1. make sure that RBGL (R Boost Graph Library) is loaded:
    library (RBGL)
  2. Select two nodes in Cytoscape
  3. To get the shortest path nodes between (and including) the selected nodes:
    sp.between (ugraph (cw@graph), getSelectedNodes (cw)[1], getSelectedNodes (cw)[2]) 
  4. To select the shortest path, all in one command:
     selectNodes (cw, sp.between (ugraph (cw@graph), getSelectedNodes (cw)[1], getSelectedNodes (cw)[2])[[1]]$path_detail)
Here's a function you might find convenient:

selectShortestPath = function (cw) {
  stopifnot (getSelectedNodeCount (cw) == 2)
  nodes = getSelectedNodes (cw)
  sp.path.nodes = sp.between (ugraph (cw@graph), nodes [1], nodes [2])[[1]]$path_detail
  stopifnot (!is.na (sp.path.nodes))
  selectNodes (cw, sp.path.nodes)
  invisible (sp.path.nodes)
  }