o
    Rŀg                     @   s   d Z ddlZddlZddlZddlZddlZdd Zdd Zdd Zd	d
 Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd ZG dd dZG dd dZG dd  d eeZG d!d" d"eeZG d#d$ d$ZdS )%zBase classes for Bio.Phylo objects.

All object representations for phylogenetic trees should derive from these base
classes in order to use the common methods defined on them.
    Nc                 c   s:    t | g}|r| }|V  ||| |s	dS dS )z9Traverse a tree in breadth-first (level) order (PRIVATE).N)collectionsdequepopleftextend)rootget_childrenQv r
   F/var/www/html/myenv/lib/python3.10/site-packages/Bio/Phylo/BaseTree.py_level_traverse   s   r   c                 #   "     fdd  | E dH  dS )zLTraverse a tree in depth-first pre-order (parent before children) (PRIVATE).c                 3   s(    | V  | D ]	} |E d H  qd S Nr
   elemr	   dfsr   r
   r   r   #   s
   z_preorder_traverse.<locals>.dfsNr
   r   r   r
   r   r   _preorder_traverse       r   c                 #   r   )zMTraverse a tree in depth-first post-order (children before parent) (PRIVATE).c                 3   s(    | D ]	} |E d H  q| V  d S r   r
   r   r   r
   r   r   .   s   
z _postorder_traverse.<locals>.dfsNr
   r   r
   r   r   _postorder_traverse+   r   r   c                 C   sd   g }g }t | j dd dD ]\}}|du rqt|tr#|| q|| qdd || D S )zGGet a flat list of elem's attributes, sorted for consistency (PRIVATE).c                 S      | d S Nr   r
   )kvr
   r
   r   <lambda>;       z_sorted_attrs.<locals>.<lambda>keyNc                 s   s    | ]
}t |tr|V  qd S r   )
isinstanceTreeElement).0xr
   r
   r   	<genexpr>B   s    z _sorted_attrs.<locals>.<genexpr>)sorted__dict__itemsr   listr   append)r   singleslistsattrnamechildr
   r
   r   _sorted_attrs6   s   
r,   c                        fdd}|S )z8Match a node to the target object by identity (PRIVATE).c                    s   |  u S r   r
   nodetargetr
   r   matchK      z _identity_matcher.<locals>.matchr
   r1   r2   r
   r0   r   _identity_matcherH      r5   c                    r-   )z>Match a node if it's an instance of the given class (PRIVATE).c                    s
   t |  S r   )r   r.   
target_clsr
   r   r2   T   s   
z_class_matcher.<locals>.matchr
   )r8   r2   r
   r7   r   _class_matcherQ   r6   r9   c                    r-   )Nc                    s$   t | ttfr| j kS t|  kS r   )r   CladeTreenamestrr.   r0   r
   r   r2   [   s   
z_string_matcher.<locals>.matchr
   r4   r
   r0   r   _string_matcherZ   s   r>   c                    r-   )aU  Match a node by specified attribute values (PRIVATE).

    ``terminal`` is a special case: True restricts the search to external (leaf)
    nodes, False restricts to internal nodes, and None allows all tree elements
    to be searched, including phyloXML annotations.

    Otherwise, for a tree element to match the specification (i.e. for the
    function produced by ``_attribute_matcher`` to return True when given a tree
    element), it must have each of the attributes specified by the keys and
    match each of the corresponding values -- think 'and', not 'or', for
    multiple keys.
    c                    s   d v r   }|d}|d urt| dr|  |krdS n }| D ]O\}}t| |s1 dS t| |}t|trJt|toGt	|d |  S t|t
rW|t
|k  S t|trb||k  S |d u rl|d u   S tdt| dS )Nterminalis_terminalF$zinvalid query type: T)copypophasattrr@   r%   getattrr   r=   rer2   boolint	TypeErrortype)r/   kwa_copypatternr   r1   kwargsr
   r   r2   r   s0   





z!_attribute_matcher.<locals>.matchr
   )rN   r2   r
   rM   r   _attribute_matcherd   s   rO   c                    r-   )zNSafer attribute lookup -- returns False instead of raising an error (PRIVATE).c                    s(   z | W S  t tttfy   Y dS w )NF)LookupErrorAttributeError
ValueErrorrI   r.   matcher_funcr
   r   r2      s
   
z _function_matcher.<locals>.matchr
   )rT   r2   r
   rS   r   _function_matcher   s   rU   c                 C   sp   t | tr	t| S t | trt| S t | trt| S t | tr$t| S t	| r,t
