Adding edges to a TreeForm of an expressionTruncate TreeForm to show only the topTransform an expression into a graph that can be plotted with TreeGraph (not TreeForm)Processing and storing a graph with a large number of vertices s.t. k-hop neighborhoods are efficiently retrievableEdgeRenderingFunction questionUsing different colors in TreeForm?VertexLabels, EdgeLabels and the direction of the arrows on a directed graphFast way to get edge-list of graph in terms of vertex indices (not vertex names)How to work with phylogenetic trees?Problem with TreeFormDemonstrate that graphs with different colors of vertices/edges are not isomorphic

Why does the Mishnah use the terms poor person and homeowner when discussing carrying on Shabbat?

How to decline a wedding invitation from a friend I haven't seen in years?

Extreme flexible working hours: how to get to know people and activities?

sed + add word before string only if not exists

How do you say "homebrewer" in Spanish?

Why 1,2 printed by a command in $() is not interpolated?

How can I search for all contacts without email?

Fermat's statement about the ancients: How serious was he?

Is an entry level DSLR going to shoot nice portrait pictures?

US doctor working in Tripoli wants me to open online account

Non-aqueous eyes?

Who enforces MPAA rating adherence?

Are there any important biographies of nobodies?

How to hide an urban landmark?

Heap allocation on microcontroller

Why can I traceroute to this IP address, but not ping?

Who won a Game of Bar Dice?

New pedal fell off maybe 50 miles after installation. Should I replace the entire crank, just the arm, or repair the thread?

Active low-pass filters --- good to what frequencies?

Electricity free spaceship

How come the nude protesters were not arrested?

How did old MS-DOS games utilize various graphic cards?

Should I ask for an extra raise?

I have a problematic assistant manager, but I can't fire him



Adding edges to a TreeForm of an expression


Truncate TreeForm to show only the topTransform an expression into a graph that can be plotted with TreeGraph (not TreeForm)Processing and storing a graph with a large number of vertices s.t. k-hop neighborhoods are efficiently retrievableEdgeRenderingFunction questionUsing different colors in TreeForm?VertexLabels, EdgeLabels and the direction of the arrows on a directed graphFast way to get edge-list of graph in terms of vertex indices (not vertex names)How to work with phylogenetic trees?Problem with TreeFormDemonstrate that graphs with different colors of vertices/edges are not isomorphic













4












$begingroup$


Say I have an expression 1,2,3,4. It's TreeForm looks as follows:



1,2,3,4 //TreeForm



enter image description here



Now, on each level of that tree I would like to draw an edge where there isn't one, i.e. between 1 and List (first level), between List and 4 (second level) and between 2 and 3 (third level). Is it possible to do it in an efficient way? Can I somehow control the direction of all of these edges (including already existing ones)? I tried to use IGExpressionTree from the IGraph package together with EdgeAdd but it didn't work. Any suggestions?










share|improve this question











