Hot answers tagged

32

You can make trees from horses and mazes ;-) Images for these can be found in documentation for SkeletonTransform and MorphologicalGraph. Actually, trees are everywhere. Arbitrary expressions have the structure of arbitrary trees. Imagine taking an integral: Integrate[Sin[(1 - x)/(1 + x)], x] This will give you a pretty random tree if you apply ...


18

Here is one way of doing it based on an example in TreePlot. We create a function to generate a random set of edges and form a graph as: vtx[] := Table[i <-> RandomInteger[{0, i - 1}], {i, 1, 50}]; Graph@vtx[] Generate several: Table[Graph@vtx[], {12}] ~Partition~ 4 // Grid


14

I think Mathematica with its symbolic and pattern-matching capabilites is well suited to tackle parser and tree searching. It's better to check, though. Here are two quick proof-of-concept of the toy engine. One ad-hoc, the other using functional parsers. It' s readily apparent that every simple selector can be mapped to some form of XMLElement pattern: ...


12

Update: functions to generate the edge list, indices and labels: ClearAll[layersF, edgesF, subscF, indicesF]; layersF = Module[{k = 1}, Table[k++, {i, #}, {j, i}]] &; edgesF = Flatten[Thread /@ Thread[# -> Partition[#2, 2, 1]] & @@@ Partition[layersF[#], 2, 1], 2] &; indicesF = Reverse[Thread /@ ...


11

The following is a slight modification to @amr's code. It shows a directory tree using TreeForm[], with a button at each vertex. When the button is pressed, it opens a dialog with the list of the files contained in that directory. ellipsizeMax = 8; ellipsize[str_] := If[StringLength[str] > ellipsizeMax, StringTake[str, ellipsizeMax] <> ...


10

The Combinatorica package has a function CodeToLabeledTree[] for generating trees from their corresponding Prüfer codes. Since the old function was adapted for Combinatorica Graph[] objects, as opposed to the built-in Graph[] objects introduced in version 8, some modification of the code in the package is needed: CodeToLabeledTree[l_List, opts___] := ...


10

This is a job for recursion: ClearAll[f]; f[{fst : {{left__}, _}, sub : Longest[{{left__, __}, _} ...], rest___}] := {{fst, f[{sub}]} /. {el_, {}} :> el, Sequence @@ f[{rest}]}; f[x_] := x; The usage is f[your-initial-structure]


10

You can build the list of elements of the form {parent,childrenlist}, ordered by tree depth (largest first), as below. Clear[distance, ordervertices, orderedvertices, families, children, orderedparents, orderedvisits]; distance[s_, v_] := Length[FindShortestPath[s, 1, v]] - 1 ordervertices[s_] := With[{verts = VertexList[s]}, ...


9

If I understand you correctly, is the following what you want? correlations2 = Map[ Outer[Correlation, #, #, 1] &[Transpose[#]] &, partitionedData, {2}]; Now the Correlation receives two vector as its input, and you can replace it with SpearmanRankCorrelation or KendallRankCorrelation legally. To verify it, compare correlations2 with your ...


9

Here's a relatively straightforward "first version": ellipsizeMax = 8; ellipsize[str_] := If[StringLength[str] > ellipsizeMax, StringTake[str, ellipsizeMax] <> "\[Ellipsis]", str]; readDir[currentDirectory_, 0] := ellipsize[FileNameTake[currentDirectory]]; readDir[currentDirectory_, level_] := Module[{joinedFiles, perFile}, ...


9

Creating the edge list The index and edges can be worked out like this: step[list_, n_] := Block[ { ln1 = list[[1]] , ln2 = list[[2]] }, Join[ If[ln2 < n , {{ln1, ln2 + 1} -> {ln1, ln2}}, {}], If[ln2 < n, {{ln1, ln2 + 1} -> {ln1 + 1, ln2 }}, {}], If[ln1 + ln2 + 1 < n, step[{ln1, ln2 + 1}, n], {}], ...


8

It would be nice to have a real big sample, but I hope it works anyway. Here is the approach: I would extract the information level by level and build up the structure. Level 1 contains the sections and this is basically your starting point Select[input, Length[First[#]] === 1 &] All section number lists which have a length of one are your sections. ...


8

Your input is the frequencies at each generation. Let's write them down freq = {{1, 5.15}, {2, 1.47}, {3, 1.47}}; For convenience we might define one of your lines to be a Node[p,g] where p is the x-position and g is the generation. With this you can directly draw lines or use the positions with a Graph. Let's have a look how we can create the complete ...


8

A function to recursively generate the edges: n[_, 0] := {}; n[x : 0, y_Integer] /; y > 0 := {{x, y} -> {x, y - 1}, {x, y} -> {x + 1, y - 1}, n[x + 1, y - 1], n[x, y - 1]}; n[x_Integer, y_Integer] /; y > 0 := {{x, y} -> {x, y - 1}, {x, y} -> {x + 1, y - 1}, n[x + 1, y - 1]}; We have to sort the vertices so that the ...


8

Some time ago (before Mathematica had the function Classify) I developed a package for construction of Decision trees and classification with them. The trees produced by that package might be a good start for making the trees from the three different perspectives listed in the question. More precisely, with the package one can build a tree using entropy ...


7

Method starts off by replacing all heads in the expression with the appropriate node index, then deduces the edge list by parsing the substituted node-index-expression. Note that input expression must be wrapped in Hold (or HoldComplete) to prevent evaluation of e.g. Plus[1, 2] into 3. (* sow node -> label replacements *) sowLabel[x_?AtomQ] := (Sow[# ...


7

It's not a TreeMap using non-rectangles. But maybe can inspire someone to go beyond. I believe that I get a nice squarification using this article suggested by @M.R. The code is for Mathematica V10, and can be tested in the WolframCloud. I played with Associations and some others new MMA funcitons as Area and the new @* notation. (*Test Function*) ...


7

Anyway, Treegraph offers a lot of flexibility: nodes = {RandomInteger[#] , # + 1} & /@ Range[0, 30]; rn = Range@Length@nodes; crules = Rule @@@ Partition[Riffle[rn, ColorData[15, "ColorList"]], 2]; g = TreeGraph[UndirectedEdge @@@ nodes, VertexSize -> 0.4, VertexStyle -> crules]; HighlightGraph[g, PathGraph@FindShortestPath[g, 1, 30], ...


6

The simplest way to do what you'd like to do seems to be this: e1 /. x -> "3" Head["3"] String Replacing x by a string "3" prevents evaluating a part of the expression including Times[3, x]. A bit more tricky way yielding the same result would be this: e1 /. x -> String["3"][[1]]


6

I guess what you want with your example input is the following tree = {3, {2, {1, None, None}, None}, None}; TreeForm[tree //. {root_, left_, right_} :> root[left, right]]


6

Just to show a less elegant way :) f[m_] := Apply[m[[##]] &, Table[{i - j + 1, j}, {i, Length@m}, {j, i}], {2}] f@m (*{{1}, {5, 2}, {9, 6, 3}, {13, 10, 7, 4}}*)


6

m = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; MapThread[m[[##]] &, {Reverse@Range@#, Range@#}] & /@ Range@Length@m {{1}, {5, 2}, {9, 6, 3}, {13, 10, 7, 4}}


6

No, this is not a bug in VertexDelete. Some background first: TreePlot, along with GraphPlot, is an old function that predates the introduction of Graph objects. Consider it deprecated that is only kept for backwards compatibility. The proper way to display vertex labels for a Graph object is g = CompleteKaryTree[5, DirectedEdges -> True, ...


5

This might not be the most efficient way, but seems to do it: ClearAll[expr]; expr[1] = {u[x]}; expr[n_Integer?Positive] := expr[n] = Join[ DeleteDuplicates@Flatten@Table[ Outer[Times, expr[n - k], expr[k]], {k, 1, n - 1} ], Map[u, expr[n - 1]] ]; For example: expr[3] (* {u[x]^3, u[x] u[u[x]], u[u[x]^2], u[u[u[x]]]} ...


5

Seems TreeForm leaks evaluation when formatting, but wrapping an extra Unevaluated seems to solve it. So e1 := 3 x + 2 (1 + y) z // Unevaluated // Unevaluated // TreeForm Now it all seems to work


5

I liked a response that got deleted. If all you want is the cosmetic look, and do not care if the expression is actually altered, here is something I use to make expressions "inert". The idea is to replace numeric functions with their string names. inertify[expr_Hold] := Module[{xx}, xx[Release[ expr /. f_Symbol /; MemberQ[Attributes[f], ...


5

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 ...


5

Not a perfect match but a start Partition[Table[Column[{"i = " <> ToString[2^(n - 1)], CompleteKaryTree[n, ImagePadding -> 10, (AbsoluteOptions[ CompleteKaryTree[n, VertexLabels -> "Name", ImagePadding -> 10], VertexCoordinates] /. {x_?NumericQ, y_?NumericQ} :> {x, -y})], "\[Omega] = " <> ToString[n]}, Center], ...


5

If you have Version 9, you can use the GraphLayout suboptions as follows: bbt[n_] := Labeled[GraphUnion[CompleteKaryTree[n], Graph[{UndirectedEdge[0, 1]}], BaseStyle ->Directive[Opacity[1], Black, PointSize[.015]], EdgeStyle -> Directive[{Black, Thick}], AspectRatio -> 1, VertexShapeFunction ...


5

The first thing I want to say is that I think Anton Antonov's solution is great. But, you wanted to be able to change the criteria for splitting, and that might be hard given that it is a library (I haven't checked the code, so I don't know). There is no in-built function either. So I got the idea that I would try to create some straight-forward code where ...



Only top voted, non community-wiki answers of a minimum length are eligible