| S t|  dt|  d)aZ  Retrieve a matcher function by passing an arbitrary object (PRIVATE).

    Passing a ``TreeElement`` such as a ``Clade`` or ``Tree`` instance returns
    an identity matcher, passing a type such as the ``PhyloXML.Taxonomy`` class
    returns a class matcher, and passing a dictionary returns an attribute
    matcher.

    The resulting 'match' function returns True when given an object matching
    the specification (identity, type or attribute values), otherwise False.
    This is useful for writing functions that search the tree, and probably
    shouldn't be used directly by the end user.
    z (type z%) is not a valid type for comparison.)r   r   r5   rJ   r9   r=   r>   dictrO   callablerU   rR   )objr
   r
   r   _object_matcher   s   



rY   c                    sJ   | s|s|r
t ddd S t|S t| |sS t|  fddS )zMerge target specifications with keyword arguments (PRIVATE).

    Dispatch the components to the various matcher functions, then merge into a
    single boolean function.
    z6you must specify a target object or keyword arguments.c                 S      dS )NTr
   r!   r
   r
   r   r          z#_combine_matchers.<locals>.<lambda>c                    s   | o | S r   r
   r[   match_kwargs	match_objr
   r   r      s    )rR   rO   rY   )r1   rN   require_specr
   r]   r   _combine_matchers   s   ra   c                 G   s:   t | drt| ttttfs|rtd| S t| g|S )zConvert ``[targets]`` or ``*targets`` arguments to a single iterable (PRIVATE).

    This helps other functions work like the built-in functions ``max`` and
    ``min``.
    __iter__zxArguments must be either a single list of targets, or separately specified targets (e.g. foo(t1, t2, t3)), but not both.)	rD   r   r   rV   r=   rJ   rR   	itertoolschain)firstrestr
   r
   r   _combine_args   s   
rg   c                   @   s,   e Zd ZdZdefddZdefddZdS )r   z%Base class for all Bio.Phylo classes.returnc                    s6   dd  d| j jd fddt| j D f S )z<Show this object's constructor with its primitive arguments.c                 S   sH   t |trt|dkr|d d d n|}|  d| dS |  d| S )N<   9   ...z=''=)r   r=   len)r   valr
   r
   r   pair_as_kwarg_string   s   
 z2TreeElement.__repr__.<locals>.pair_as_kwarg_stringz%s(%s)z, c                 3   s<    | ]\}}|d urt |tttttfv r ||V  qd S r   )rJ   r=   rH   floatrG   )r    r   ro   rp   r
   r   r"      s    z'TreeElement.__repr__.<locals>.<genexpr>)	__class____name__joinr#   r$   r%   selfr
   rr   r   __repr__   s   zTreeElement.__repr__c                 C      |   S r   )rx   rv   r
   r
   r   __str__   r3   zTreeElement.__str__N)rt   
__module____qualname____doc__r=   rx   rz   r
   r
   r
   r   r      s    r   c                   @   s   e Zd ZdZdd Zdd Zd3dd	Zd3d
dZd4ddZd5ddZ	d5ddZ
dd Zdd Zdd Zd6ddZd4ddZdd Zdd  Zd4d!d"Zd#d$ Zd%d& Zd4d'd(Zd4d)d*Zd6d+d,Zd4d-d.Zd7d1d2ZdS )8	TreeMixina5  Methods for Tree- and Clade-based classes.

    This lets ``Tree`` and ``Clade`` support the same traversal and searching
    operations without requiring Clade to inherit from Tree, so Clade isn't
    required to have all of Tree's attributes -- just ``root`` (a Clade
    instance) and ``is_terminal``.
    c              	   C   sn   t ttd}z|| }W n ty    td| dt| dw |r(t}| }ndd }| j}t||||S )zPerform a BFS or DFS traversal through all elements in this tree (PRIVATE).

        :returns: generator of all elements for which ``filter_func`` is True.

        )preorder	postorderlevelzInvalid order 'z'; must be one of: Nc                 S      | j S r   cladesr   r
   r
   r   r   #  s    z*TreeMixin._filter_search.<locals>.<lambda>)	r   r   r   KeyErrorrR   tupler,   r   filter)rw   filter_funcorderfollow_attrs
order_opts
order_funcr   r   r
   r
   r   _filter_search  s&   zTreeMixin._filter_searchc                 O   s0   | j |i |}zt|W S  ty   Y dS w )zReturn the first element found by find_elements(), or None.

        This is also useful for checking whether any matching element exists in
        the tree, and can be used in a conditional expression.
        N)find_elementsnextStopIteration)rw   argsrN   hitsr
   r
   r   find_any'  s   
