
    wg                        d Z ddlZddlmZ ddlZddlmZ g dZ edd      	 	 	 	 	 dd       Z	 edd      	 	 	 	 	 dd       Z
	 	 	 	 ddZ edd       ej                  dd	      eed
fd              Z ej                  dd	      eed
fd       Z G d d      Z G d de      Z G d d      Z G d de      Ze
Z G d de      Zy)aH  
*******
GraphML
*******
Read and write graphs in GraphML format.

.. warning::

    This parser uses the standard xml library present in Python, which is
    insecure - see :external+python:mod:`xml` for additional information.
    Only parse GraphML files you trust.

This implementation does not support mixed graphs (directed and unidirected
edges together), hyperedges, nested graphs, or ports.

"GraphML is a comprehensive and easy-to-use file format for graphs. It
consists of a language core to describe the structural properties of a
graph and a flexible extension mechanism to add application-specific
data. Its main features include support of

    * directed, undirected, and mixed graphs,
    * hypergraphs,
    * hierarchical graphs,
    * graphical representations,
    * references to external data,
    * application-specific attribute data, and
    * light-weight parsers.

Unlike many other file formats for graphs, GraphML does not use a
custom syntax. Instead, it is based on XML and hence ideally suited as
a common denominator for all kinds of services generating, archiving,
or processing graphs."

http://graphml.graphdrawing.org/

Format
------
GraphML is an XML format.  See
http://graphml.graphdrawing.org/specification.html for the specification and
http://graphml.graphdrawing.org/primer/graphml-primer.html
for examples.
    N)defaultdict)	open_file)write_graphmlread_graphmlgenerate_graphmlwrite_graphml_xmlwrite_graphml_lxmlparse_graphmlGraphMLWriterGraphMLReader   wb)modeTFc                 h    t        |||||      }|j                  |        |j                  |       y)a  Write G in GraphML XML format to path

    Parameters
    ----------
    G : graph
       A networkx graph
    path : file or string
       File or filename to write.
       Filenames ending in .gz or .bz2 will be compressed.
    encoding : string (optional)
       Encoding for text data.
    prettyprint : bool (optional)
       If True use line breaks and indenting in output XML.
    infer_numeric_types : boolean
       Determine if numeric types should be generalized.
       For example, if edges have both int and float 'weight' attributes,
       we infer in GraphML that both are floats.
    named_key_ids : bool (optional)
       If True use attr.name as value for key elements' id attribute.
    edge_id_from_attribute : dict key (optional)
        If provided, the graphml edge id is set by looking up the corresponding
        edge data attribute keyed by this parameter. If `None` or the key does not exist in edge data,
        the edge id is set by the edge key if `G` is a MultiGraph, else the edge id is left unset.

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> nx.write_graphml(G, "test.graphml")

    Notes
    -----
    This implementation does not support mixed graphs (directed
    and unidirected edges together) hyperedges, nested graphs, or ports.
    )encodingprettyprintinfer_numeric_typesnamed_key_idsedge_id_from_attributeN)r   add_graph_elementdump)Gpathr   r   r   r   r   writers           _/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/networkx/readwrite/graphml.pyr   r   >   s:    X /#5F Q
KK    c           
          	 ddl m} t	        || |||||      }|j                          y# t        $ r t        | ||||||      cY S w xY w)a  Write G in GraphML XML format to path

    This function uses the LXML framework and should be faster than
    the version using the xml library.

    Parameters
    ----------
    G : graph
       A networkx graph
    path : file or string
       File or filename to write.
       Filenames ending in .gz or .bz2 will be compressed.
    encoding : string (optional)
       Encoding for text data.
    prettyprint : bool (optional)
       If True use line breaks and indenting in output XML.
    infer_numeric_types : boolean
       Determine if numeric types should be generalized.
       For example, if edges have both int and float 'weight' attributes,
       we infer in GraphML that both are floats.
    named_key_ids : bool (optional)
       If True use attr.name as value for key elements' id attribute.
    edge_id_from_attribute : dict key (optional)
        If provided, the graphml edge id is set by looking up the corresponding
        edge data attribute keyed by this parameter. If `None` or the key does not exist in edge data,
        the edge id is set by the edge key if `G` is a MultiGraph, else the edge id is left unset.

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> nx.write_graphml_lxml(G, "fourpath.graphml")

    Notes
    -----
    This implementation does not support mixed graphs (directed
    and unidirected edges together) hyperedges, nested graphs, or ports.
    r   N)graphr   r   r   r   r   )
lxml.etreeetreeImportErrorr   GraphMLWriterLxmlr   )	r   r   r   r   r   r   r   	lxmletreer   s	            r   r	   r	   u   sj    ^
& /#5F KKM)  	
 "
 	
	
s   + AAc              #      K   t        ||||      }|j                  |        t        |      j                         E d{    y7 w)aB  Generate GraphML lines for G

    Parameters
    ----------
    G : graph
       A networkx graph
    encoding : string (optional)
       Encoding for text data.
    prettyprint : bool (optional)
       If True use line breaks and indenting in output XML.
    named_key_ids : bool (optional)
       If True use attr.name as value for key elements' id attribute.
    edge_id_from_attribute : dict key (optional)
        If provided, the graphml edge id is set by looking up the corresponding
        edge data attribute keyed by this parameter. If `None` or the key does not exist in edge data,
        the edge id is set by the edge key if `G` is a MultiGraph, else the edge id is left unset.

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> linefeed = chr(10)  # linefeed = 

    >>> s = linefeed.join(nx.generate_graphml(G))
    >>> for line in nx.generate_graphml(G):  # doctest: +SKIP
    ...     print(line)

    Notes
    -----
    This implementation does not support mixed graphs (directed and unidirected
    edges together) hyperedges, nested graphs, or ports.
    )r   r   r   r   N)r   r   str
splitlines)r   r   r   r   r   r   s         r   r   r      sE     J #5	F Q6{%%'''s   =AA Arb)graphsreturns_graphc                 :   t        |||      }t         ||             }t        |      dk(  rjd}| j                  d       | j	                         }|j                  d|      }t         ||            }t        |      dk(  rt        j                  d      |d   S )a  Read graph in GraphML format from path.

    Parameters
    ----------
    path : file or string
       File or filename to write.
       Filenames ending in .gz or .bz2 will be compressed.

    node_type: Python type (default: str)
       Convert node ids to this type

    edge_key_type: Python type (default: int)
       Convert graphml edge ids to this type. Multigraphs use id as edge key.
       Non-multigraphs add to edge attribute dict with name "id".

    force_multigraph : bool (default: False)
       If True, return a multigraph with edge keys. If False (the default)
       return a multigraph when multiedges are in the graph.

    Returns
    -------
    graph: NetworkX graph
        If parallel edges are present or `force_multigraph=True` then
        a MultiGraph or MultiDiGraph is returned. Otherwise a Graph/DiGraph.
        The returned graph is directed if the file indicates it should be.

    Notes
    -----
    Default node and edge attributes are not propagated to each node and edge.
    They can be obtained from `G.graph` and applied to node and edge attributes
    if desired using something like this:

    >>> default_color = G.graph["node_default"]["color"]  # doctest: +SKIP
    >>> for node, data in G.nodes(data=True):  # doctest: +SKIP
    ...     if "color" not in data:
    ...         data["color"] = default_color
    >>> default_color = G.graph["edge_default"]["color"]  # doctest: +SKIP
    >>> for u, v, data in G.edges(data=True):  # doctest: +SKIP
    ...     if "color" not in data:
    ...         data["color"] = default_color

    This implementation does not support mixed graphs (directed and unidirected
    edges together), hypergraphs, nested graphs, or ports.

    For multigraphs the GraphML edge "id" will be used as the edge
    key.  If not specified then they "key" attribute will be used.  If
    there is no "key" attribute a default NetworkX multigraph edge key
    will be provided.

    Files with the yEd "yfiles" extension can be read. The type of the node's
    shape is preserved in the `shape_type` node attribute.

    yEd compressed files ("file.graphmlz" extension) can be read by renaming
    the file to "file.graphml.gz".

    )r   r   s7   <graphml xmlns="http://graphml.graphdrawing.org/xmlns">s	   <graphml>string%file not successfully read as graphml)r   listlenseekreadreplacenxNetworkXError)	r   	node_typeedge_key_typeforce_multigraphreaderglistheader	old_bytes	new_bytess	            r   r   r      s    v 9m5EFFT"#E
5zQK		!IIK	%%lF;	V9-.u:?""#JKK8Or   c                     t        |||      }t         ||             }t        |      dk(  rId}| j                  d|      }t         ||            }t        |      dk(  rt	        j
                  d      |d   S )a   Read graph in GraphML format from string.

    Parameters
    ----------
    graphml_string : string
       String containing graphml information
       (e.g., contents of a graphml file).

    node_type: Python type (default: str)
       Convert node ids to this type

    edge_key_type: Python type (default: int)
       Convert graphml edge ids to this type. Multigraphs use id as edge key.
       Non-multigraphs add to edge attribute dict with name "id".

    force_multigraph : bool (default: False)
       If True, return a multigraph with edge keys. If False (the default)
       return a multigraph when multiedges are in the graph.


    Returns
    -------
    graph: NetworkX graph
        If no parallel edges are found a Graph or DiGraph is returned.
        Otherwise a MultiGraph or MultiDiGraph is returned.

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> linefeed = chr(10)  # linefeed = 

    >>> s = linefeed.join(nx.generate_graphml(G))
    >>> H = nx.parse_graphml(s)

    Notes
    -----
    Default node and edge attributes are not propagated to each node and edge.
    They can be obtained from `G.graph` and applied to node and edge attributes
    if desired using something like this:

    >>> default_color = G.graph["node_default"]["color"]  # doctest: +SKIP
    >>> for node, data in G.nodes(data=True):  # doctest: +SKIP
    ...     if "color" not in data:
    ...         data["color"] = default_color
    >>> default_color = G.graph["edge_default"]["color"]  # doctest: +SKIP
    >>> for u, v, data in G.edges(data=True):  # doctest: +SKIP
    ...     if "color" not in data:
    ...         data["color"] = default_color

    This implementation does not support mixed graphs (directed and unidirected
    edges together), hypergraphs, nested graphs, or ports.

    For multigraphs the GraphML edge "id" will be used as the edge
    key.  If not specified then they "key" attribute will be used.  If
    there is no "key" attribute a default NetworkX multigraph edge key
    will be provided.

    r+   r   z7<graphml xmlns="http://graphml.graphdrawing.org/xmlns">z	<graphml>r-   )r   r.   r/   r2   r3   r4   )graphml_stringr5   r6   r7   r8   r9   r:   
new_strings           r   r
   r
   6  sz    z 9m5EFF~./E
5zQJ#++K@
V:./u:?""#JKK8Or   c                   \    e Zd ZdZdZdZdj                  ddg      Zd Zddddddd	Z	d
 Z
y)GraphMLz%http://graphml.graphdrawing.org/xmlnsz)http://www.w3.org/2001/XMLSchema-instancez!http://www.yworks.com/xml/graphml z5http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsdc                 n   t         dft        dft        dft         dft         dft        dft        dft        dfg}	 d	d l}|j
                  df|j                  df|j                  df|j                  df|j                  df|j                  df|j                  df|j                  df|j                  df|j                  df|j                  df|j                   df|j                  df|j"                  df|j$                  dfg|z   }t'        |      | _        t'        d
 |D              | _        y #  Y ,xY w)Nintegeryfilesr,   intlongfloatdoublebooleanr   c              3   2   K   | ]  }t        |        y wN)reversed).0as     r   	<genexpr>z*GraphML.construct_types.<locals>.<genexpr>  s     ;;s   )rF   r%   rH   boolnumpyfloat64float32float16int_int8int16int32int64uint8uint16uint32uint64intcintpdictxml_typepython_type)selftypesnps      r   construct_typeszGraphML.construct_types  s>   )(O(O%L&MGH9	
	 W%W%W%% % 5!5!5!5!E"E"E"% % %   !E$ U;U;;/	s   D0 0D4TF)truefalse0r   1r   c                 d    	 | j                   |   S # t        $ r}t        d| d      |d}~ww xY w)zWrapper around the xml_type dict that raises a more informative
        exception message when a user attempts to use data of a type not
        supported by GraphML.zGraphML does not support type  as data values.N)rb   KeyError	TypeError)rd   keyerrs      r   get_xml_typezGraphML.get_xml_type  sC    	==%% 	05EF	s    	/*/N)__name__
__module____qualname__
NS_GRAPHMLNS_XSINS_YjoinSCHEMALOCATIONrg   convert_boolrr    r   r   rA   rA     sP    8J8F.DXX3C	
N&<\ 	L	r   rA   c                   f    e Zd Z	 	 	 	 	 	 ddZd Zd Zd ZddZd Zd Z	d	 Z
d
 Zd Zd ZddZy)r   Nc                 |   | j                          ddlm} || _        || _        || _        || _        || _        || _        | j                  d| j                  | j                  | j                  d      | _        i | _        t        t              | _        t        t"              | _        || j'                  |       y y )Nr   )Elementgraphmlxmlnsz	xmlns:xsizxsi:schemaLocation)rg   xml.etree.ElementTreer   	myElementr   r   r   r   r   rv   rw   rz   xmlkeysr   r.   
attributessetattribute_typesr   )rd   r   r   r   r   r   r   r   s           r   __init__zGraphMLWriter.__init__  s     	1 #6 &*&<# >>![[&*&9&9
 	%d+*3/""5) r   c                     ddl m} | j                  r| j                  | j                          || j                        j                  | j                        }|S )Nr   )tostring)r   r   r   indentr   decoder   )rd   r   ss      r   __str__zGraphMLWriter.__str__  s@    2KK!TXX%%dmm4r   c                    | j                   ri| j                  ||f   }t        |      dkD  r<|D ch c]  }| j                  |       }}d|v rt        S d|v sd|v rt
        S t        S t        |      d   S t        |      S c c}w )a  Infer the attribute type of data named name. Currently this only
        supports inference of numeric types.

        If self.infer_numeric_types is false, type is used. Otherwise, pick the
        most general of types found across all values with name and scope. This
        means edges with data named 'weight' are treated separately from nodes
        with data named 'weight'.
        r   r,   rH   rI   r   )	r   r   r/   rr   r%   rH   rF   r.   type)rd   namescopevaluere   ts         r   	attr_typezGraphMLWriter.attr_type  s     ##(($7E5zA~7<=!**1-==u$J%U): LJE{1~%; >s   Bc                    |||f}	 | j                   |   S # t        $ r | j                  r|}n!dt        t	        | j                                }|| j                   |<   ||||d} | j
                  di |}|2| j                  d      }	t        |      |	_        |j                  |	       | j                  j                  d|       Y |S w xY w)Nd)idfor	attr.name	attr.typedefaultr   rp   )r   rn   r   r/   r.   r   r%   textappendr   insert)
rd   r   r   r   r   keys_keynew_id
key_kwargskey_elementdefault_elements
             r   get_keyzGraphMLWriter.get_key  s    )U+	,99X&& 	,!!Sdii123"(DIIh!&	J )$..=*=K""&..";'*7|$""?3HHOOA{+)	,s    B1C
Cc                     || j                   vrt        j                  d| d      | j                  || j	                  |      ||      }| j                  d|      }t        |      |_        |S )zn
        Make a data element for an edge or a node. Keep a log of the
        type in the keys table.
        z GraphML writer does not support rm   datar   )rb   r3   r4   r   rr   r   r%   r   )rd   r   element_typer   r   r   keyiddata_elements           r   add_datazGraphMLWriter.add_data-  su    
 t}},""2<.@PQ  T4#4#4\#BE7S~~f%~8Jr   c           	          |j                         D ]h  \  }}| j                  t        |      |f   j                  t	        |             | j
                  |   j                  ||||j                  |      g       j y)zAppends attribute data to edges or nodes, and stores type information
        to be added later. See add_graph_element.
        N)itemsr   r%   addr   r   r   get)rd   r   xml_objr   r   kvs          r   add_attributeszGraphMLWriter.add_attributes;  sl     JJL 	KDAq  #a&%155d1g>OOG$++Q5'++a.,IJ	Kr   c                     |j                   j                  di       }|j                  d      D ]F  \  }}| j                  dt	        |            }| j                  d|||       |j                  |       H y )Nnode_defaultTr   node)r   )r   r   nodesr   r%   r   r   )rd   r   graph_elementr   r   r   node_elements          r   	add_nodeszGraphMLWriter.add_nodesC  sl    ''++nb1''t', 	/JD$>>&SY>?LdGD  .	/r   c                    |j                         r|j                  dd      D ]  \  }}}}| j                  dt        |      t        |      | j                  r2| j                  |v r$t        |j                  | j                              n
t        |            }|j                  j                  di       }| j                  d|||       |j                  |        y |j                  d      D ]  \  }}}| j                  rX| j                  |v rJ| j                  dt        |      t        |      t        |j                  | j                                    }n&| j                  dt        |      t        |            }|j                  j                  di       }| j                  d|||       |j                  |        y )NT)r   r   edge)sourcetargetr   edge_defaultr   )r   r   )	is_multigraphedgesr   r%   r   r   r   r   r   )	rd   r   r   ur   rp   r   edge_elementr   s	            r   	add_edgeszGraphMLWriter.add_edgesJ  s   ??#$7747#@ 31c4#~~q6q62233t; 488D$?$?@A S  .   ''++nb9##FL$H$$\23  gg4g0 3
1d..43N3NRV3V#'>>"1v"1vtxx(C(CDE	 $2 $L $(>>&QPSTUPV>#WL''++nb9##FL$H$$\23r   c                    |j                         rd}nd}|j                  j                  dd      }|| j                  d|      }n| j                  d||      }i }|j                  j	                         D ci c]  \  }}|dvr|| }}}| j                  d|||       | j                  ||       | j                  ||       | j                  j	                         D ]X  \  }	}|D ]N  \  }}}
}|	j                  | j                  t        |      | j                  ||
|      t        |      |
|             P Z | j                  j                  |       yc c}}w )	=
        Serialize graph G in GraphML to the stream.
        directed
undirectedr   Nr   edgedefaultr   r   r   r   )is_directedr   popr   r   r   r   r   r   r   r   r%   r   r   )rd   r   default_edge_typegraphidr   r   r   r   r   r   r   s              r   r   zGraphMLWriter.add_graph_elementj  s\    ==? * ,''++dD)? NN7@QNRM NN%67 + M  ''--/
A88 qD
 

 	G]D'Bq-(q-( "__224 	MGT(, $1eWMMAq% ;SVUG	 	&)
s   ;Ec                 4    |D ]  }| j                  |        y)z)Add many graphs to this GraphML document.N)r   )rd   
graph_listr   s      r   
add_graphszGraphMLWriter.add_graphs  s     	&A""1%	&r   c                     ddl m} | j                  r| j                  | j                          || j                        }|j                  || j                  d       y )Nr   )ElementTreeT)r   xml_declaration)r   r   r   r   r   writer   )rd   streamr   documents       r   r   zGraphMLWriter.dump  sB    5KK!txx(vtLr   c                    d|dz  z   }t        |      r|j                  r|j                  j                         s
|dz   |_        |j                  r|j                  j                         s||_        |D ]  }| j	                  ||dz           |j                  r|j                  j                         s||_        y y |r/|j                  r|j                  j                         s||_        y y y )N
z  r   )r/   r   striptailr   )rd   elemlevelis       r   r   zGraphMLWriter.indent  s    54<t999DIIOO$5H	99DIIOO$5	 -D%!),-99DIIOO$5	 %6 diityy/@	 0Aur   Nutf-8TFFN)allN)r   )rs   rt   ru   r   r   r   r   r   r   r   r   r   r   r   r   r|   r   r   r   r     sW     !# *D24K/3@%'N&
Mr   r   c                       e Zd ZdZd Zd Zy)IncrementalElementzWrapper for _IncrementalWriter providing an Element like interface.

    This wrapper does not intend to be a complete implementation but rather to
    deal with those calls used in GraphMLWriter.
    c                      || _         || _        y rL   )r   r   )rd   r   r   s      r   r   zIncrementalElement.__init__  s    &r   c                 R    | j                   j                  || j                         y )Npretty_print)r   r   r   )rd   elements     r   r   zIncrementalElement.append  s    wT-=-=>r   N)rs   rt   ru   __doc__r   r   r|   r   r   r   r     s    '?r   r   c                   :    e Zd Z	 	 	 	 	 	 ddZd Zd Zd ZddZy)	r"   Nc                    | j                          dd lm} |j                  | _        || _        || _        || _        || _        || _	        |j                  ||      | _        | j                  j                         | _        | j                  j                          g | _        | j                  | _        | j                  j#                  d| j$                  | j&                  | j(                  d      | _        | j*                  j                          i | _        t/        t0              | _        || j5                  |       y y )Nr   )r   r   r   )rg   r   r    r   r   	_encoding_prettyprintr   r   r   xmlfile	_xml_base	__enter___xmlwrite_declarationr   _keysr   rv   rw   rz   _graphmlr   r   r   r   r   )	rd   r   r   r   r   r   r   r   r#   s	            r   r   zGraphMLWriterLxml.__init__  s
    	&"**!'*&<##6 "**4(*CNN,,.			##% XX
		))![[&*&9&9
 	!	*3/""5) r   c           
      	   |j                         rd}nd}|j                  j                  dd      }|| j                  j	                  d|      }n| j                  j	                  d||      }|j                  j                         D ci c]  \  }}|dvr|| }}}|j                  j                  d	i       }|j                  j                  d
i       }	|j                         D ]7  \  }}| j                  t        |      df   j                  t        |             9 |j                         D ]D  \  }}| j                  | j                  |d|            }
| j                  t        |      |
dd       F |j                  d      D ]O  \  }}|j                         D ]7  \  }}| j                  t        |      df   j                  t        |             9 Q |j                  d      D ]k  \  }}|j                         D ]S  \  }}| j                  | j                  |d|            }| j                  t        |      |d|j                  |             U m |j                         r|j!                  dd      D ]Q  \  }}}}|j                         D ]7  \  }}| j                  t        |      df   j                  t        |             9 S |j!                  dd      D ]m  \  }}}}|j                         D ]S  \  }}| j                  | j                  |d|            }| j                  t        |      |d|	j                  |             U o n|j!                  d      D ]P  \  }}}|j                         D ]7  \  }}| j                  t        |      df   j                  t        |             9 R |j!                  d      D ]l  \  }}}|j                         D ]S  \  }}| j                  | j                  |d|            }| j                  t        |      |d|	j                  |             U n | j"                  D ])  }| j                  j%                  || j&                         + t)        | j                  | j&                        }|5  | j+                  d||i        | j-                  ||       | j/                  ||       ddd       yc c}}w # 1 sw Y   yxY w)r   r   r   r   Nr   r   r   r   r   r   Tr   r   )r   r   r   r   )r   r   r   r   r   r   r   r   r%   r   r   rr   r   r   r   r   r   r   r   r   r   r   r   r   )rd   r   r   r   r   r   r   	graphdatar   r   r   r   r   Tr   ekeyrp   incremental_writers                     r   r   z#GraphMLWriterLxml.add_graph_element  s    ==? * ,''++dD)? II--gCT-UM II--%67 . M 
188 qD
	 

 ww{{>26ww{{>26OO% 	ADAq  #a&'!2377Q@	AOO% 	>DAq,,T^^Aw-JKLLLQw=	> wwDw) 	DGD!	 D1$$c!ff%56::47CD	D wwDw) 	EGD!	 E1%%dnnQ&BCSVQ0@0@0CDE	E
 ??!"d!> H1dAGGI HDAq((#a&&)9:>>tAwGHH "#d!> I1dAGGI IDAq))$..FA*FGALLQFL4D4DQ4GHII
 777- H1aGGI HDAq((#a&&)9:>>tAwGHH 777- I1aGGI IDAq))$..FA*FGALLQFL4D4DQ4GHII 88 	ACIIOOCd.?.?O@	A 0		4;L;LM 	2);YKNN101NN101	2 	2[
Z	2 	2s   S9S!!S*c           
          |j                         D ]f  \  }}| j                  t        |      | j                  t        |      ||      t        |      ||j	                  |            }|j                  |       h y)zAppends attribute data.N)r   r   r%   r   r   r   )rd   r   r   r   r   r   r   r   s           r   r   z GraphMLWriterLxml.add_attributes3  sd    JJL 	)DAq==As1vua8#a&%UVL NN<(		)r   c                 ,    t         j                  |       S rL   )objectr   )rd   s    r   r   zGraphMLWriterLxml.__str__;  s    ~~d##r   c                 x    | j                   j                  d d d        | j                  j                  d d d        y rL   )r   __exit__r   )rd   r   s     r   r   zGraphMLWriterLxml.dump>  s.    tT40dD1r   r   rL   )rs   rt   ru   r   r   r   r   r   r|   r   r   r"   r"     s2     !#,*\D2L)$2r   r"   c                   F    e Zd ZdZeedfdZddZddZd Z	d Z
d	 Zd
 Zy)r   z:Read a GraphML document.  Produces NetworkX graph objects.Fc                 \    | j                          || _        || _        || _        i | _        y rL   )rg   r5   r6   
multigraphedge_ids)rd   r5   r6   r7   s       r   r   zGraphMLReader.__init__J  s+    "**r   Nc              #   6  K   ddl m}m} | ||      | _        n| ||      | _        nt	        d      | j                  | j                        \  }}| j                  j                  d| j                   d      D ]  }| j                  |||        y w)Nr   )r   
fromstring)filez/Must specify either 'path' or 'string' as kwarg{}graph)	r   r   r
  r   
ValueErrorfind_graphml_keysfindallrv   
make_graph)rd   r   r,   r   r
  r   defaultsgs           r   __call__zGraphMLReader.__call__Q  s     A"-DH!&)DHNOO11$((;x!!Bt&7w"?@ 	5A//!T844	5s   BBc                 L   |j                  dd       }|.|dk(  rt        j                         }nt        j                         }i |j                  d<   i |j                  d<   |j                         D ]t  \  }}||   d   }||   d   }	||   d   }
|dk(  r&|j                  d   j                  |	 |
|      i       |d	k(  sO|j                  d   j                  |	 |
|      i       v |j                  d
| j                   d      }|t        j                  d      |j                  d
| j                   d      D ]  }| j                  ||||        |j                  d
| j                   d      D ]  }| j                  |||        | j                  ||      }|j                  j                  |       | j                  r|S |j                         rt        j                   |      nt        j"                  |      }t        j$                  || j&                  d       |S )Nr   r   r   r   r   r   r   r   r   r  z
}hyperedgez)GraphML reader doesn't support hyperedgesz}nodez}edger   )valuesr   )r   r3   MultiDiGraph
MultiGraphr   r   updatefindrv   r4   r  add_nodeadd_edgedecode_data_elementsr  r   DiGraphGraphset_edge_attributesr  )rd   	graph_xmlgraphml_keysr  r   r   key_idr   key_forr   rc   	hyperedgenode_xmledge_xmlr   s                  r   r  zGraphMLReader.make_graph^  s   mmM489j(OO%MMO"$"$%^^- 	KMFE"6*51G'/D&v.v6K& '..k%6H/IJ& '..k%6H/IJ	K NNR'8#DE	 ""#NOO!))Bt.?v*FG 	?HMM!X|X>	? "))Bt.?v*FG 	5HMM!X|4	5 ((yA	t ??H]]_BJJqM"((1+
qTBr   c                    |j                  d| j                   d      }|t        j                  d       | j	                  |j                  d            }| j                  ||      } |j                  |fi | |j                  j                  d      dk(  r4|j                  d| j                   d      }| j                  ||||       yy)	zAdd a node to the graph.r  }portNGraphML port tag not supported.r   zyfiles.foldertypegroupr  )
r  rv   warningswarnr5   r   r  r  attribr  )	rd   r   r&  r"  r  portsnode_idr   r!  s	            r   r  zGraphMLReader.add_node  s     4??"36:;MM;<..d!34((x@

7#d#??23w> 4??*;7&CDIOOI|XqA ?r   c                    |j                  d| j                   d      }|t        j                  d       |j	                  d      }|j                         r|dk(  rd}t        j                  |      |j                         s|dk(  rd	}t        j                  |      | j                  |j	                  d
            }| j                  |j	                  d            }| j                  ||      }	|j	                  d      }
|
r$|
| j                  ||f<   	 | j                  |
      }
n|	j	                  d      }
|j                  ||      rd| _        |j                  |||
|	fg       y# t        $ r Y ;w xY w)zAdd an edge to the graph.r  r)  Nr*  r   ri   z,directed=false edge found in directed graph.rh   z-directed=true edge found in undirected graph.r   r   r   rp   T)r  rv   r,  r-  r   r   r3   r4   r5   r  r  r6   r  has_edger  add_edges_from)rd   r   r   r"  r/  r   msgr   r   r   edge_ids              r   r  zGraphMLReader.add_edge  sg    !!Bt&7v">?MM;<  ##J/==?x72@C""3''X%7AC""3'' 0 0 :; 0 0 :;((|D ""4(,3DMM&&.),,W5 hhuoG::ff%"DO 	
667D9:;  s   E* *	E65E6c           	      j   i }|j                  d| j                   d      D ]  }|j                  d      }	 ||   d   }||   d   }|j                  }	|	Mt        t        |            dk(  r6|t        k(  r!| j                  |	j                            ||<   u ||	      ||<   t        t        |            dkD  rBd}
|j                  d| j                   d	      }||j                  d
      |d<   dD ]  }d| j                   d| d| j                   d}|j                  | d      }|(|j                  d      |d<   |j                  d      |d<   |
|j                  | d      }
|j                  | d      }||j                  d      |d<    |
|
j                  |d<   dD ]:  }d| j                   d| d| j                   d}|j                  | d      }|: n |j                  |d<   |	d||<    |S # t        $ r}t	        j
                  d|       |d}~ww xY w)z:Use the key information to decode the data XML if present.r  z}datarp   r   r   zBad GraphML data: no key Nr   z}GenericNodeconfiguration
shape_type)GenericNode	ShapeNodeSVGNode	ImageNode}z/{Geometryxy	NodeLabelShapelabel)PolyLineEdge
SplineEdgeQuadCurveEdge
BezierEdgeArcEdge	EdgeLabel )r  rv   r   rn   r3   r4   r   r/   r.   rQ   r{   lowerr  rx   )rd   r"  obj_xmlr   r   rp   	data_name	data_typerq   r   
node_labelgnr5   prefgeometryshape	edge_type
edge_labels                     r   r  z"GraphMLReader.decode_data_elements  s   #OOb0A,HI 5	%L""5)CS(-f5	(-f5	  $$DC\(:$;q$@$ '+&7&7

&EDO&/oDOT,'(1,!
!&&DII;m'DE>)+)@D&!U 
?I		{"YKs499+RHD+00D61BCH+$,LL$5S	$,LL$5S	!)%1%6%6$y7I%J
(--en=E(-2YYv->\*
? )$.OODM" 
I  		{"YKs499+RHD!-!2!2dV93E!FJ!-
 )$.OODM"$Yk5	%l c  S&&)B3%'HIsRSs   H	H2H--H2c                    i }i }|j                  d| j                   d      D ]  }|j                  d      }|j                  d      }|j                  d      }|j                  d      }||}d}|d}t        j                  d	| d
       |t        j                  d| d      || j                  |   |j                  d      d||<   |j                  d| j                   d      }	|	||   d   }
|
t        k(  r,| j                  |	j                  j                            ||<   
 |
|	j                        ||<   ! ||fS )z4Extracts all the keys and key defaults from the xml.r  z}keyr   r   r   zyfiles.typerE   r,   zNo key type for id z. Using stringzUnknown key for id .r   )r   r   r   z}defaultr   )r  rv   r   r,  r-  r3   r4   rc   r  rQ   r{   r   rK  )rd   r   r"  graphml_key_defaultsr   attr_idr   	attr_nameyfiles_typer   rc   s              r   r  zGraphMLReader.find_graphml_keys  sn   !&&DOO+<E'BC 	NAeeDkGk*Ik*I%%.K&'	$	 $	 3G9NKL &&)<WIQ'GHH!((3uuU|%L! ffr$//!2)<=G"*73F;$&484E4E**,5(1 5@4M(19	N: 111r   )NNrL   )rs   rt   ru   r   r%   rF   r   r  r  r  r  r  r  r|   r   r   r   r   G  s3    D!$C% 5(TB '<R9v!2r   r   )r   TFFN)r   TFN)r   r,  collectionsr   networkxr3   networkx.utilsr   __all__r   r	   r   _dispatchabler%   rF   r   r
   rA   r   r   r"   r   r   r|   r   r   <module>ra     sC  )V  #  $	 14 3 3l 14 D DR ,(^ 14T2!$C% E 3 EP T2!uF 3FRL L^]G ]@? ?B2 B2L #V2G V2r   