# Converting expressions to "edges" for use in TreePlot, Graph

This question is similar to this: Nested list to graph. How to "flatten" an arbitrary expression, eg

expr = a[b[c, d[e][f], g], h]


to a list of key-value pairs representing Graph edges of the expression tree:

These can be extracted by applying WReach's exception-based method --> Can TreeForm be displayed “sideways”?:

Block[{TreePlot},
t_TreePlot := Throw@Hold@t;
Catch@MakeBoxes@TreeForm[expr]
][[1, 1]]


Giving:

{{"a", "0", "a[b[c, d[e][f], g], h]"} -> {"b", "1",
"b[c, d[e][f], g]"}, {"b", "1", "b[c, d[e][f], g]"} -> {"c", "2",
"c"}, {"b", "1", "b[c, d[e][f], g]"} -> {"d[e]", "3",
"d[e][f]"}, {"d[e]", "3", "d[e][f]"} -> {"f", "4", "f"}, {"b", "1",
"b[c, d[e][f], g]"} -> {"g", "5", "g"}, {"a", "0",
"a[b[c, d[e][f], g], h]"} -> {"h", "6", "h"}}


(Why are they cast to String?) Note non-atomic sub-expressions replaced with their Head. Based on the above, and the rule: ({h_, _, _} -> {a_, _, _}) :> ToExpression@h -> ToExpression@ a gives:

{a -> b, b -> c, b -> d[e], d[e] -> f, b -> g, a -> h}


TreeForm is a wrapper around TreePlot. TreePlot[%, VertexLabeling -> True] gives:

Since the layout is different, TreePlot must be making use of the other components of the output of the Block above.

EDIT:

How do TreeForm and SparseArayExpressionToTree (see below) extract these pairs of vertices? "Proof of work" is to extract the position (in the expression) of each vertex along with the edges.

Previously, I asked how to extract these "edges" based on a more restricted example Alternatives ordering affects pattern matching in Cases?. Also tried ReplaceList but don't know how to map it consistently across all levels.

• Related: (11458) Commented Jun 3, 2016 at 3:50

Although kguler posted an answer using a nice internal function that does this (almost) directly I find this kind of expression manipulation interesting in itself so I wanted to see what could be done without it.

expr = a[b[c, d[e][f], g], h];

edges =
Reap[
Cases[expr, h_[___, c_[___] | c_?AtomQ, ___] /; Sow[h -> c], {0, -1}]
][[2, 1]];

TreePlot[edges, VertexLabeling -> True]


Or for the different layout:

TreePlot[edges, Automatic, Head @ expr, VertexLabeling -> True]


tree[expr_] :=
edges = Reap[
Sow[Annotation[h, x] ->
Annotation[c, If[{z} === {}, {a}, {z}]]], {0, -1}]][[2, 1]];
edges = edges /. head -> Annotation;
TreePlot[edges, Automatic, edges[[-1, 1]], VertexLabeling -> True]
]

a[b[c, d[e][f], g, b, d[e][b]], h] // tree


This very likely has bugs that will need to be addressed as I did it in a hurry and tired, but I think it at least gives us a place to start.

• Thanks, nice use of Sow/Reap, and inner Alternatives. One issue, how to specify Head[expr] as RootVertex? Maybe using a function of Position[expr, h] (in Sow)? Commented Jun 27, 2014 at 21:09
• @alancalvitti I'm glad this helps. Regarding "RootVertex" does this do what you want? TreePlot[%, Automatic, Head@expr, VertexLabeling -> True] Commented Jun 28, 2014 at 1:11
• this answer, as the others here, relies on the nodes being all different. it's not easy to see how to extend it to the case where e.g. b appears twice at different places. one would probably need some temporary node numbering? Commented Sep 12, 2017 at 18:14
• @user3240588 Good question! I'll have to think about that. Commented Sep 12, 2017 at 20:47
• @user3240588 Please see my update, and look for cases where it fails so I can try to fix those. Commented Sep 12, 2017 at 21:25

An alternative method to WReach's method is to use SparseArrayExpressionToTree which produces the same output without string wrappers:

expr = a[b[c, d[e][f], g], h];
ett = SparseArrayExpressionToTree[expr]
(* {{a,0,a[b[c,d[e][f],g],h]}->{b,1,b[c,d[e][f],g]},
{b,1,b[c,d[e][f],g]}->{c,2,c},
{b,1,b[c,d[e][f],g]}->{d[e],3,d[e][f]},
{d[e],3,d[e][f]}->{f,4,f},
{b,1,b[c,d[e][f],g]}->{g,5,g},
{a,0,a[b[c,d[e][f],g],h]}->{h,6,h}} *)

edges = ett[[All,All,1]] (* thanks: @Mr.Wizard *)
(* or edges = ett /. Rule[a_, b_] :> Rule[First[a], First[b]];*)
(* {a->b,b->c,b->d[e],d[e]->f,b->g,a->h} *)