zTreeMixin.find_anyNr   c                 K   s*   |dur||d< t ||d}| ||dS )a  Find all tree elements matching the given attributes.

        The arbitrary keyword arguments indicate the attribute name of the
        sub-element and the value to match: string, integer or boolean. Strings
        are evaluated as regular expression matches; integers are compared
        directly for equality, and booleans evaluate the attribute's truth value
        (True or False) before comparing. To handle nonzero floats, search with
        a boolean argument, then filter the result manually.

        If no keyword arguments are given, then just the class type is used for
        matching.

        The result is an iterable through all matching objects, by depth-first
        search. (Not necessarily the same order as the elements appear in the
        source file!)

        :Parameters:
            target : TreeElement instance, type, dict, or callable
                Specifies the characteristics to search for. (The default,
                TreeElement, matches any standard Bio.Phylo type.)
            terminal : bool
                A boolean value to select for or against terminal nodes (a.k.a.
                leaf nodes). True searches for only terminal nodes, False
                excludes terminal nodes, and the default, None, searches both
                terminal and non-terminal nodes, as well as any tree elements
                lacking the ``is_terminal`` method.
            order : {'preorder', 'postorder', 'level'}
                Tree traversal order: 'preorder' (default) is depth-first
                search, 'postorder' is DFS with child nodes preceding parents,
                and 'level' is breadth-first search.

        Examples
        --------
        >>> from Bio import Phylo
        >>> phx = Phylo.PhyloXMLIO.read('PhyloXML/phyloxml_examples.xml')
        >>> matches = phx.phylogenies[5].find_elements(code='OCTVU')
        >>> next(matches)
        Taxonomy(code='OCTVU', scientific_name='Octopus vulgaris')

        Nr?   FT)ra   r   rw   r1   r?   r   rN   is_matching_elemr
   r
   r   r   3  s   )zTreeMixin.find_elementsc                    s8    fdddu r}nfdd}|  ||dS )a?  Find each clade containing a matching element.

        That is, find each element as with find_elements(), but return the
        corresponding clade object. (This is usually what you want.)

        :returns: an iterable through all matching objects, searching
            depth-first (preorder) by default.

        c                    s,   | j d}| jfi  }|| _|d uS )Nr   )r$   rC   r   r   )r   orig_cladesfound)rN   r1   r
   r   match_attrsl  s   z*TreeMixin.find_clades.<locals>.match_attrsNc                    s   |   ko	 | S r   )r@   r   )r   r?   r
   r   r   v  s   z/TreeMixin.find_clades.<locals>.is_matching_elemF)r   r   r
   )rN   r   r1   r?   r   find_cladesa  s
   zTreeMixin.find_cladesc                    s<   g t ||d fdd  | jsdS ddd S )zList the clades directly between this root and the given target.

        :returns: list of all clade objects along this path, ending with the
            given target, but excluding the root clade.

        Tc                    sH   | r |  dS |  rdS | D ]} |r! |   dS qdS )NTF)r'   r@   )r	   r+   check_in_pathr2   pathr
   r   r     s   

z)TreeMixin.get_path.<locals>.check_in_pathN)ra   r   rw   r1   rN   r
   r   r   get_path{  s   
zTreeMixin.get_pathc                 C      t | jd|dS )z>Get a list of all of this tree's nonterminal (internal) nodes.Fr?   r   r&   r   rw   r   r
   r
   r   get_nonterminals     zTreeMixin.get_nonterminalsc                 C   r   )z7Get a list of all of this tree's terminal (leaf) nodes.Tr   r   r   r
   r
   r   get_terminals  r   zTreeMixin.get_terminalsc                 C   s8   |  ||}||ddd }||}||g | S )zwList of all clade object between two targets in this tree.

        Excluding ``start``, including ``finish``.
        r   Nr   )common_ancestorr   )rw   startfinishmrca	fromstarttor
   r
   r   trace  s   
zTreeMixin.tracec           
         s    fddt |g|R  D }t||D ]\}}|du r$td|dq j}t| D ]}|d }|dd D ]}	||	ur@ nq8|}||urJ |S q,|S )a  Most recent common ancestor (clade) of all the given targets.

        Edge cases:
         - If no target is given, returns self.root
         - If 1 target is given, returns the target
         - If any target is not found in this tree, raises a ValueError

        c                    s   g | ]}  |qS r
   r   )r    trv   r
   r   
<listcomp>  s    z-TreeMixin.common_ancestor.<locals>.<listcomp>Nztarget z is not in this treer      )rg   ziprR   r   )
rw   targetsmore_targetspathspr   r   r   refotherr
   rv   r   r     s$   	zTreeMixin.common_ancestorc                 C      t dd | jddD S )z;Count the number of terminal (leaf) nodes within this tree.c                 s   s    | ]}d V  qdS )r   Nr
   )r    clader
   r
   r   r"     s    z,TreeMixin.count_terminals.<locals>.<genexpr>T)r?   sumr   rv   r
   r
   r   count_terminals     zTreeMixin.count_terminalsFc                    sB   |rdd  ndd  i  fdd| j | j jpd S )a  Create a mapping of tree clades to depths (by branch length).

        :Parameters:
            unit_branch_lengths : bool
                If True, count only the number of branches (levels in the tree).
                By default the distance is the cumulative branch length leading
                to the clade.

        :returns: dict of {clade: depth}, where keys are all of the Clade
            instances in the tree, and values are the distance from the root to
            each clade (including terminals).

        c                 S   rZ   Nr   r
   cr
   r
   r   r     r\   z"TreeMixin.depths.<locals>.<lambda>c                 S   s
   | j pdS r   branch_lengthr   r
   r
   r   r     s   
 c                    s.   || < | j D ]}| | }|| qd S r   r   )r/   
curr_depthr+   	new_depthdepth_ofdepthsupdate_depthsr
   r   r     s
   
z'TreeMixin.depths.<locals>.update_depthsr   )r   r   )rw   unit_branch_lengthsr
   r   r   r     s   
zTreeMixin.depthsc                 C   s@   |du rt dd | |D S | ||}|||| S )zCalculate the sum of the branch lengths between two targets.

        If only one target is specified, the other is the root of this tree.
        Nc                 s   s     | ]}|j d ur|j V  qd S r   r   )r    nr
   r
   r   r"     s    
z%TreeMixin.distance.<locals>.<genexpr>)r   r   r   distance)rw   target1target2r   r
   r
   r   r     s   zTreeMixin.distancec                 C   s   t | tr$t| jdkr$| jjd  o#| jjd  o#| jjd  S t| jdkr;| jjd  o:| jjd  S t| jdkrDdS dS )a#  Return True if tree downstream of node is strictly bifurcating.

        I.e., all nodes have either 2 or 0 children (internal or external,
        respectively). The root may have 3 descendents and still be considered
        part of a bifurcating tree, because it has no ancestor.
           r   r      TF)r   r;   rn   r   r   is_bifurcatingrv   r
   r
   r   r     s   zTreeMixin.is_bifurcatingc                 G   s\   t t|g|R  }| j}	 t | |kr|S |jD ]}t | |r*|} nqdS q)a!  MRCA of terminals if they comprise a complete subclade, or False.

        I.e., there exists a clade such that its terminals are the same set as
        the given targets.

        The given targets must be terminals of the tree.

        To match both ``Bio.Nexus.Trees`` and the other multi-target methods in
        Bio.Phylo, arguments to this method can be specified either of two ways:
        (i) as a single list of targets, or (ii) separately specified targets,
        e.g. is_monophyletic(t1, t2, t3) -- but not both.

        For convenience, this method returns the common ancestor (MCRA) of the
        targets if they are monophyletic (instead of the value True), and False
        otherwise.

        :returns: common ancestor if terminals are monophyletic, otherwise False.

        TF)setrg   r   r   r   
issuperset)rw   	terminalsmore_terminals
target_setcurrentsubclader
   r
   r   is_monophyletic
  s   
zTreeMixin.is_monophyleticc                 K   s   | j |fi |duS )zCheck if target is a descendent of this tree.

        Not required to be a direct descendent.

        To check only direct descendents of a clade, simply use list membership
        testing: ``if subclade in clade: ...``
        Nr   r   r
   r
   r   is_parent_of+  s   zTreeMixin.is_parent_ofc                 C   s.   | j  rdS | j jD ]	}| s dS qdS )z-Check if all direct descendents are terminal.FT)r   r@   r   )rw   r   r
   r
   r   is_preterminal5  s   
zTreeMixin.is_preterminalc                 C   r   )z9Calculate the sum of all the branch lengths in this tree.c                 s   s    | ]}|j V  qd S r   r   )r    r/   r
   r
   r   r"   @  s    z0TreeMixin.total_branch_length.<locals>.<genexpr>Tr   r   rv   r
   r
   r   total_branch_length>  r   zTreeMixin.total_branch_lengthc                 K   s   | j |fi |}|std|p| t|dkr| j}n|d }|j|j|d }|jp1d}|D ]	}| j|7  _q4|j|j |S )zqDelete target from the tree, relinking its children to its parent.

        :returns: the parent clade.

        z!couldn't collapse %s in this treer   r   r   r   )	r   rR   rn   r   r   rC   indexr   r   )rw   r1   rN   r   parentpoppedextra_lengthr+   r
   r
   r   collapseD  s   
zTreeMixin.collapsec                 K   sR   t | j|ddfi |}|sdS |d | jkr|d |D ]}| | qdS )a  Collapse all the descendents of this tree, leaving only terminals.

        Total branch lengths are preserved, i.e. the distance to each terminal
        stays the same.

        For example, this will safely collapse nodes with poor bootstrap
        support:

            >>> from Bio import Phylo
            >>> tree = Phylo.read('PhyloXML/apaf.xml', 'phyloxml')
            >>> print("Total branch length %0.2f" % tree.total_branch_length())
            Total branch length 20.44
            >>> tree.collapse_all(lambda c: c.confidence is not None and c.confidence < 70)
            >>> print("Total branch length %0.2f" % tree.total_branch_length())
            Total branch length 21.37

        This implementation avoids strange side-effects by using level-order
        traversal and testing all clade properties (versus the target
        specification) up front. In particular, if a clade meets the target
        specification in the original tree, it will be collapsed.  For example,
        if the condition is:

            >>> from Bio import Phylo
            >>> tree = Phylo.read('PhyloXML/apaf.xml', 'phyloxml')
            >>> print("Total branch length %0.2f" % tree.total_branch_length())
            Total branch length 20.44
            >>> tree.collapse_all(lambda c: c.branch_length < 0.1)
            >>> print("Total branch length %0.2f" % tree.total_branch_length())
            Total branch length 21.13

        Collapsing a clade's parent node adds the parent's branch length to the
        child, so during the execution of collapse_all, a clade's branch_length
        may increase. In this implementation, clades are collapsed according to
        their properties in the original tree, not the properties when tree
        traversal reaches the clade. (It's easier to debug.) If you want the
        other behavior (incremental testing), modifying the source code of this
        function is straightforward.
        Fr   Nr   )r&   r   r   rC   r   )rw   r1   rN   matchesr   r
   r
   r   collapse_allX  s   (
zTreeMixin.collapse_allc                 C   s4   | j jjdd |d | j jD ]}|j|d qdS )zSort clades in-place according to the number of terminal nodes.

        Deepest clades are last by default. Use ``reverse=True`` to sort clades
        deepest-to-shallowest.
        c                 S   ry   r   )r   r   r
   r
   r   r     r   z%TreeMixin.ladderize.<locals>.<lambda>)r   reverse)r   N)r   r   sort	ladderize)rw   r   r   r
   r
   r   r     s   zTreeMixin.ladderizec           	      K   s  d|v r|d rt d| j|fddi|}|st dt|dkr'| j}n|d }|j|d  t|dkr|| jkrM|jd }d	|_| }| _|S |jd }|jd	ura| j|jp^d
7  _t|dk rk| j}n|d }|j|}|j| |j	|| |}|S )a+  Prunes a terminal clade from the tree.

        If taxon is from a bifurcation, the connecting node will be collapsed
        and its branch length added to remaining terminal node. This might be no
        longer be a meaningful value.

        :returns: parent clade of the pruned target

        r?   ztarget must be terminalTz,can't find a matching target below this rootr   r   r   r   N        r   )
rR   r   rn   r   r   remover   r   rC   insert)	rw   r1   rN   r   r   newrootr+   grandparentr   r
   r
   r   prune  s4   





zTreeMixin.pruner         ?c                 C   sJ   t | j}| jjp
d}t|D ]}||t| |d}| jj| qdS )a  Generate n (default 2) new descendants.

        In a species tree, this is a speciation event.

        New clades have the given branch_length and the same name as this
        clade's root plus an integer suffix (counting from 0). For example,
        splitting a clade named "A" produces sub-clades named "A0" and "A1".
        If the clade has no name, the prefix "n" is used for child nodes, e.g.
        "n0" and "n1".
        r   )r<   r   N)rJ   r   r<   ranger=   r   r'   )rw   r   r   	clade_cls	base_nameir   r
   r
   r   split  s   
zTreeMixin.split)NNr   r   )r   )F)r   r   )rt   r{   r|   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r
   r
   r
   r   r~     s0    


.





!
	


2

,r~   c                   @   s   e Zd ZdZdddZedd Zedd	d
Zedd Z	dd Z
ddddZdd Zdd Zdd ZdddZdefddZdS ) r;   aa  A phylogenetic tree, containing global info for the phylogeny.

    The structure and node-specific data is accessible through the 'root'
    clade attached to the Tree instance.

    :Parameters:
        root : Clade
            The starting node of the tree. If the tree is rooted, this will
            usually be the root node.
        rooted : bool
            Whether or not the tree is rooted. By default, a tree is assumed to
            be rooted.
        id : str
            The identifier of the tree, if there is one.
        name : str
            The name of the tree, in essence a label.

    NTc                 C   s"   |pt  | _|| _|| _|| _dS )z+Initialize parameter for phylogenetic tree.N)r:   r   rootedidr<   )rw   r   r   r   r<   r
   r
   r   __init__  s   
zTree.__init__c                 K   s   t |}| |fi |S )zzCreate a new Tree object given a clade.

        Keyword arguments are the usual ``Tree`` constructor parameters.
        )rB   deepcopy)clsr   rN   r   r
   r
   r   
from_clade  s   
zTree.from_clader   c                 C   s   t |trdd t|D }nt|drt|}ntd|  }|jg}t|t|k r]t	|}|j
|d |j}|rK|D ]}tdt|||_q>|| || t|t|k s,t| t||D ]\}	}
|
|	_qg|S )a/  Create a randomized bifurcating tree given a list of taxa.

        :param taxa: Either an integer specifying the number of taxa to create
            (automatically named taxon#), or an iterable of taxon names, as
            strings.

        :returns: a tree of the same type as this class.

        c                 S   s   g | ]	}d |d  qS )taxonr   r
   )r    r   r
   r
   r   r     s    z#Tree.randomized.<locals>.<listcomp>rb   zBtaxa argument must be integer (# taxa) or iterable of taxon names.r   r   )r   rH   r   rD   r&   rI   r   rn   randomchoicer   r   maxgaussr   r   r   shuffler   r<   )r   taxar   branch_stdevrtreer   newsplitnewtermsntr/   r<   r
   r
   r   
randomized  s.   






zTree.randomizedc                 C   r   )z-Return first clade in this tree (not itself).)r   rv   r
   r
   r   r     s   z
Tree.cladec                 K   s   ddl m} |j| fi |S )zConvert this tree to a PhyloXML-compatible Phylogeny.

        This lets you use the additional annotation types PhyloXML defines, and
        save this information when you write this tree as 'phyloxml'.
        r   )	Phylogeny)Bio.Phylo.PhyloXMLr	  	from_tree)rw   rN   r	  r
   r
   r   as_phyloxml   s   zTree.as_phyloxmloutgroup_branch_lengthc                G   s  | j |g|R  }| |}t|dkrdS |jpd}| s#|dur_|p&d|_| jj| jj|gd}t|dkr<|}n,|d}	|	j|	j	| |	j||j }|	_|j
d|	 |	}n	|}| jj|_|}|ddd D ]}	|	j|	j	| |	j|}|	_|j
d|	 |	}qo| j}
||
jv rt|dksJ |
j|
j	| n
|
j|
j	| t|
dkr|
jd }|jr| j|7  _n||_|j
d| n
||
_|j
d|
 || _d| _dS )	a  Reroot this tree with the outgroup clade containing outgroup_targets.

        Operates in-place.

        Edge cases:
         - If ``outgroup == self.root``, no change
         - If outgroup is terminal, create new bifurcating root node with a
           0-length branch to the outgroup
         - If outgroup is internal, use the given outgroup node as the new
           trifurcating root, keeping branches the same
         - If the original root was bifurcating, drop it from the tree,
           preserving total branch lengths

        :param outgroup_branch_length: length of the branch leading to the
            outgroup after rerooting. If not specified (None), then:

            - If the outgroup is an internal node (not a single terminal taxon),
              then use that node as the new root.
            - Otherwise, create a new root node as the parent of the outgroup.

        r   Nr   )r   r   r   r   r   T)r   r   rn   r   r@   r   rs   rC   r   r   r   r   )rw   outgroup_targetsr  r   outgroupoutgroup_path	prev_blennew_root
new_parentr   old_rootingroupr
   r
   r   root_with_outgroup*  sT   








zTree.root_with_outgroupc                 C   s   d}|   }|D ]#}| | t|   dd d}|d |kr+|}|d }|d }q| | d|| jjp8d  }|dksAJ | |D ]}||j8 }|dk rX|}	| }
 nqFtd| j|	|
d	 d
S )a  Root the tree at the midpoint of the two most distant taxa.

        This operates in-place, leaving a bifurcating root. The topology of the
        tree is otherwise retained, though no guarantees are made about the
        stability of clade/node/taxon ordering.
        r   c                 S   r   r   r
   )ndr
   r
   r   r     r   z'Tree.root_at_midpoint.<locals>.<lambda>r   r   r   g      ?z%Somehow, failed to find the midpoint!r  N)	r   r  r   r   r%   r   r   r   rR   )rw   max_distancetipstipnew_maxtip1tip2root_remainderr/   outgroup_noder  r
   r
   r   root_at_midpoint  s0   



zTree.root_at_midpointc                 C   s
   | j j S )z+Check if the root of this tree is terminal.)r   r   rv   r
   r
   r   r@        
zTree.is_terminalc                 C   sB   |rddl m} ddlm} | }|| g|| | S t| S )a  Serialize the tree as a string in the specified file format.

        This method supports Python's ``format`` built-in function.

        :param format_spec: a lower-case string supported by ``Bio.Phylo.write``
            as an output file format.

        r   )StringIO)_io)ior#  	Bio.Phylor$  writegetvaluer=   )rw   format_specr#  r$  handler
   r
   r   
__format__  s   	zTree.__format__c                 C   s
   |  |S )zSerialize the tree as a string in the specified file format.

        :param fmt: a lower-case string supported by ``Bio.Phylo.write``
            as an output file format.

        )r+  )rw   fmtr
   r
   r   format  s   
zTree.formatrh   c                    s,   d g  fdd| d d S )zReturn a string representation of the entire tree.

        Serialize each sub-clade recursively using ``repr`` to create a summary
        of the object structure.
        z    c                    s   t | ttfrt| }nt| } | |  |d7 }| jD ]&}t| |}t |tr2|| q t |t	rF|D ]}t |trE|| q9q dS )zrRecursively serialize sub-elements.

            This closes over textlines and modifies it in-place.
            r   N)
r   r;   r:   reprr=   r'   r$   rE   r   r&   )rX   indentobjstrattrr+   r   TAB
print_tree	textlinesr
   r   r4    s   






z Tree.__str__.<locals>.print_treer   
)ru   rv   r
   r2  r   rz     s
   

zTree.__str__)NTNN)r   Nr   )rt   r{   r|   r}   r   classmethodr   r  propertyr   r  r  r!  r@   r+  r-  r=   rz   r
   r
   r
   r   r;     s"    

$
_&
r;   c                   @   s   e Zd ZdZ						dddZedd Zdd Zd	d
 Zdd Z	dd Z
dd ZdefddZdd Zdd ZeeeddZdS )r:   a  A recursively defined sub-tree.

    :Parameters:
        branch_length : str
            The length of the branch leading to the root node of this clade.
        name : str
            The clade's name (a label).
        clades : list
            Sub-trees rooted directly under this tree's root.
        confidence : number
            Support.
        color : BranchColor
            The display color of the branch and descendents.
        width : number
            The display width of the branch and descendents.

    Nc                 C   s,   || _ || _|p	g | _|| _|| _|| _dS )z%Define parameters for the Clade tree.N)r   r<   r   
confidencecolorwidth)rw   r   r<   r   r9  r:  r;  r
   r
   r   r   
  s   


zClade.__init__c                 C   s   | S )z4Allow TreeMixin methods to traverse clades properly.r
   rv   r
   r
   r   r     s   z
Clade.rootc                 C   s   | j  S )z(Check if this is a terminal (leaf) node.r   rv   r
   r
   r   r@      s   zClade.is_terminalc                 C   s2   t |ttfr| j| S | }|D ]}|| }q|S )z'Get clades by index (integer or slice).)r   rH   slicer   )rw   r   r   idxr
   r
   r   __getitem__&  s   

zClade.__getitem__c                 C   
   t | jS )zAIterate through this tree's direct descendent clades (sub-trees).)iterr   rv   r
   r
   r   rb   /  r"  zClade.__iter__c                 C   r?  )z4Return the number of clades directly under the root.)rn   r   rv   r
   r
   r   __len__3  r"  zClade.__len__c                 C   rZ   )a  Boolean value of an instance of this class (True).

        NB: If this method is not defined, but ``__len__``  is, then the object
        is considered true if the result of ``__len__()`` is nonzero. We want
        Clade instances to always be considered True.
        Tr
   rv   r
   r
   r   __bool__7  s   zClade.__bool__rh   c                 C   s4   | j rt| j dkr| j dd d S | j S | jjS )z"Return name of the class instance.(   N%   rk   )r<   rn   rs   rt   rv   r
   r
   r   rz   @  s   &zClade.__str__c                 C   r   r   )_colorrv   r
   r
   r   
