Guest User

Untitled

a guest
Dec 14th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. (* sow node -> label replacements *)
  2. sowLabel[x_?AtomQ] := (Sow[# -> x]; #) &[c++];
  3. sowLabel[x_] := x;
  4.  
  5. (* sow parent -> child replacements *)
  6. sowEdge[head_[arg__]] := (Sow[head -> #] & /@ {arg}; head);
  7. sowEdge[x_?AtomQ] := x;
  8.  
  9. (* the expression to be parsed into a tree *)
  10. expr = Hold[Log[Sin[1 + 2], ToExpression["1" <> "0"]]];
  11. FullForm@expr
  12.  
  13. Hold[Log[Sin[Plus[1, 2]], ToExpression[StringJoin["1", "0"]]]]
  14.  
  15. (* replace heads with node index & collect index -> label list *)
  16. c = 1;
  17. {new, labels} = Reap@ReleaseHold@Map[sowLabel, expr, {2, [Infinity]}, Heads -> True]
  18.  
  19. {
  20. 1[2[3[4, 5]], 6[7[8, 9]]],
  21. {{1 -> Log, 2 -> Sin, 3 -> Plus, 4 -> 1, 5 -> 2, 6 -> ToExpression, 7 -> StringJoin, 8 -> "1", 9 -> "0"}}
  22. }
  23.  
  24. (* create graph edges from substituted expression *)
  25. edges = Sort@Most@First@Last@Reap@Map[sowEdge, {new}, {0, [Infinity]}]
  26.  
  27. {1 -> 2, 1 -> 6, 2 -> 3, 3 -> 4, 3 -> 5, 6 -> 7, 7 -> 8, 7 -> 9}
  28.  
  29. (* plot results *)
  30. {
  31. TreeGraph[edges,
  32. VertexLabels -> First@labels, ImagePadding -> {{1, 35}, {0, 10}}
  33. ],
  34. LayeredGraphPlot[edges,
  35. VertexLabeling -> True,
  36. VertexRenderingFunction :> (Inset[
  37. Framed[InputForm[#2 /. First@labels], Background -> Hue[.15, .3, 1]], #1] &)
  38. ],
  39. TreeForm[expr, ImageSize -> 230]
  40. }
  41.  
  42. Hold[Log[Sin[Plus[1, 2]], ToExpression[StringJoin["1", "0"]]]]
  43.  
  44. reStyle = SetProperty[#, VertexLabels ->
  45. (PropertyValue[# , VertexLabels]/. HoldPattern[Rule[a_, b_]] :> Rule[a, Placed[b, Center]])]&;
  46.  
  47. reStyle @ GraphComputation`ExpressionGraph[Sin[Plus[a, b, Times[c,d]]],
  48. GraphStyle -> "VintageDiagram"]
  49.  
  50. reStyle @ GraphComputation`ExpressionGraph[Hold[Log[Sin[1 + 2], ToExpression["1"<>"0"]]],
  51. GraphStyle->"VintageDiagram"]
Add Comment
Please, Sign In to add comment