Tag Info

Hot answers tagged

28

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


15

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


13

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


10

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


9

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

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]


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


8

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

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___] := ...


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

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


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


6

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


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


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

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


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

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


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

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


4

The benefit of using a symbolic tree representation with inert heads as in Leonid's parser is that you can then decide how to represent the data. And that is indeed what you should do, instead of extracting the elements using Cases. Here's an example using your parsed output above: Block[{ulContainer, liContainer}, ulContainer[_, l__] := {l}; ...


4

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


4

You appear to have an inefficiency in your algorithm. You generate a symmetrical correlation matrix and only use one element (correlations[[All, All, 1, 2]]). You also partition everything before processing which takes a lot of memory: ByteCount[partitionedData] 505899832 I suggest reformulating your code to produce only the significant correlation ...


4

I doubt if 'random' and elongated/compact can be nicely combined, but you can get close. With n=60 (60 leaves), there are CatalanNumber[60] or about 1.58385*10^33 binary trees to choose from. They can be written as binary strings (or numbers) ordered from 1111 ... 0000 to 101010...101010 with, counting from left to right, at least as many 1's as 0's in the ...


3

To Solve your example: Calculate the mean and the mean square deviation of the irregular partition of lengths n={3,2,5} of the list y={3,5,8,7,9,4,6,2,1,5}; (* irregular partitions of lists based on Nest *) iPartition[x_, lengths_] := First@Nest[{Append[First@#, Take[#[[2]], First@Last@#]], Drop[#[[2]], First@Last@#], Rest@Last@#} &, {{}, x, ...


3

Does this work for you: Unprotect@TreeForm SetAttributes[TreeForm, HoldFirst] TreeForm[e1 /. x -> 3] It has a superfluous TreeForm at the root ... maybe there is a way to remove that?


3

ClearAll[dL]; dL = Function[{str}, With[{s = Last@str}, Thread[s -> DictionaryLookup[Alternatives @@ (StringExpression @@ StringSplit[StringInsert[s, ".", #], "." -> LetterCharacter] & /@ Range[1 + StringLength@s])]]], Listable]; edges = DeleteDuplicates@Flatten@Rest@NestList[dL, {"a" ...



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