K idZddlmZmZddlmZmZddlZddl m Z gdZ ejddd Z ejddd Ze d ejdddd d Ze d ejdddd dZe d ejdddd dZddZdZdZdZe d ejddddddZdZdZdZe d ejdddddddZdZdZdZe d ejddddddZy) a Functions for generating trees. The functions sampling trees at random in this module come in two variants: labeled and unlabeled. The labeled variants sample from every possible tree with the given number of nodes uniformly at random. The unlabeled variants sample from every possible *isomorphism class* of trees with the given number of nodes uniformly at random. To understand the difference, consider the following example. There are two isomorphism classes of trees with four nodes. One is that of the path graph, the other is that of the star graph. The unlabeled variant will return a line graph or a star graph with probability 1/2. The labeled variant will return the line graph with probability 3/4 and the star graph with probability 1/4, because there are more labeled variants of the line graph than of the star graph. More precisely, the line graph has an automorphism group of order 2, whereas the star graph has an automorphism group of order 6, so the line graph has three times as many labeled variants as the star graph, and thus three more chances to be drawn. Additionally, some functions in this module can sample rooted trees and forests uniformly at random. A rooted tree is a tree with a designated root node. A rooted forest is a disjoint union of rooted trees. )Counter defaultdict)comb factorialN)py_random_state) prefix_treeprefix_tree_recursiverandom_labeled_treerandom_labeled_rooted_treerandom_labeled_rooted_forestrandom_unlabeled_treerandom_unlabeled_rooted_treerandom_unlabeled_rooted_forestT)graphs returns_graphc fd}tj d} j|dd j d|||}|t|j fg}|r|d\}} t |\}}t dz } j| | j|| || |}|j| t|j f|r S#t $r|jYwxYw)a(Creates a directed prefix tree from a list of paths. Usually the paths are described as strings or lists of integers. A "prefix tree" represents the prefix structure of the strings. Each node represents a prefix of some string. The root represents the empty prefix with children for the single letter prefixes which in turn have children for each double letter prefix starting with the single letter corresponding to the parent node, and so on. More generally the prefixes do not need to be strings. A prefix refers to the start of a sequence. The root has children for each one element prefix and they have children for each two element prefix that starts with the one element sequence of the parent, and so on. Note that this implementation uses integer nodes with an attribute. Each node has an attribute "source" whose value is the original element of the path to which this node corresponds. For example, suppose `paths` consists of one path: "can". Then the nodes `[1, 2, 3]` which represent this path have "source" values "c", "a" and "n". All the descendants of a node have a common prefix in the sequence/path associated with that node. From the returned tree, the prefix for each node can be constructed by traversing the tree up to the root and accumulating the "source" values along the way. The root node is always `0` and has "source" attribute `None`. The root is the only node with in-degree zero. The nil node is always `-1` and has "source" attribute `"NIL"`. The nil node is the only node with out-degree zero. Parameters ---------- paths: iterable of paths An iterable of paths which are themselves sequences. Matching prefixes among these sequences are identified with nodes of the prefix tree. One leaf of the tree is associated with each path. (Identical paths are associated with the same leaf of the tree.) Returns ------- tree: DiGraph A directed graph representing an arborescence consisting of the prefix tree generated by `paths`. Nodes are directed "downward", from parent to child. A special "synthetic" root node is added to be the parent of the first node in each path. A special "synthetic" leaf node, the "nil" node `-1`, is added to be the child of all nodes representing the last element in a path. (The addition of this nil node technically makes this not an arborescence but a directed acyclic graph; removing the nil node makes it an arborescence.) Notes ----- The prefix tree is also known as a *trie*. Examples -------- Create a prefix tree from a list of strings with common prefixes:: >>> paths = ["ab", "abs", "ad"] >>> T = nx.prefix_tree(paths) >>> list(T.edges) [(0, 1), (1, 2), (1, 4), (2, -1), (2, 3), (3, -1), (4, -1)] The leaf nodes can be obtained as predecessors of the nil node:: >>> root, NIL = 0, -1 >>> list(T.predecessors(NIL)) [2, 3, 4] To recover the original paths that generated the prefix tree, traverse up the tree from the node `-1` to the node `0`:: >>> recovered = [] >>> for v in T.predecessors(NIL): ... prefix = "" ... while v != root: ... prefix = str(T.nodes[v]["source"]) + prefix ... v = next(T.predecessors(v)) # only one predecessor ... recovered.append(prefix) >>> sorted(recovered) ['ab', 'abs', 'ad'] ctt}|D]/}|sj||^}}||j|1|SN)rlistadd_edgeappend)parentpathschildrenpathchildrestNILtrees _/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/networkx/generators/trees.py get_childrenz!prefix_tree..get_childrensTt$ )D fc*LED UO " "4 ( )rNsourcer) nxDiGraphadd_nodeiteritemsnext StopIterationpoplenrr) rr!rootrstackrremaining_childrenrremaining_pathsnew_namerrs @@r rr1s x  ::>> paths = ["ab", "abs", "ad"] >>> T = nx.prefix_tree(paths) >>> list(T.edges) [(0, 1), (1, 2), (1, 4), (2, -1), (2, 3), (3, -1), (4, -1)] The leaf nodes can be obtained as predecessors of the nil node. >>> root, NIL = 0, -1 >>> list(T.predecessors(NIL)) [2, 3, 4] To recover the original paths that generated the prefix tree, traverse up the tree from the node `-1` to the node `0`:: >>> recovered = [] >>> for v in T.predecessors(NIL): ... prefix = "" ... while v != root: ... prefix = str(T.nodes[v]["source"]) + prefix ... v = next(T.predecessors(v)) # only one predecessor ... recovered.append(prefix) >>> sorted(recovered) ['ab', 'abs', 'ad'] c6tt}|D]/}|s|j| |^}}||j|1|j D]B\}}t |dz }|j |||j|| |||Dy)apRecursively create a trie from the given list of paths. `paths` is a list of paths, each of which is itself a list of nodes, relative to the given `root` (but not including it). This list of paths will be interpreted as a tree-like structure, in which two paths that share a prefix represent two branches of the tree with the same initial segment. `root` is the parent of the node at index 0 in each path. `tree` is the "accumulator", the :class:`networkx.DiGraph` representing the branching to which the new nodes and edges will be added. r&r#N)rrrrr+r/r)) rr0rrrrrr3r4r_helpers r r7z&prefix_tree_recursive.._helpers$t$ )D dC(LED UO " "4 ( )'/nn&6 5 "E?4y1}H MM(5M 1 MM$ ) OXt 4  5r"rNr#r%r)r'r(r))rrr0rr7s @@r r r sR~"5J ::` Returns ------- :class:`networkx.Graph` A `networkx.Graph` with nodes in the set {0, …, *n* - 1}. Raises ------ NetworkXPointlessConcept If `n` is zero (because the null graph is not a tree). Examples -------- >>> G = nx.random_labeled_tree(5, seed=42) >>> nx.is_tree(G) True >>> G.edges EdgeView([(0, 1), (0, 3), (0, 2), (2, 4)]) A tree with *arbitrarily directed* edges can be created by assigning generated edges to a ``DiGraph``: >>> DG = nx.DiGraph() >>> DG.add_edges_from(G.edges) >>> nx.is_tree(DG) True >>> DG.edges OutEdgeView([(0, 1), (0, 3), (0, 2), (2, 4)]) rthe null graph is not a treer&)r'NetworkXPointlessConcept empty_graphfrom_prufer_sequencerangechoice)nr8is r r r Dsh^ Av))*HIIAv~~a  " "5Q<#PaDKKa$9#P QQ#Ps!A<cdt||}|jd|dz |jd<|S)aPReturns a labeled rooted tree with `n` nodes. The returned tree is chosen uniformly at random from all labeled rooted trees. Parameters ---------- n : int The number of nodes seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness`. Returns ------- :class:`networkx.Graph` A `networkx.Graph` with integer nodes 0 <= node <= `n` - 1. The root of the tree is selected uniformly from the nodes. The "root" graph attribute identifies the root of the tree. Notes ----- This function returns the result of :func:`random_labeled_tree` with a randomly selected root. Raises ------ NetworkXPointlessConcept If `n` is zero (because the null graph is not a tree). r9rr&r0)r randintgraph)rBr8ts r r r zs2@ AD)All1a!e,AGGFO Hr"cd}tj|}|dk(ri|jd<|S|||}||k(r#tt ||jd<|S|j t ||}tt |j |}t ||z dz Dcgc]}|jd|dz }}t|D cgc] } | |vs|  c} tfd|D} t| x} } |D]>} |j| | | xxdzcc<| | kr | dk(r| } 2t| x} } @|j| |dt||jd<|Scc}wcc} w)uReturns a labeled rooted forest with `n` nodes. The returned forest is chosen uniformly at random using a generalization of Prüfer sequences [1]_ in the form described in [2]_. Parameters ---------- n : int The number of nodes. seed : random_state See :ref:`Randomness`. Returns ------- :class:`networkx.Graph` A `networkx.Graph` with integer nodes 0 <= node <= `n` - 1. The "roots" graph attribute is a set of integers containing the roots. References ---------- .. [1] Knuth, Donald E. "Another Enumeration of Trees." Canadian Journal of Mathematics, 20 (1968): 1077-1086. https://doi.org/10.4153/CJM-1968-104-8 .. [2] Rubey, Martin. "Counting Spanning Trees". Diplomarbeit zur Erlangung des akademischen Grades Magister der Naturwissenschaften an der Formal- und Naturwissenschaftlichen Fakultät der Universität Wien. Wien, May 2000. c|jd|dz|dz zdz }d}td|D]C}|t|dz |||z zzt|dz t||z zzz }||ksA|cS|S)Nrr&)rEr@r)rBr8rcum_sumks r _select_kz/random_labeled_rooted_forest.._select_ks LLQUA.2 3q! A  !a%(1Q<7!a% 9QU#33 G7{  r"rrootsr&c34K|]}|dk(s |yw)rN).0xdegrees r z/random_labeled_rooted_forest..s3!F1INA3s ) r'r>rFsetr@sample differencerErr*r,r)rBr8rMFrLrNprCNrRiteratorulastvrSs @r r r sxD  qAAv!TAAvuQx= KKa! $E E!H   'A).q1uqy)9:AaQ :A: -Aa1fa- .F3q33HH~A& 1aq Q t8q QAH~ %D1 &JJq%(5zAGGG H% ;-s2F F#Fctj|}|j||||jd<|||jd<|S)a% Converts the (edges, n_nodes) input to a :class:`networkx.Graph`. The (edges, n_nodes) input is a list of even length, where each pair of consecutive integers represents an edge, and an integer `n_nodes`. Integers in the list are elements of `range(n_nodes)`. Parameters ---------- edges : list of ints The flattened list of edges of the graph. n_nodes : int The number of nodes of the graph. root: int (default=None) If not None, the "root" attribute of the graph will be set to this value. roots: collection of ints (default=None) If not None, he "roots" attribute of the graph will be set to this value. Returns ------- :class:`networkx.Graph` The graph with `n_nodes` nodes and edges given by `edges`. r0rN)r'r>add_edges_fromrF)edgesn_nodesr0rNGs r _to_nxrdsL. wAU    Hr"ctt||dzD]h}|jttd|Dcgc]0}td|dz |zdzD]}|||||zz z||z2c}}|dz zj||Scc}}w)aReturns the number of unlabeled rooted trees with `n` nodes. See also https://oeis.org/A000081. Parameters ---------- n : int The number of nodes cache_trees : list of ints The $i$-th element is the number of unlabeled rooted trees with $i$ nodes, which is used as a cache (and is extended to length $n+1$ if needed) Returns ------- int The number of unlabeled rooted trees with `n` nodes. r&)r@r/rsum)rB cache_treesn_idjs r _num_rooted_treesrks$S%q1u-   #1c]"1sQw1nq&89 C!a%K00;q>AA a     q>s5B c |jdt|||dz zdz }d}t|dz ddD]N}td|dz |zdzD]4}||t|||zz |zt||zz }||ks.||fccSPy)aReturns a pair $(j,d)$ with a specific probability Given $n$, returns a pair of positive integers $(j,d)$ with the probability specified in formula (5) of Chapter 29 of [1]_. Parameters ---------- n : int The number of nodes cache_trees : list of ints Cache for :func:`_num_rooted_trees`. seed : random_state See :ref:`Randomness`. Returns ------- (int, int) A pair of positive integers $(j,d)$ satisfying formula (5) of Chapter 29 of [1]_. References ---------- .. [1] Nijenhuis, Albert, and Wilf, Herbert S. "Combinatorial algorithms: for computers and calculators." Academic Press, 1978. https://doi.org/10.1016/C2013-0-11243-3 rr&r%N)rErkr@)rBrgr8rYcumsumrirjs r _select_jd_treesrn3s8 Q)![9QUCaGHA F 1q5!R q1q5Q,*+ A #AAI{;<#A{34 F 6z1v  r"cx |dk(rgd}}||fS|dk(r dgd}}||fSt|||\}}t|||zz ||\} t|||\}} t|D cgc] } d| | z zf} } |j| t|D]!} |j fd|D | z #| fScc} w)aReturns an unlabeled rooted tree with `n` nodes. Returns an unlabeled rooted tree with `n` nodes chosen uniformly at random using the "RANRUT" algorithm from [1]_. The tree is returned in the form: (list_of_edges, number_of_nodes) Parameters ---------- n : int The number of nodes, greater than zero. cache_trees : list ints Cache for :func:`_num_rooted_trees`. seed : random_state See :ref:`Randomness`. Returns ------- (list_of_edges, number_of_nodes) : list, int A random unlabeled rooted tree with `n` nodes as a 2-tuple ``(list_of_edges, number_of_nodes)``. The root is node 0. References ---------- .. [1] Nijenhuis, Albert, and Wilf, Herbert S. "Combinatorial algorithms: for computers and calculators." Academic Press, 1978. https://doi.org/10.1016/C2013-0-11243-3 r&r<)rr&rc38K|]\}}|z|zfywrrPrQn1n2t1_nodess r rTz0_random_unlabeled_rooted_tree.."BVR2="x-0B)rn_random_unlabeled_rooted_treer@extend)rBrgr8rarbrjrit1t2t2_nodesrCt12_rts @r rwrw\s< AvQwg~Av 1wg~ A{D 1DAq0QUKNLB0KFLB16q :AAx!|h& ' :C :IIcN 1X BrBBH x< ;s B7)number_of_treesr8c |dk(rtjdddg}|tt|||ddiSt |Dcgc]}tt|||ddic}Scc}w)uReturns a number of unlabeled rooted trees uniformly at random Returns one or more (depending on `number_of_trees`) unlabeled rooted trees with `n` nodes drawn uniformly at random. Parameters ---------- n : int The number of nodes number_of_trees : int or None (default) If not None, this number of trees is generated and returned. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness`. Returns ------- :class:`networkx.Graph` or list of :class:`networkx.Graph` A single `networkx.Graph` (or a list thereof, if `number_of_trees` is specified) with nodes in the set {0, …, *n* - 1}. The "root" graph attribute identifies the root of the tree. Notes ----- The trees are generated using the "RANRUT" algorithm from [1]_. The algorithm needs to compute some counting functions that are relatively expensive: in case several trees are needed, it is advisable to use the `number_of_trees` optional argument to reuse the counting functions. Raises ------ NetworkXPointlessConcept If `n` is zero (because the null graph is not a tree). References ---------- .. [1] Nijenhuis, Albert, and Wilf, Herbert S. "Combinatorial algorithms: for computers and calculators." Academic Press, 1978. https://doi.org/10.1016/C2013-0-11243-3 rr;r&r0)r'r=rdrwr@)rBr~r8rgrCs r rrs\ Av))*HIIa&K4Q TJSQRSS'   -adCL!L  sA$c6tt||dzD]t}t||}|jt td|dzDcgc]0}td||zdzD]}|||||zz z||dz z2c}}|zv||Scc}}w)aReturns the number of unlabeled rooted forests with `n` nodes, and with no more than `q` nodes per tree. A recursive formula for this is (2) in [1]_. This function is implemented using dynamic programming instead of recursion. Parameters ---------- n : int The number of nodes. q : int The maximum number of nodes for each tree of the forest. cache_forests : list of ints The $i$-th element is the number of unlabeled rooted forests with $i$ nodes, and with no more than `q` nodes per tree; this is used as a cache (and is extended to length `n` + 1 if needed). Returns ------- int The number of unlabeled rooted forests with `n` nodes with no more than `q` nodes per tree. References ---------- .. [1] Wilf, Herbert S. "The uniform selection of free trees." Journal of Algorithms 2.2 (1981): 204-207. https://doi.org/10.1016/0196-6774(81)90021-3 r&)r@r/minrrf)rBq cache_forestsrhq_irirjs r _num_rooted_forestsrs:S'Q/  #qk #1cAg."1cQhl3 cAEk22]1q55III       s 5Bc |jdt||||zdz }d}t|ddD]P}td||zdzD]9}||t|||zz ||zt|dz ||zz }||ks3||fccSRy)aGiven `n` and `q`, returns a pair of positive integers $(j,d)$ such that $j\leq d$, with probability satisfying (F1) of [1]_. Parameters ---------- n : int The number of nodes. q : int The maximum number of nodes for each tree of the forest. cache_forests : list of ints Cache for :func:`_num_rooted_forests`. seed : random_state See :ref:`Randomness`. Returns ------- (int, int) A pair of positive integers $(j,d)$ References ---------- .. [1] Wilf, Herbert S. "The uniform selection of free trees." Journal of Algorithms 2.2 (1981): 204-207. https://doi.org/10.1016/0196-6774(81)90021-3 rr&r%N)rErr@)rBrrr8rYrmrirjs r _select_jd_forestsrs4 Q+Aq-@1DqHIA F 1a_q!q&1*% A %a!a%iMBC%a!eQ >? F 6z1v  r"c |dk(rgdgfSt||||\}}t|||zz ||||\} }t|||\} } t|D]2} |j |j fd| D | z 4| |fS)aHReturns an unlabeled rooted forest with `n` nodes, and with no more than `q` nodes per tree, drawn uniformly at random. It is an implementation of the algorithm "Forest" of [1]_. Parameters ---------- n : int The number of nodes. q : int The maximum number of nodes per tree. cache_trees : Cache for :func:`_num_rooted_trees`. cache_forests : Cache for :func:`_num_rooted_forests`. seed : random_state See :ref:`Randomness`. Returns ------- (edges, n, r) : (list, int, list) The forest (edges, n) and a list r of root nodes. References ---------- .. [1] Wilf, Herbert S. "The uniform selection of free trees." Journal of Algorithms 2.2 (1981): 204-207. https://doi.org/10.1016/0196-6774(81)90021-3 rc38K|]\}}|z|zfywrrPrqs r rTz2_random_unlabeled_rooted_forest..Arurv)r_random_unlabeled_rooted_forestrwr@rrx) rBrrgrr8rjriryr1rzr{r}rts @r rrs: AvAr{ aM4 8DAq6 AE 1k=$B"1KFLB 1X ( BrBBH x r")rnumber_of_forestsr8c 4||}|dk(r|dk7r tdddg}dg}|*t|||||\}}}t||t|Sg} t |D];} t|||||\}}}| j t||t|=| S)upReturns a forest or list of forests selected at random. Returns one or more (depending on `number_of_forests`) unlabeled rooted forests with `n` nodes, and with no more than `q` nodes per tree, drawn uniformly at random. The "roots" graph attribute identifies the roots of the forest. Parameters ---------- n : int The number of nodes q : int or None (default) The maximum number of nodes per tree. number_of_forests : int or None (default) If not None, this number of forests is generated and returned. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness`. Returns ------- :class:`networkx.Graph` or list of :class:`networkx.Graph` A single `networkx.Graph` (or a list thereof, if `number_of_forests` is specified) with nodes in the set {0, …, *n* - 1}. The "roots" graph attribute is a set containing the roots of the trees in the forest. Notes ----- This function implements the algorithm "Forest" of [1]_. The algorithm needs to compute some counting functions that are relatively expensive: in case several trees are needed, it is advisable to use the `number_of_forests` optional argument to reuse the counting functions. Raises ------ ValueError If `n` is non-zero but `q` is zero. References ---------- .. [1] Wilf, Herbert S. "The uniform selection of free trees." Journal of Algorithms 2.2 (1981): 204-207. https://doi.org/10.1016/0196-6774(81)90021-3 rz.q must be a positive integer if n is positive.r&)rN) ValueErrorrrdrUr@r) rBrrr8rgrgnodesrsresrCs r rrFsb y Av!q&IJJa&KCM 6 q+}d 5"ac"g.. C $ %46 q+}d 5" 6!U#b'23 4 Jr"c t||ttd|dzdzDcgc]}t||t||z |z c}z }|dzdk(r|tt|dz|dzdz }|Scc}w)aMReturns the number of unlabeled trees with `n` nodes. See also https://oeis.org/A000055. Parameters ---------- n : int The number of nodes. cache_trees : list of ints Cache for :func:`_num_rooted_trees`. Returns ------- int The number of unlabeled trees with `n` nodes. r&r<r)rkrfr@r)rBrgrjrJs r _num_treesrs" ![)C1a1fqj)  a -0A!a%0U U - A  1uz T#AFK81` Returns ------- (edges, n) The tree as a list of edges and number of nodes. References ---------- .. [1] Wilf, Herbert S. "The uniform selection of free trees." Journal of Algorithms 2.2 (1981): 204-207. https://doi.org/10.1016/0196-6774(81)90021-3 r<r)rwrErkrxr) rBcacher8rGt_nodesrzr{rrrss r _bicenterrs2/qAvudCJAw ||A(a78A='H4Q!VUDI HHH2 >RrQ!V}bAFm, >?HHaa[ g  ?sB c(|dzdk(rd}ntt|dz|dzd}|jdt||dz |kr t |||St |dz |dz dz|||\}}}|D]}|j ||f||dzfS)a Returns a tree on `n` nodes drawn uniformly at random. It implements the Wilf's algorithm "Free" of [1]_. Parameters ---------- n : int The number of nodes, greater than zero. cache_trees : list of ints Cache for :func:`_num_rooted_trees`. cache_forests : list of ints Cache for :func:`_num_rooted_forests`. seed : random_state Indicator of random number generation state. See :ref:`Randomness` Returns ------- (edges, n) The tree as a list of edges and number of nodes. References ---------- .. [1] Wilf, Herbert S. "The uniform selection of free trees." Journal of Algorithms 2.2 (1981): 204-207. https://doi.org/10.1016/0196-6774(81)90021-3 r<r&r)rrkrErrrr) rBrgrr8rYfn_frJrCs r _random_unlabeled_treers6 1uz  "16;7!;Q ? ||Az![1A56:K..3 EAEa<mT 3 A HHaX  #'zr"c |dk(rtjdddg}dg}|tt||||St |Dcgc]}tt||||c}Scc}w)uReturns a tree or list of trees chosen randomly. Returns one or more (depending on `number_of_trees`) unlabeled trees with `n` nodes drawn uniformly at random. Parameters ---------- n : int The number of nodes number_of_trees : int or None (default) If not None, this number of trees is generated and returned. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness`. Returns ------- :class:`networkx.Graph` or list of :class:`networkx.Graph` A single `networkx.Graph` (or a list thereof, if `number_of_trees` is specified) with nodes in the set {0, …, *n* - 1}. Raises ------ NetworkXPointlessConcept If `n` is zero (because the null graph is not a tree). Notes ----- This function generates an unlabeled tree uniformly at random using Wilf's algorithm "Free" of [1]_. The algorithm needs to compute some counting functions that are relatively expensive: in case several trees are needed, it is advisable to use the `number_of_trees` optional argument to reuse the counting functions. References ---------- .. [1] Wilf, Herbert S. "The uniform selection of free trees." Journal of Algorithms 2.2 (1981): 204-207. https://doi.org/10.1016/0196-6774(81)90021-3 rr;r&)r'r=rdrr@)rBr~r8rgrrCs r r r sX Av))*HIIa&KCM-amTRSS?+  *1k=$O P   sA#)NN)__doc__ collectionsrrmathrrnetworkxr'networkx.utilsr__all__ _dispatchablerr r r r rdrkrnrwrrrrrrrrr rPr"r rs<- * T2A3AHT2J3JZT2#'1R31RhT2*.  3  FT2,0L 3L d @@&R.bT27;$434n*Z$N)XT2+/4dC3CL 8 !F'TT20445 35 r"