The following code comes from OEIS A000311 which is labeled phylogenetic trees. The function mtot
enumerates the labeled trees.
size=4;
sps[{}] := {{}};
sps[set : {i_, ___}] :=
Join @@ Function[s, Prepend[#, s] & /@ sps[Complement[set, s]]] /@
Cases[Subsets[set], {i, ___}];
mtot[m_] :=
Prepend[Join @@
Table[Tuples[mtot /@ p], {p,
Select[sps[m], 1 < Length[#] < Length[m] &]}], m];
Table[Length[mtot[Range[n]]], {n, 1, size}]
(*Labeled trees*)
mtot[Range[4]]
>{{1,2,3,4},{{1},{2},{3,4}},{{1},{2,3},{4}},{{1},{2,4},{3}},{{1},{2,3,4}},
{{1},{{2},{3,4}}},{{1},{{2,3},{4}},{{1},{{2,4},{3}}},{{1,2},{3},{4}},
{{1,2},{3,4}},{{1,3},{2},{4}},{{1,3},{2,4}},{{1,4},{2},{3}},{{1,4},{2,3}},
{{1,2,3},{4}},{{{1},{2,3}},{4}},{{{1,2},{3}},{4}},{{{1,3},{2}},{4}},
{{1,2,4},{3}},{{{1},{2,4}},{3}},{{{1,2},{4}},{3}},{{{1,4},{2}},{3}},
{{1,3,4},{2}},{{{1},{3,4}},{2}},{{{1,3},{4}},{2}},{{{1,4},{3}},{2}}}
What I need is an fast method of enumerating unlabeled trees. See OEIS A000669 While the labeled trees can be used to find the unlabeled trees, it is very inefficient.
(*Unlabeled trees*)
{{o,o,o,o},{o,o,{o,o}},{o,{o,o,o}},{o,{o,{o,o}}},{{o,o},{o,o}}}
(*Number of first 6 enumerated labeled trees*)
{1,1,4,26,236,2752,39208,660032};
(*Number of first 6 enumerated unlabeled trees*)
{1,1,2,5,12,33,90,261};
geng
utility from the nauty suite. It can generate all unlabelled graphs with $n$ vertices and $m$ edges, with certain constraints. If we want trees, we can ask for connceted graphs with $n$ vertices and $n-1$ edges. For example, with $n=7$, useImport["!geng 7 6 -c", "Graph6"]
. You may need to put the absolute path togeng
for your system. $\endgroup$Function[n, Catenate[ Function[tree, DeleteDuplicatesBy[IGOrientTree[tree, #] & /@ VertexList[tree], CanonicalGraph]] /@ IGImport[ "!/opt/local/bin/geng " <> IntegerString[n] <> " " <> IntegerString[n - 1] <> " -c", "Nauty"]]]
Remember to edit the path togeng
for your system. $\endgroup$