_get_colorG  s   zClade._get_colorc                 C   s   |d u s	t |tr|| _d S t |tr:|tjv r t|| _d S |dr3t|dkr3t|| _d S t	d| t
|drLt|dkrLt| | _d S t	d| )N#   zinvalid color string rb   r   zinvalid color value )r   BranchColorrE  r=   color_names	from_name
startswithrn   from_hexrR   rD   )rw   argr
   r
   r   
_set_colorJ  s   


zClade._set_colorzBranch color.)doc)NNNNNN)rt   r{   r|   r}   r   r8  r   r@   r>  rb   rA  rB  r=   rz   rF  rO  r:  r
   r
   r
   r   r:     s(    

		r:   c                   @   s*  e Zd ZdZi dddddddddd	d
d	ddddddddddddddddddddddi ddddd dd!d"d#d$d%dd&d'd(d)d*d+d,d+d-d.d/d0d1d2d3d4d5d6d7d8Zd9d: Zed;d< Zed=d> Zd?d@ Z	dAdB Z
dCefdDdEZdCefdFdGZdHS )IrI  a  Indicates the color of a clade when rendered graphically.

    The color should be interpreted by client code (e.g. visualization
    programs) as applying to the whole clade, unless overwritten by the
    color(s) of sub-clades.

    Color values must be integers from 0 to 255.
    red)   r   r   ryellow)rR  rR  r   ygreen)r      r   gcyan)r   rR  rR  r   blue)r   r   rR  bmagenta)rR  r   rR  mblack)r   r   r   kwhite)rR  rR  rR  wmaroon)rW  r   r   olive)rW  rW  r   lime)r   rR  r   aquateal)r   rW  rW  navy)r   r   rW  fuchsiapurple)rW  r   rW  silver)   rk  rk  gray)rW  rW  rW  greypink)rR  rk     salmon)   rW  r   orange)rR     r   gold)rR     r   tan)         brown)rt  *   r|  c                 C   sT   |||fD ]}t |trd|  krdksJ d J dq|| _|| _|| _dS )z"Initialize BranchColor for a tree.r   rR  z0Color values must be integers between 0 and 255.N)r   rH   rQ  rV  rZ  )rw   rQ  rV  rZ  r:  r
   r
   r   r     s   
zBranchColor.__init__c                 C   s\   t |tr|drt|dksJ d|dd |dd |dd f}| dd	 |D  S )
zConstruct a BranchColor object from a hexadecimal string.

        The string format is the same style used in HTML and CSS, such as
        '#FF8000' for an RGB value of (255, 128, 0).
        rG  rH  z.need a 24-bit hexadecimal string, e.g. #000000r   r      Nc                 s   s     | ]}t d | ddV  qdS )0x   )baseN)rH   )r    ccr
   r
   r   r"     s    z'BranchColor.from_hex.<locals>.<genexpr>)r   r=   rL  rn   )r   hexstrRGBr
   r
   r   rM    s   "zBranchColor.from_hexc                 C   s   | | j |  S )z3Construct a BranchColor object by the color's name.)rJ  )r   	colornamer
   r
   r   rK    s   zBranchColor.from_namec                 C   s   d| j d| jd| jdS )aG  Return a 24-bit hexadecimal RGB representation of this color.

        The returned string is suitable for use in HTML/CSS, as a color
        parameter in matplotlib, and perhaps other situations.

        Examples
        --------
        >>> bc = BranchColor(12, 200, 100)
        >>> bc.to_hex()
        '#0cc864'

        rG  02xrQ  rV  rZ  rv   r
   r
   r   to_hex  s   zBranchColor.to_hexc                 C   s   | j | j| jfS )zReturn a tuple of RGB values (0 to 255) representing this color.

        Examples
        --------
        >>> bc = BranchColor(255, 165, 0)
        >>> bc.to_rgb()
        (255, 165, 0)

        r  rv   r
   r
   r   to_rgb  s   
zBranchColor.to_rgbrh   c                 C   s   d| j j| j| j| jf S )z>Preserve the standard RGB order when representing this object.z%s(red=%d, green=%d, blue=%d))rs   rt   rQ  rV  rZ  rv   r
   r
   r   rx     s   zBranchColor.__repr__c                 C   s   d| j | j| jf S )zShow the color's RGB values.z(%d, %d, %d)r  rv   r
   r
   r   rz     s   zBranchColor.__str__N)rt   r{   r|   r}   rJ  r   r7  rM  rK  r  r  r=   rx   rz   r
   r
   r
   r   rI  _  s    		
 !"#$'


	rI  )r}   r   rB   rc   r   rF   r   r   r   r,   r5   r9   r>   rO   rU   rY   ra   rg   r   r~   r;   r:   rI  r
   r
   r
   r   <module>   s8   			
,   S  'h