$endgroup$







  • 1




    $begingroup$
    maybe EdgeAdd[GraphComputation`ExpressionGraph[1, 2, 3, 4 ], 2->3,4->7,5->6]?
    $endgroup$
    – kglr
    May 23 at 11:50











  • $begingroup$
    @kglr Thanks! Does that work, I've tried EdgeAdd[IGExpressionTree[1, 2, 3, 4, VertexLabels->"Subexpression"],4[UndirectedEdge]6], but that didn't work, I wonder why..
    $endgroup$
    – amator2357
    May 23 at 11:55






  • 1




    $begingroup$
    What if you have more than two nodes at the same level in the tree?
    $endgroup$
    – Szabolcs
    May 23 at 12:02






  • 1




    $begingroup$
    @amator2357 IGExpressionTree does not use the same vertex names as GraphComputation`ExpressionGraph
    $endgroup$
    – Szabolcs
    May 23 at 12:07











  • $begingroup$
    @Szabolcs it'll never happen for my case
    $endgroup$
    – amator2357
    May 23 at 12:07















4












$begingroup$


Say I have an expression 1,2,3,4. It's TreeForm looks as follows:



1,2,3,4 //TreeForm



enter image description here



Now, on each level of that tree I would like to draw an edge where there isn't one, i.e. between 1 and List (first level), between List and 4 (second level) and between 2 and 3 (third level). Is it possible to do it in an efficient way? Can I somehow control the direction of all of these edges (including already existing ones)? I tried to use IGExpressionTree from the IGraph package together with EdgeAdd but it didn't work. Any suggestions?










share|improve this question











$endgroup$







  • 1




    $begingroup$
    maybe EdgeAdd[GraphComputation`ExpressionGraph[1, 2, 3, 4 ], 2->3,4->7,5->6]?
    $endgroup$
    – kglr
    May 23 at 11:50











  • $begingroup$
    @kglr Thanks! Does that work, I've tried EdgeAdd[IGExpressionTree[1, 2, 3, 4, VertexLabels->"Subexpression"],4[UndirectedEdge]6], but that didn't work, I wonder why..
    $endgroup$
    – amator2357
    May 23 at 11:55






  • 1




    $begingroup$
    What if you have more than two nodes at the same level in the tree?
    $endgroup$
    – Szabolcs
    May 23 at 12:02






  • 1




    $begingroup$
    @amator2357 IGExpressionTree does not use the same vertex names as GraphComputation`ExpressionGraph
    $endgroup$
    – Szabolcs
    May 23 at 12:07











  • $begingroup$
    @Szabolcs it'll never happen for my case
    $endgroup$
    – amator2357
    May 23 at 12:07













4












4








4





$begingroup$


Say I have an expression 1,2,3,4. It's TreeForm looks as follows:



1,2,3,4 //TreeForm



enter image description here



Now, on each level of that tree I would like to draw an edge where there isn't one, i.e. between 1 and List (first level), between List and 4 (second level) and between 2 and 3 (third level). Is it possible to do it in an efficient way? Can I somehow control the direction of all of these edges (including already existing ones)? I tried to use IGExpressionTree from the IGraph package together with EdgeAdd but it didn't work. Any suggestions?










share|improve this question











$endgroup$




Say I have an expression 1,2,3,4. It's TreeForm looks as follows:



1,2,3,4 //TreeForm



enter image description here



Now, on each level of that tree I would like to draw an edge where there isn't one, i.e. between 1 and List (first level), between List and 4 (second level) and between 2 and 3 (third level). Is it possible to do it in an efficient way? Can I somehow control the direction of all of these edges (including already existing ones)? I tried to use IGExpressionTree from the IGraph package together with EdgeAdd but it didn't work. Any suggestions?







graphs-and-networks trees igraphm






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 23 at 13:30









m_goldberg

90.5k873203




90.5k873203










asked May 23 at 11:12









amator2357amator2357

74310




74310







  • 1




    $begingroup$
    maybe EdgeAdd[GraphComputation`ExpressionGraph[1, 2, 3, 4 ], 2->3,4->7,5->6]?
    $endgroup$
    – kglr
    May 23 at 11:50











  • $begingroup$
    @kglr Thanks! Does that work, I've tried EdgeAdd[IGExpressionTree[1, 2, 3, 4, VertexLabels->"Subexpression"],4[UndirectedEdge]6], but that didn't work, I wonder why..
    $endgroup$
    – amator2357
    May 23 at 11:55






  • 1




    $begingroup$
    What if you have more than two nodes at the same level in the tree?
    $endgroup$
    – Szabolcs
    May 23 at 12:02






  • 1




    $begingroup$
    @amator2357 IGExpressionTree does not use the same vertex names as GraphComputation`ExpressionGraph
    $endgroup$
    – Szabolcs
    May 23 at 12:07











  • $begingroup$
    @Szabolcs it'll never happen for my case
    $endgroup$
    – amator2357
    May 23 at 12:07












  • 1




    $begingroup$
    maybe EdgeAdd[GraphComputation`ExpressionGraph[1, 2, 3, 4 ], 2->3,4->7,5->6]?
    $endgroup$
    – kglr
    May 23 at 11:50











  • $begingroup$
    @kglr Thanks! Does that work, I've tried EdgeAdd[IGExpressionTree[1, 2, 3, 4, VertexLabels->"Subexpression"],4[UndirectedEdge]6], but that didn't work, I wonder why..
    $endgroup$
    – amator2357
    May 23 at 11:55






  • 1




    $begingroup$
    What if you have more than two nodes at the same level in the tree?
    $endgroup$
    – Szabolcs
    May 23 at 12:02






  • 1




    $begingroup$
    @amator2357 IGExpressionTree does not use the same vertex names as GraphComputation`ExpressionGraph
    $endgroup$
    – Szabolcs
    May 23 at 12:07











  • $begingroup$
    @Szabolcs it'll never happen for my case
    $endgroup$
    – amator2357
    May 23 at 12:07







1




1




$begingroup$
maybe EdgeAdd[GraphComputation`ExpressionGraph[1, 2, 3, 4 ], 2->3,4->7,5->6]?
$endgroup$
– kglr
May 23 at 11:50





$begingroup$
maybe EdgeAdd[GraphComputation`ExpressionGraph[1, 2, 3, 4 ], 2->3,4->7,5->6]?
$endgroup$
– kglr
May 23 at 11:50













$begingroup$
@kglr Thanks! Does that work, I've tried EdgeAdd[IGExpressionTree[1, 2, 3, 4, VertexLabels->"Subexpression"],4[UndirectedEdge]6], but that didn't work, I wonder why..
$endgroup$
– amator2357
May 23 at 11:55




$begingroup$
@kglr Thanks! Does that work, I've tried EdgeAdd[IGExpressionTree[1, 2, 3, 4, VertexLabels->"Subexpression"],4[UndirectedEdge]6], but that didn't work, I wonder why..
$endgroup$
– amator2357
May 23 at 11:55




1




1




$begingroup$
What if you have more than two nodes at the same level in the tree?
$endgroup$
– Szabolcs
May 23 at 12:02




$begingroup$
What if you have more than two nodes at the same level in the tree?
$endgroup$
– Szabolcs
May 23 at 12:02




1




1




$begingroup$
@amator2357 IGExpressionTree does not use the same vertex names as GraphComputation`ExpressionGraph
$endgroup$
– Szabolcs
May 23 at 12:07





$begingroup$
@amator2357 IGExpressionTree does not use the same vertex names as GraphComputation`ExpressionGraph
$endgroup$
– Szabolcs
May 23 at 12:07













$begingroup$
@Szabolcs it'll never happen for my case
$endgroup$
– amator2357
May 23 at 12:07




$begingroup$
@Szabolcs it'll never happen for my case
$endgroup$
– amator2357
May 23 at 12:07










2 Answers
2






active

oldest

votes


















4












$begingroup$

g0 = GraphComputation`ExpressionGraph[1, 2, 3, 4 , ImageSize -> 200];
newedges = UndirectedEdge @@@ GatherBy[Rest@VertexList@g0, GraphDistance[g0, 1, #] &]



2 [UndirectedEdge] 3, 4 [UndirectedEdge] 7, 5 [UndirectedEdge] 6




g1 = EdgeAdd[g0, newedges];
Row[g0, g1, Spacer[10]]


enter image description here



Alternatively, you can use newedges to post-process the TreeForm of the input expression to add the new lines:



tf1 = TreeForm[1, 2, 3, 4, DirectedEdges -> True, ImageSize -> Medium]; 
tf2 = RawBoxes[ToBoxes[tf1] /. l : (_ArrowBox | _LineBox) :>
l, Dashing @ Small, LineBox @ # ] &[List @@@ newedges];
Row @ tf1, tf2


enter image description here



If there are more than two nodes at the same level in the tree:



g0 = GraphComputation`ExpressionGraph[1, 2, 3, 4, 5 , ImageSize -> 200];
newedges = Join @@ Map[UndirectedEdge @@@ # &,
Subsets[#, 2] & /@ GatherBy[Rest@VertexList@g0, GraphDistance[g0, 1, #] &]]



2 [UndirectedEdge] 3, 4 [UndirectedEdge] 7,
4 [UndirectedEdge] 8, 7 [UndirectedEdge] 8, 5 [UndirectedEdge] 6




 g1 = SetProperty[EdgeAdd[g0, newedges],
EdgeShapeFunction -> Alternatives @@ newedges :> "CurvedArc"]
Row[g0, g1, Spacer[10]]


enter image description here






share|improve this answer











$endgroup$




















    5












    $begingroup$

    With IGraph/M,



    g = IGExpressionTree[1, 2, 3, 4]


    enter image description here



    Notice that the vertices created by this function are lists (encoding subexpression positions), and their length is the same if they are on the same tree level.



    IGExpressionTree[1, 2, 3, 4, VertexLabels -> "Name"]


    enter image description here



    Thus we can easily create the additional edges:



    pathEdges[list_] := DirectedEdge @@@ Partition[list, 2, 1]

    newEdges = Flatten[pathEdges /@ GatherBy[VertexList[g], Length]]
    (* 1 [DirectedEdge] 2, 2, 1, 1 [DirectedEdge] 2, 1, 2, 2, 1 [DirectedEdge] 2, 2 *)

    EdgeAdd[g, newEdges]


    enter image description here



    If you never have more than two nodes at a level, then simply use



    EdgeAdd[
    g,
    DirectedEdge @@@ GatherBy[Most@VertexList[g], Length]
    ]


    Both of these rely on the order in which vertices are returned by IGExpressionTree (which is sorted) as well as on GatherBy not changing this order.






    share|improve this answer











    $endgroup$













      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "387"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f198930%2fadding-edges-to-a-treeform-of-an-expression%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      4












      $begingroup$

      g0 = GraphComputation`ExpressionGraph[1, 2, 3, 4 , ImageSize -> 200];
      newedges = UndirectedEdge @@@ GatherBy[Rest@VertexList@g0, GraphDistance[g0, 1, #] &]



      2 [UndirectedEdge] 3, 4 [UndirectedEdge] 7, 5 [UndirectedEdge] 6




      g1 = EdgeAdd[g0, newedges];
      Row[g0, g1, Spacer[10]]


      enter image description here



      Alternatively, you can use newedges to post-process the TreeForm of the input expression to add the new lines:



      tf1 = TreeForm[1, 2, 3, 4, DirectedEdges -> True, ImageSize -> Medium]; 
      tf2 = RawBoxes[ToBoxes[tf1] /. l : (_ArrowBox | _LineBox) :>
      l, Dashing @ Small, LineBox @ # ] &[List @@@ newedges];
      Row @ tf1, tf2


      enter image description here



      If there are more than two nodes at the same level in the tree:



      g0 = GraphComputation`ExpressionGraph[1, 2, 3, 4, 5 , ImageSize -> 200];
      newedges = Join @@ Map[UndirectedEdge @@@ # &,
      Subsets[#, 2] & /@ GatherBy[Rest@VertexList@g0, GraphDistance[g0, 1, #] &]]



      2 [UndirectedEdge] 3, 4 [UndirectedEdge] 7,
      4 [UndirectedEdge] 8, 7 [UndirectedEdge] 8, 5 [UndirectedEdge] 6




       g1 = SetProperty[EdgeAdd[g0, newedges],
      EdgeShapeFunction -> Alternatives @@ newedges :> "CurvedArc"]
      Row[g0, g1, Spacer[10]]


      enter image description here






      share|improve this answer











      $endgroup$

















        4












        $begingroup$

        g0 = GraphComputation`ExpressionGraph[1, 2, 3, 4 , ImageSize -> 200];
        newedges = UndirectedEdge @@@ GatherBy[Rest@VertexList@g0, GraphDistance[g0, 1, #] &]



        2 [UndirectedEdge] 3, 4 [UndirectedEdge] 7, 5 [UndirectedEdge] 6




        g1 = EdgeAdd[g0, newedges];
        Row[g0, g1, Spacer[10]]


        enter image description here



        Alternatively, you can use newedges to post-process the TreeForm of the input expression to add the new lines:



        tf1 = TreeForm[1, 2, 3, 4, DirectedEdges -> True, ImageSize -> Medium]; 
        tf2 = RawBoxes[ToBoxes[tf1] /. l : (_ArrowBox | _LineBox) :>
        l, Dashing @ Small, LineBox @ # ] &[List @@@ newedges];
        Row @ tf1, tf2


        enter image description here



        If there are more than two nodes at the same level in the tree:



        g0 = GraphComputation`ExpressionGraph[1, 2, 3, 4, 5 , ImageSize -> 200];
        newedges = Join @@ Map[UndirectedEdge @@@ # &,
        Subsets[#, 2] & /@ GatherBy[Rest@VertexList@g0, GraphDistance[g0, 1, #] &]]



        2 [UndirectedEdge] 3, 4 [UndirectedEdge] 7,
        4 [UndirectedEdge] 8, 7 [UndirectedEdge] 8, 5 [UndirectedEdge] 6




         g1 = SetProperty[EdgeAdd[g0, newedges],
        EdgeShapeFunction -> Alternatives @@ newedges :> "CurvedArc"]
        Row[g0, g1, Spacer[10]]


        enter image description here






        share|improve this answer











        $endgroup$















          4












          4








          4





          $begingroup$

          g0 = GraphComputation`ExpressionGraph[1, 2, 3, 4 , ImageSize -> 200];
          newedges = UndirectedEdge @@@ GatherBy[Rest@VertexList@g0, GraphDistance[g0, 1, #] &]



          2 [UndirectedEdge] 3, 4 [UndirectedEdge] 7, 5 [UndirectedEdge] 6




          g1 = EdgeAdd[g0, newedges];
          Row[g0, g1, Spacer[10]]


          enter image description here



          Alternatively, you can use newedges to post-process the TreeForm of the input expression to add the new lines:



          tf1 = TreeForm[1, 2, 3, 4, DirectedEdges -> True, ImageSize -> Medium]; 
          tf2 = RawBoxes[ToBoxes[tf1] /. l : (_ArrowBox | _LineBox) :>
          l, Dashing @ Small, LineBox @ # ] &[List @@@ newedges];
          Row @ tf1, tf2


          enter image description here



          If there are more than two nodes at the same level in the tree:



          g0 = GraphComputation`ExpressionGraph[1, 2, 3, 4, 5 , ImageSize -> 200];
          newedges = Join @@ Map[UndirectedEdge @@@ # &,
          Subsets[#, 2] & /@ GatherBy[Rest@VertexList@g0, GraphDistance[g0, 1, #] &]]



          2 [UndirectedEdge] 3, 4 [UndirectedEdge] 7,
          4 [UndirectedEdge] 8, 7 [UndirectedEdge] 8, 5 [UndirectedEdge] 6




           g1 = SetProperty[EdgeAdd[g0, newedges],
          EdgeShapeFunction -> Alternatives @@ newedges :> "CurvedArc"]
          Row[g0, g1, Spacer[10]]


          enter image description here






          share|improve this answer











          $endgroup$



          g0 = GraphComputation`ExpressionGraph[1, 2, 3, 4 , ImageSize -> 200];
          newedges = UndirectedEdge @@@ GatherBy[Rest@VertexList@g0, GraphDistance[g0, 1, #] &]



          2 [UndirectedEdge] 3, 4 [UndirectedEdge] 7, 5 [UndirectedEdge] 6




          g1 = EdgeAdd[g0, newedges];
          Row[g0, g1, Spacer[10]]


          enter image description here



          Alternatively, you can use newedges to post-process the TreeForm of the input expression to add the new lines:



          tf1 = TreeForm[1, 2, 3, 4, DirectedEdges -> True, ImageSize -> Medium]; 
          tf2 = RawBoxes[ToBoxes[tf1] /. l : (_ArrowBox | _LineBox) :>
          l, Dashing @ Small, LineBox @ # ] &[List @@@ newedges];
          Row @ tf1, tf2


          enter image description here



          If there are more than two nodes at the same level in the tree:



          g0 = GraphComputation`ExpressionGraph[1, 2, 3, 4, 5 , ImageSize -> 200];
          newedges = Join @@ Map[UndirectedEdge @@@ # &,
          Subsets[#, 2] & /@ GatherBy[Rest@VertexList@g0, GraphDistance[g0, 1, #] &]]



          2 [UndirectedEdge] 3, 4 [UndirectedEdge] 7,
          4 [UndirectedEdge] 8, 7 [UndirectedEdge] 8, 5 [UndirectedEdge] 6




           g1 = SetProperty[EdgeAdd[g0, newedges],
          EdgeShapeFunction -> Alternatives @@ newedges :> "CurvedArc"]
          Row[g0, g1, Spacer[10]]


          enter image description here







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited May 24 at 5:32

























          answered May 23 at 12:02









          kglrkglr

          196k10220442




          196k10220442





















              5












              $begingroup$

              With IGraph/M,



              g = IGExpressionTree[1, 2, 3, 4]


              enter image description here



              Notice that the vertices created by this function are lists (encoding subexpression positions), and their length is the same if they are on the same tree level.



              IGExpressionTree[1, 2, 3, 4, VertexLabels -> "Name"]


              enter image description here



              Thus we can easily create the additional edges:



              pathEdges[list_] := DirectedEdge @@@ Partition[list, 2, 1]

              newEdges = Flatten[pathEdges /@ GatherBy[VertexList[g], Length]]
              (* 1 [DirectedEdge] 2, 2, 1, 1 [DirectedEdge] 2, 1, 2, 2, 1 [DirectedEdge] 2, 2 *)

              EdgeAdd[g, newEdges]


              enter image description here



              If you never have more than two nodes at a level, then simply use



              EdgeAdd[
              g,
              DirectedEdge @@@ GatherBy[Most@VertexList[g], Length]
              ]


              Both of these rely on the order in which vertices are returned by IGExpressionTree (which is sorted) as well as on GatherBy not changing this order.






              share|improve this answer











              $endgroup$

















                5












                $begingroup$

                With IGraph/M,



                g = IGExpressionTree[1, 2, 3, 4]


                enter image description here



                Notice that the vertices created by this function are lists (encoding subexpression positions), and their length is the same if they are on the same tree level.



                IGExpressionTree[1, 2, 3, 4, VertexLabels -> "Name"]


                enter image description here



                Thus we can easily create the additional edges:



                pathEdges[list_] := DirectedEdge @@@ Partition[list, 2, 1]

                newEdges = Flatten[pathEdges /@ GatherBy[VertexList[g], Length]]
                (* 1 [DirectedEdge] 2, 2, 1, 1 [DirectedEdge] 2, 1, 2, 2, 1 [DirectedEdge] 2, 2 *)

                EdgeAdd[g, newEdges]


                enter image description here



                If you never have more than two nodes at a level, then simply use



                EdgeAdd[
                g,
                DirectedEdge @@@ GatherBy[Most@VertexList[g], Length]
                ]


                Both of these rely on the order in which vertices are returned by IGExpressionTree (which is sorted) as well as on GatherBy not changing this order.






                share|improve this answer











                $endgroup$















                  5












                  5








                  5





                  $begingroup$

                  With IGraph/M,



                  g = IGExpressionTree[1, 2, 3, 4]


                  enter image description here



                  Notice that the vertices created by this function are lists (encoding subexpression positions), and their length is the same if they are on the same tree level.



                  IGExpressionTree[1, 2, 3, 4, VertexLabels -> "Name"]


                  enter image description here



                  Thus we can easily create the additional edges:



                  pathEdges[list_] := DirectedEdge @@@ Partition[list, 2, 1]

                  newEdges = Flatten[pathEdges /@ GatherBy[VertexList[g], Length]]
                  (* 1 [DirectedEdge] 2, 2, 1, 1 [DirectedEdge] 2, 1, 2, 2, 1 [DirectedEdge] 2, 2 *)

                  EdgeAdd[g, newEdges]


                  enter image description here



                  If you never have more than two nodes at a level, then simply use



                  EdgeAdd[
                  g,
                  DirectedEdge @@@ GatherBy[Most@VertexList[g], Length]
                  ]


                  Both of these rely on the order in which vertices are returned by IGExpressionTree (which is sorted) as well as on GatherBy not changing this order.






                  share|improve this answer











                  $endgroup$



                  With IGraph/M,



                  g = IGExpressionTree[1, 2, 3, 4]


                  enter image description here



                  Notice that the vertices created by this function are lists (encoding subexpression positions), and their length is the same if they are on the same tree level.



                  IGExpressionTree[1, 2, 3, 4, VertexLabels -> "Name"]


                  enter image description here



                  Thus we can easily create the additional edges:



                  pathEdges[list_] := DirectedEdge @@@ Partition[list, 2, 1]

                  newEdges = Flatten[pathEdges /@ GatherBy[VertexList[g], Length]]
                  (* 1 [DirectedEdge] 2, 2, 1, 1 [DirectedEdge] 2, 1, 2, 2, 1 [DirectedEdge] 2, 2 *)

                  EdgeAdd[g, newEdges]


                  enter image description here



                  If you never have more than two nodes at a level, then simply use



                  EdgeAdd[
                  g,
                  DirectedEdge @@@ GatherBy[Most@VertexList[g], Length]
                  ]


                  Both of these rely on the order in which vertices are returned by IGExpressionTree (which is sorted) as well as on GatherBy not changing this order.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited May 23 at 13:16

























                  answered May 23 at 12:06









                  SzabolcsSzabolcs

                  168k17460974




                  168k17460974



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Mathematica Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      Use MathJax to format equations. MathJax reference.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f198930%2fadding-edges-to-a-treeform-of-an-expression%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

                      Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

                      Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020