generate_random_tree#
- graph_tool.generation.generate_random_tree(N, labeled=True, rooted=False)[git][source]#
Generate a uniformly random tree.
- Parameters:
- N
int Number of vertices.
- labeled
bool(optional, default:True) If
True, the tree is chosen uniformly among the labeled trees, and otherwise among the unlabeled ones (i.e. the isomorphism classes).- rooted
bool(optional, default:False) If
True, the tree is chosen uniformly among the rooted trees, and its root is returned.
- N
- Returns:
- g
Graph The generated undirected tree.
- root
int(only ifrooted == True) The root vertex.
- g
See also
generate_random_forestUniformly random forests
prufer_treeTree with a given Prüfer sequence
graph_tool.structure.random_spanning_treeUniformly random spanning tree of a graph
Notes
Labeled trees are generated from a uniformly random Prüfer sequence (see
prufer_tree()), in time \(O(N)\), and rooted at a uniformly chosen vertex ifrooted == True.Unlabeled rooted trees are generated with the algorithm of Nijenhuis and Wilf [nijenhuis-combinatorial-1978], which attaches \(j\) copies of a random rooted tree with \(d\) vertices to the root of a random rooted tree with \(N - jd\) vertices, choosing \((j, d)\) with the probability that makes every rooted tree equally likely. Unlabeled free trees are generated with the algorithm of Wilf [wilf-uniform-1981], as two rooted trees joined at their roots, if the tree has two centroids, or as a root joined to a forest of rooted trees with at most \((N-1)/2\) vertices. The counts of the trees are computed exactly (with GMP integers), by evaluating their recurrences with a divide-and-conquer convolution that needs \(O(\log N)\) products of integers with \(O(N^2)\) bits, and the choices take \(O(N^2)\) operations in the worst case.
References
[nijenhuis-combinatorial-1978]Albert Nijenhuis and Herbert S. Wilf, “Combinatorial Algorithms for Computers and Calculators”, 2nd ed., Academic Press (1978), Chapter 29, DOI: 10.1016/C2013-0-11243-3 [sci-hub, @tor]
[wilf-uniform-1981]Herbert S. Wilf, “The uniform selection of free trees”, Journal of Algorithms 2, 204-207 (1981), DOI: 10.1016/0196-6774(81)90021-3 [sci-hub, @tor]
Examples
>>> g = gt.generate_random_tree(100) >>> print(g.num_edges(), gt.label_components(g)[1]) 99 [100] >>> g, root = gt.generate_random_tree(100, labeled=False, rooted=True) >>> print(g.num_edges(), root) 99 0
A uniformly random labeled tree is drawn as follows:
>>> g = gt.generate_random_tree(100) >>> gt.graph_draw(g, pos=gt.sfdp_layout(g), ... output="generate_random_tree-labeled.pdf") <...>
Uniformly random labeled tree with \(N=100\) vertices.#