
    {Ti*                     V   d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
 ddl	mZ dd	l	mZ d
ddddZej                  e       ed   ZdZdZej$                  Zej'                         D ]  \  ZZ eee        d Zd Zd Z G d de      Zd ZddZ G d d      Z G d d      Zy)zLI/O function wrappers for the NeXML file format.

See: http://www.nexml.org
    StringIO)minidom)ElementTree)NeXML   )cdao_elements)cdao_namespaces)resolve_uriz)http://www.w3.org/2001/XMLSchema-instancez$http://www.w3.org/XML/1998/namespacezhttp://www.nexml.org/2009z!http://www.w3.org/2001/XMLSchema#)xsixmlnexxsdr   z0.9z-http://www.nexml.org/2009/nexml/xsd/nexml.xsdc                 &    t        | t        d      S )z*Given a prefixed URI, return the full URI.T)
namespaces	xml_style)r   
NAMESPACESss    D/home/agent/.local/lib/python3.12/site-packages/Bio/Phylo/NeXMLIO.pyqUrir   +   s    qZ4@@    c                 2    dt         | t        d      d     S )zAOptionally converts a CDAO-prefixed URI into an OBO-prefixed URI.zobo:cdao:N)r	   lenr   s    r   cdao_to_obor   0   s     -#g,. 12344r   c                 D    | j                  d      r| t        |       fS | fS )z2Check for matches in both CDAO and OBO namespaces.r   )
startswithr   r   s    r   matchesr   5   s$    ||G;q>""tr   c                       e Zd ZdZy)
NeXMLErrorz@Exception raised when NeXML object construction cannot continue.N)__name__
__module____qualname____doc__ r   r   r!   r!   =   s    Jr   r!   c                 8     t        |       j                  di |S )znIterate over the trees in a NeXML file handle.

    :returns: generator of Bio.Phylo.NeXML.Tree objects.

    r&   )Parserparse)handlekwargss     r   r)   r)   E   s      6&>)&))r   c                 >     t        |       j                  |fd|i|S )zeWrite a trees in NeXML format to the given file handle.

    :returns: number of trees written.

    plain)Writerwrite)treesr*   r-   r+   s       r   r/   r/   N   s%     6%=v=U=f==r   c                   D    e Zd ZdZd Zed        Zd ZddZed        Z	y)	r(   z]Parse a NeXML tree given a file handle.

    Based on the parser in ``Bio.Nexus.Trees``.
    c                     || _         y)z,Initialize parameters for NeXML file parser.N)r*   )selfr*   s     r   __init__zParser.__init__a   s	    r   c                 (    t        |      } | |      S )z'Convert file handle to StringIO object.r   )clstreetextr*   s      r   from_stringzParser.from_stringe   s     (#6{r   c                     d|j                   v r|j                   d   }nd}|t        d      v rt        |j                        |d<   y|j                  ||<   y)z%Add annotations for the NeXML parser.propertymetacdao:has_Support_Value
