Message Boards Message Boards

3 Replies
2 Total Likes
View groups...
Share this post:

How to best graph a tree structure

Posted 10 years ago

Hello everyone!

I've a nested function I'm trying to examine, which may or may not branch at each point. It generates data looking like this: $$\left\{1, \{2\}, \{\{3,4\}\}, \{\{\{5,6\},\{7\}\}\}\right\}$$ So above $2$ has the image $\{3,4\}$ and $3$ in turn splits to $\{5,6\}$. Each element having higher depth than the last.

I want to graph these progressions, but I'm struggling to map vertex edges between my nodes automatically. For The above example data the desired result is a list of directed edges pointing each node to its image, like so: $$\left\{1\to 2,2\to 3,2\to 4,3\to 5,3\to 6,4\to 7\right\}$$

My attempts get tied up with successive tables very quickly. So I'm looking for any advice or examples to follow.


POSTED BY: David Gathercole
3 Replies
Posted 10 years ago

You should check that output very carefully to make certain it is doing what you want. I'm not convinced I really understand exactly what the function should do with all possible variations of your input.

What the function was trying to do was massage the input into a consistent form and then use Outer to generate all the edges from source to destination verticies.

POSTED BY: Bill Simpson

That's really great Bill! Thank you so much.

A few of these functions are a tad unfamiliar to me, so this will hopefully fuel me to get through these sorts of problems alone in future.

POSTED BY: David Gathercole
Posted 10 years ago

Is this what you are looking for?

In[1]:= tree = {1, {2}, {{3, 4}}, {{{5, 6}, {7}}}};
flat[v_] := If[ListQ[v], Flatten[v], {v}];
verts = Map[{flat[First[#]], flat[Last[#]]} &, Partition[tree, 2, 1]];
edgelist = Flatten[Map[Outer[DirectedEdge, Sequence @@ #] &, verts]]

Out[3]= {1 \[DirectedEdge] 2, 2 \[DirectedEdge] 3, 2 \[DirectedEdge] 4, 3 \[DirectedEdge] 5,
 3 \[DirectedEdge] 6, 3 \[DirectedEdge] 7, 4 \[DirectedEdge] 5, 4 \[DirectedEdge] 6, 4 \[DirectedEdge] 7}

With a little bit of concentration and time it should be possible to simplify that even more.

POSTED BY: Bill Simpson
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract