Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

For some expressions, TreeForm may grow very long. I'm only interested in the top levels of the expression. How can I get the tree form of only the first levels an expression?

For example: how to get the first levels of this expression in tree form?

Nest[1/(1 + #) (1 - #) &, w, 5]

TreeLevel of the above expression

share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

Can use something like this:

ClearAll[showTopTree];
showTopTree[expr_, level_] :=
  Module[{myHold}, 
     SetAttributes[myHold, HoldAll];
     Function[code,
       TreeForm[Unevaluated@Unevaluated@code],
       HoldAll] @@
    (Hold[#] &@
      DeleteCases[MapAll[myHold, expr], _, {2*level, Infinity}] //.
           myHold[x__] :> x)];

Pretty ugly, but seems to work:

expr = Nest[1/(1 + #) (1 - #) &, w, 5]
Manipulate[showTopTree[expr, n], {n, 1, Depth[expr], 1}]

GraphicsGrid[Partition[showTopTree[expr, #] & /@ Range[6], 3]]

enter image description here

share|improve this answer
add comment

You can use the second argument of TreeForm to display and expression to a certain depth, so for your example you could do TreeForm[Nest[1/(1 + #) (1 - #) &, w, 5], 1] (although the result isn't very pretty in this case)

Mathematica graphics

Edit

Instead of using TreeForm you could also construct a graph of the expression using ExpressionTreePlot in the GraphUtilities` package and use that to extract the desired subtree.

Needs["GraphUtilities`"];
exprTree[expr_] :=
 Module[{g, edges, labels},
  g = ExpressionTreePlot[expr, Top];
  edges = Rule @@@ Cases[g, Line[a_] :> a, Infinity][[1]];
  labels = Cases[g, Text[a_, b_] :> (b -> a[[1, 1]]), Infinity];
  {edges, labels}]

subTree[expr_, d_, pos_: Top] := Module[{edges, labels, sub},
  {edges, labels} = exprTree[expr];
  sub = NeighborhoodSubgraph[edges, 1, d];
  TreePlot[sub, pos, VertexRenderingFunction ->
    Function[{p, v}, 
     Text[Framed[Style[v /. labels, FontSize -> 10], 
       Background -> Lighter[Gray, .8]], p]]]]

Example:

subTree[Nest[1/(1 + #) (1 - #) &, w, 5], 4]

Mathematica graphics

Here, I've chosen the style of VertexRenderingFunction in the definition of subTree to mimic the style of TreeForm but you could choose you own style for displaying the vertex labels.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.