confidenceN)attribr   floattext)r3   	node_dict	meta_nodeprops       r   add_annotationzParser.add_annotationk   sS    )))##J/DD7344&+INN&;Il#'nnIdOr   c              #     K   t        j                  | j                  d      }|D ]  \  }}|j                  t	        d      k(  s i }i }d}g }	g }
|D ]U  }|j                  t	        d      k(  r|	j                  |       |j                  t	        d      k(  sE|
j                  |       W |	D ]  }|j                  d   }i x}||<   d|j                  v r!|j                  d   r|j                  d   |d	<   d
|j                  v r|j                  d
   dk(  r|}|D ]0  }|j                  t	        d      k(  s| j                  ||   |       2  t               t               |
D ]  }|j                  d   |j                  d   }}j                  |       j                  |       ||vrt               ||<   ||   j                  |       d|j                  v rt        |j                  d         ||   d<   d|j                  v r8|j                  d   t        d      v rt        |j                  d         ||   d<   |D ]0  }|j                  t	        d      k(  s| j                  ||   |       2  |d}fd|	D        }t        |      }nd}t        j                  | j                  |||      |        yw)z7Parse the text stream this object was initialized with.)end)eventsznex:treeNznex:nodeznex:edgeidotunameroottrueznex:metasourcetargetlengthbranch_lengthr:   r<   contentr=   Fc              3      K   | ]5  }|j                   d    v r"|j                   d    vr|j                   d     7 yw)rH   N)r>   ).0nodesrcstarss     r   	<genexpr>zParser.parse.<locals>.<genexpr>   sD      & ;;t,4T9JRV9V D)&s   ;>T)rK   rooted)r   	iterparser*   tagr   appendr>   rD   setaddr?   r   nextr   Tree
_make_tree)r3   values_are_confidencerX   	nexml_doceventrT   rA   node_childrenrK   nodesedgeschildnode_id	this_nodeedgesrctarpossible_rootsrU   rV   s                     @@r   r)   zParser.parsew   s    ))$++hG	$ >	KE4xx4
++	 "! ,EyyD$44U+yyD$44U+	, " 
KD"kk$/G577I	' 2+E0B,0KK,>	&),V1D1N&!% K 99Z(88 //	'0BEJK
K uu! GD#{{84dkk(6KCHHSMHHSM-/-0Uc*!#&**3/4;;.:?H@U:V	#7!T[[0T[[5LPW0Q 6 8=T[[=S7T	#|4!% G 99Z(88 //	#FGG& < #F&$)&N
  /D!Fjjy-HQW y>	s"   AKAKBK6D'KA&Kc                     ||   }t        j                  di |}||v r)||   D cg c]  }| j                  |||       c}|_        |S c c}w )zTraverse the tree creating a nested clade structure (PRIVATE).

        Return a NeXML.Clade, and calls itself recursively for each child,
        traversing the  entire tree and creating a nested structure of NeXML.Clade
        objects.
        r&   )r   Clader`   clades)r6   rT   rA   childrenri   claderg   s          r   r`   zParser._make_tree   s[     dO	(i(8HPQU?Dui:EL 	s   A
N)FF)
r"   r#   r$   r%   r4   classmethodr8   rD   r)   r`   r&   r   r   r(   r(   [   s@    
  

-BH  r   r(   c                   ,    e Zd ZdZd Zd ZddZddZy)	r.   z8Based on the writer in Bio.Nexus.Trees (str, to_string).c                 <    || _         d| _        d| _        d| _        y)z'Initialize parameters for NeXML writer.r   N)r0   node_counteredge_countertree_counter)r3   r0   s     r   r4   zWriter.__init__   s!    
r   c                 `    | d}t        | |t        | |      dz          | t        | |       S )z'Create new labels for the NeXML writer._counterr   )setattrgetattr)r3   obj_typecounters      r   	new_labelzWriter.new_label   s=    Jh'gwtW59:GD'2344r   c           	         || _         t        j                  d      }|j                  dt               |j                  dt
               |j                  dt               t        j                         D ]  \  }}|j                  d| |        t        j                  |dfi ddd	}t        j                  |d
fi dddd}d}	t               }
| j                  D ]h  }t        j                  |dfi d| j                  d      i}|j                  }|
j                  | j                  |||j                               |	dz  }	j |
D ]  }t        j                  |dfi d|i} t        j                   |d      }t#        j$                  |      }	 |j'                  |j)                  d      j+                  d             |	S # t,        $ r% |j'                  |j)                  d             Y |	S w xY w)z-Write this instance's trees to a file handle.z	nex:nexmlversionxmlnszxsi:schemaLocationzxmlns:otustaxRootTaxaBlockrH   labelr0   TreesTreesBlockFromXML)rH   r   r   r   treerH   )rX   r   rI   zutf-8z  )indentutf8)r   r   Elementr\   VERSIONDEFAULT_NAMESPACESCHEMAr   items
SubElementr0   r   rr   update_write_treerX   tostringr   parseStringr/   toprettyxmlencode	TypeError)r3   r*   r   r+   	root_nodeprefixurir   r0   counttusr   	this_treefirst_cladeturI   rough_stringreparseds                     r   r/   zWriter.write   s   &  ''4	i)g01*F3%++- 	2KFCMMF6(+S1	2 %%v
(-!H

 &&
 ':EJ

 eJJ 	D#..v"&v(>!?I **KJJt''Yt{{'STQJE	  	DB((uCr
CC	D #++Iw?&&|4	<LL--T-:AA&IJ
 	  	<LL--T-:;		<s   0G *G43G4Nc                    t               }| j                  rt        nd }| j                  d      }||_        ||d}|xr |du }	|	rd|d<   |j                  r*|j                  |j                         |j                  |d<   t        j                  |dfi |}
|| j                  d      }||j                  |t        |j                         |d	      d
}	 |j                  }||j                   |d      d|dd       	 t        j                  |dfi |}
|j                         s4|j                  D ]%  }|j                  | j                  |||             ' |`|S # t        $ r Y jw xY w)zRecursively process tree, adding nodes and edges to Tree object (PRIVATE).

        Returns a set of all OTUs encountered.
        c                     | S )Nr&   r   s    r   <lambda>z$Writer._write_tree.<locals>.<lambda>#  s    a r   rT   r   NrL   rK   rI   rj   z	cdao:Edge)rH   rM   rN   rO   typeofr<   z	xsd:floatz1.2f)r:   datatyperQ   )parent)r\   r   r   rh   rJ   r]   r   r   strrP   r=   r   AttributeErroris_terminalrp   r   )r3   rr   r   r   rX   r   convert_urirh   r>   rK   rT   edge_idr=   	new_clades                 r   r   zWriter._write_tree  s   
 e%)%5%5kK..('2(&D.#F6N::GGEJJ!JJF5M%%dF=f=nnV,G ..!e112%k2F"--
 )MM(34L(M(3*4T): ))$A&AD  ""\\ L	

4++ItE+JKL M
' " s   E# #	E/.E/)T)NF)r"   r#   r$   r%   r4   r   r/   r   r&   r   r   r.   r.      s    B57r2r   r.   N)F)r%   ior   xml.domr   	xml.etreer   	Bio.Phylor   	_cdao_owlr	   r
   r   r   r   r   r   r   register_namespacer   r   r   r   r   r   	Exceptionr!   r)   r/   r(   r.   r&   r   r   <module>r      s   
   !  $ & " 71&.	
   / "u% 
	8 33 ##% $KFCvs#$A
5
K K*>p pn| |r   