Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All paths in directed tree graph from root to leaves in igraph R

Tags:

r

igraph

Given is a tree:

library(igraph)

# setup graph
g= graph.formula(A -+ B,
                 A -+ C,
                 B -+ C,
                 B -+ D,
                 B -+ E
)
plot(g, layout = layout.reingold.tilford(g, root="A"))

enter image description here

Vertex "A" is the root of the tree, while vertices "C", "D", "E" are considered as terminal leaves.

Problem:

The task is to find all paths between root and leaves. I fail with following code, as it only provides the shortest paths:

# find root and leaves
leaves= which(degree(g, v = V(g), mode = "out")==0, useNames = T)
root= which(degree(g, v = V(g), mode = "in")==0, useNames = T)

# find all paths
paths= lapply(root, function(x) get.all.shortest.paths(g, from = x, to = leaves, mode = "out")$res)
named_paths= lapply(unlist(paths, recursive=FALSE), function(x) V(g)[x])
named_paths

Output:

$A1
Vertex sequence:
[1] "A" "C"

$A2
Vertex sequence:
[1] "A" "B" "D"

$A3
Vertex sequence:
[1] "A" "B" "E"

Question:

How can I find all paths including the vertex sequence: "A" "B" "C"?

My understanding is, that the missing sequence "A" "B" "C" is not provided by get.all.shortest.paths() as the path from "A" to "C" via the vertex sequence: "A" "C" (which is found in list element $A1) is shorter. So igraph works properly. Nevertheless I am looking for a code solution to get all paths from the root to all leaves in form of a R list.

Comment:

I am aware that for large trees the algorithm covering all combinations might become expensive, but my real application is relatively small.

like image 779
user2030503 Avatar asked Jul 14 '15 12:07

user2030503


1 Answers

Based on Gabor's comment:

all_simple_paths(g, from = root, to = leaves)

yields:

[[1]]
+ 3/5 vertices, named:
[1] A B C

[[2]]
+ 3/5 vertices, named:
[1] A B D

[[3]]
+ 3/5 vertices, named:
[1] A B E

[[4]]
+ 2/5 vertices, named:
[1] A C
like image 76
user2030503 Avatar answered Oct 19 '22 22:10

user2030503