Graph[edges, VertexLabels -> Placed["Name", {Center, Center}],
VertexSize -> .3, VertexLabelStyle -> Directive[Red, Italic, 20],
ImagePadding -> 20, ImageSize -> 400,
GraphLayout -> {"LayeredEmbedding", "RootVertex" -> edges[[1,1]]}]


Update: You can also use GraphComputationExpressionGraph:

eg = GraphComputationExpressionGraph[expr, VertexSize -> Large,
VertexLabelStyle -> Directive[Red, Italic, 20]];
SetProperty[eg,  VertexLabels -> {v_ :>
Placed[PropertyValue[{eg, v}, VertexLabels], Center]}]


• More directly: SparseArrayExpressionToTree[expr][[All, All, 1]]. Also, thanks for showing me ExpressionToTree! (Again?) Commented Jun 27, 2014 at 1:24
• @kguler, +1 - btw ETT --> ReleaseHold. But I'm asking how TreeForm (and ETT) convert the expr. I edited my Q to reflect this. Commented Jun 27, 2014 at 18:40
• @alancalvitti Is my answer of no interest to you? Are you only interested in the details of the internal implementation and not an equivalent method in top-level code? Commented Jun 27, 2014 at 19:37
• Yes that works, thank you, I had to test on some expressions of interest. Commented Jun 27, 2014 at 21:06
• Since 12.1 ExpressionGraph is now a documented symbol in the System context. reference.wolfram.com/language/ref/ExpressionGraph.html Commented Feb 1 at 18:41

IGraph/M now includes IGExpressionTree:

<<IGraphM
IGExpressionTree[expr]


GraphQ[%]
(* True *)


The function Position provides all the information we need to construct the vertex list, edge list and vertex labels to build our own expression graph (in case ExpressionTree or ExpressionGraph is not available in your version):

ClearAll[homeMadeExpressionTree]

{"DownToLevel" -> Automatic, "VertexLabeling" -> Automatic,
"RootPosition" -> Top},
Options[Graph]];

homeMadeExpressionTree[$$expr_, opts : OptionsPattern[]] := Module[ {el, vlbls, vl = Position[expr, _, {0, OptionValue["DownToLevel"] /. Automatic -> Depth@expr}, Heads -> False]},$$vlbls = Thread[$$vl -> Extract[$$expr, $$vl, Tooltip[If[AtomQ @ #, #, (OptionValue["VertexLabeling"] /. {Automatic | Head -> Head, _ -> Identity}) @ #], #, TooltipStyle -> 14] &]];$$el = Thread[Map[Most] @ # -> #] & @ Most[$$vl]; Graph[$$vl, $$el, FilterRules[{opts}, Options[Graph]], ImageSize -> Medium, GraphLayout -> {"LayeredEmbedding", "RootVertex" -> {}, "Orientation" -> OptionValue["RootPosition"]}, VertexLabels ->$$vlbls]];


Examples:

expr1 = a[b[c, d[e][f], g], h];



dsk = Graphics[{RGBColor[1, 0, 0], Disk[{0, 0}]}, ImageSize -> 80];

TreeForm[dsk, ImageSize -> Medium]}, Spacer[20]]


expr2 = a[b[c, d[e][f], g, b, d[e][b]], h];

expr3 = HornerForm[1 + x + x^2 + x^3, x];

homeMadeExpressionTree[#, "DownToLevel" -> 2, "VertexLabeling" -> Blah]} & /@
{expr1, expr2, expr3},
Dividers -> All]


Is this what you are seeking?

expr = a[b[c, d[e][f], g], h]
boxes = ToBoxes@TreeForm[expr]
positions = Cases[boxes, LineBox[{x__}] -> x, Infinity]
nodes =
Cases[
boxes,
StyleBox[x_, __] :> ToExpression@x, Infinity] /.
{t_Times :> First@t, Verbatim[HoldForm][x_] -> x}
Rule @@@ Extract[nodes, List /@ positions]


{a -> b, a -> h, b -> c, b -> d, b -> g, d -> f}

• No, for example that doesn't match d[e]. But also, How to extract it directly without using TreeForm? Commented Jun 26, 2014 at 23:15

In versions 13.2+, we can use ExpressionTree as follows:

expr = a[b[c, d[e][f], g], h];



VertexList @ ExpressionTree[expr, "Heads"]

{{c, {1, 1}},
{f, {1, 2, 1}},
{d[e], {1, 2}},
{g, {1, 3}},
{b, {1}},
{h, {2}},
{a, {}}}

EdgeList @ ExpressionTree[expr, "Heads"]

 {{d[e], {1, 2}} \[DirectedEdge] {f, {1, 2, 1}},
{b, {1}} \[DirectedEdge] {c, {1, 1}},
{b, {1}} \[DirectedEdge] {d[e], {1, 2}},
{b, {1}} \[DirectedEdge] {g, {1, 3}},
{a, {}} \[DirectedEdge] {b, {1}},
{a, {}} \[DirectedEdge] {h, {2}}}

%[[All, All, 1]]


WolframLanguageData["ExpressionTree", #] & /@
{"VersionIntroduced", "DateIntroduced"}
`