Truncate TreeForm to show only the top
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]]
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)
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]
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.
The solutions seem a bit complicated. What about this one?
myTreeForm[expr_, dep_] := Map[Head, TreeForm[expr, dep], {dep + 1}];
a = Nest[1/(1 + #) (1 - #) &, w, 5];
myTreeForm[a, 1]
myTreeForm[a, 2]
myTreeForm[a, 3]