o
    3ήc+                     @   s   d Z g dZddlZddlmZmZ eddddddZeddddZ	
dddZ	eddd					
		dddZ
dS )a  
********************
Bipartite Edge Lists
********************
Read and write NetworkX graphs as bipartite edge lists.

Format
------
You can read or write three formats of edge lists with these functions.

Node pairs with no data::

 1 2

Python dictionary as data::

 1 2 {'weight':7, 'color':'green'}

Arbitrary data::

 1 2 7 green

For each edge (u, v) the node u is assigned to part 0 and the node v to part 1.
)generate_edgelistwrite_edgelistparse_edgelistread_edgelist    N)not_implemented_for	open_file   wb)mode# Tutf-8c                 C   s.   t | ||D ]}|d7 }||| qdS )a   Write a bipartite graph as a list of edges.

    Parameters
    ----------
    G : Graph
       A NetworkX bipartite graph
    path : file or string
       File or filename to write. If a file is provided, it must be
       opened in 'wb' mode. Filenames ending in .gz or .bz2 will be compressed.
    comments : string, optional
       The character used to indicate the start of a comment
    delimiter : string, optional
       The string used to separate values.  The default is whitespace.
    data : bool or list, optional
       If False write no edge data.
       If True write a string representation of the edge data dictionary..
       If a list (or other iterable) is provided, write the  keys specified
       in the list.
    encoding: string, optional
       Specify which encoding to use when writing file.

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> G.add_nodes_from([0, 2], bipartite=0)
    >>> G.add_nodes_from([1, 3], bipartite=1)
    >>> nx.write_edgelist(G, "test.edgelist")
    >>> fh = open("test.edgelist", "wb")
    >>> nx.write_edgelist(G, fh)
    >>> nx.write_edgelist(G, "test.edgelist.gz")
    >>> nx.write_edgelist(G, "test.edgelist.gz", data=False)

    >>> G = nx.Graph()
    >>> G.add_edge(1, 2, weight=7, color="red")
    >>> nx.write_edgelist(G, "test.edgelist", data=False)
    >>> nx.write_edgelist(G, "test.edgelist", data=["color"])
    >>> nx.write_edgelist(G, "test.edgelist", data=["color", "weight"])

    See Also
    --------
    write_edgelist
    generate_edgelist
    
N)r   writeencode)Gpathcomments	delimiterdataencodingline r   M/tmp/pip-target-vg8gfxp4/lib/python/networkx/algorithms/bipartite/edgelist.pyr      s   -r   directedc           	   
   #   s    zdd | j  D }W n ty } ztd|d}~ww |du s'|du rA|D ]}| j||dD ]}|tt|V  q2q)dS |D ]4}| j|ddD ]*\}} ||g}z| fdd	|D  W n	 t	yl   Y nw |tt|V  qLqCdS )
a  Generate a single line of the bipartite graph G in edge list format.

    Parameters
    ----------
    G : NetworkX graph
       The graph is assumed to have node attribute `part` set to 0,1 representing
       the two graph parts

    delimiter : string, optional
       Separator for node labels

    data : bool or list of keys
       If False generate no edge data.  If True use a dictionary
       representation of edge data.  If a list of keys use a list of data
       values corresponding to the keys.

    Returns
    -------
    lines : string
        Lines of data in adjlist format.

    Examples
    --------
    >>> from networkx.algorithms import bipartite
    >>> G = nx.path_graph(4)
    >>> G.add_nodes_from([0, 2], bipartite=0)
    >>> G.add_nodes_from([1, 3], bipartite=1)
    >>> G[1][2]["weight"] = 3
    >>> G[2][3]["capacity"] = 12
    >>> for line in bipartite.generate_edgelist(G, data=False):
    ...     print(line)
    0 1
    2 1
    2 3

    >>> for line in bipartite.generate_edgelist(G):
    ...     print(line)
    0 1 {}
    2 1 {'weight': 3}
    2 3 {'capacity': 12}

    >>> for line in bipartite.generate_edgelist(G, data=["weight"]):
    ...     print(line)
    0 1
    2 1 3
    2 3
    c                 S   s    g | ]\}}|d  dkr|qS )	bipartiter   r   ).0ndr   r   r   
<listcomp>   s     z%generate_edgelist.<locals>.<listcomp>z"Missing node attribute `bipartite`NTF)r   c                 3   s    | ]} | V  qd S Nr   )r   kr   r   r   	<genexpr>   s    z$generate_edgelist.<locals>.<genexpr>)
nodesitemsBaseExceptionAttributeErroredgesjoinmapstrextendKeyError)	r   r   r   part0errr   edgeuvr   r"   r   r   Q   s0   1
r   c                 C   s  ddl m} td|}| D ]}||}	|	dkr|d|	 }t|s$q| |}
t|
dk r2q|
d}|
d}|
}|durhz
||}||}W n t	yg } zt
d| d| d| d|d}~ww t|dksr|d	u rui }no|d
u rzt|d|}W n_ t	y } z	t
d| d|d}~ww t|t|krtd| d| di }t||D ]/\\}}}z||}W n t	y } zt
d| d| d| d|d}~ww |||i q|j|dd |j|dd |j||fi | q|S )a  Parse lines of an edge list representation of a bipartite graph.

    Parameters
    ----------
    lines : list or iterator of strings
        Input data in edgelist format
    comments : string, optional
       Marker for comment lines
    delimiter : string, optional
       Separator for node labels
    create_using: NetworkX graph container, optional
       Use given NetworkX graph for holding nodes or edges.
    nodetype : Python type, optional
       Convert nodes to this type.
    data : bool or list of (label,type) tuples
       If False generate no edge data or if True use a dictionary
       representation of edge data or a list tuples specifying dictionary
       key names and types for edge data.

    Returns
    -------
    G: NetworkX Graph
        The bipartite graph corresponding to lines

    Examples
    --------
    Edgelist with no data:

    >>> from networkx.algorithms import bipartite
    >>> lines = ["1 2", "2 3", "3 4"]
    >>> G = bipartite.parse_edgelist(lines, nodetype=int)
    >>> sorted(G.nodes())
    [1, 2, 3, 4]
    >>> sorted(G.nodes(data=True))
    [(1, {'bipartite': 0}), (2, {'bipartite': 0}), (3, {'bipartite': 0}), (4, {'bipartite': 1})]
    >>> sorted(G.edges())
    [(1, 2), (2, 3), (3, 4)]

    Edgelist with data in Python dictionary representation:

    >>> lines = ["1 2 {'weight':3}", "2 3 {'weight':27}", "3 4 {'weight':3.0}"]
    >>> G = bipartite.parse_edgelist(lines, nodetype=int)
    >>> sorted(G.nodes())
    [1, 2, 3, 4]
    >>> sorted(G.edges(data=True))
    [(1, 2, {'weight': 3}), (2, 3, {'weight': 27}), (3, 4, {'weight': 3.0})]

    Edgelist with data in a list:

    >>> lines = ["1 2 3", "2 3 27", "3 4 3.0"]
    >>> G = bipartite.parse_edgelist(lines, nodetype=int, data=(("weight", float),))
    >>> sorted(G.nodes())
    [1, 2, 3, 4]
    >>> sorted(G.edges(data=True))
    [(1, 2, {'weight': 3.0}), (2, 3, {'weight': 27.0}), (3, 4, {'weight': 3.0})]

    See Also
    --------
    r   )literal_evalN   zFailed to convert nodes ,z	 to type .FTr   zFailed to convert edge data (z)to dictionary.z
Edge data z and data_keys z are not the same lengthzFailed to convert z data )r   r   )astr3   nxempty_graphfindlenstripsplitpopr&   	TypeErrordictr)   
IndexErrorzipupdateadd_nodeadd_edge)linesr   r   create_usingnodetyper   r3   r   r   psr1   r2   r   r/   edgedataedge_key	edge_type
edge_valuer   r   r   r      s   >



r   rbc           	         s&    fdd| D }t ||||||dS )a  Read a bipartite graph from a list of edges.

    Parameters
    ----------
    path : file or string
       File or filename to read. If a file is provided, it must be
       opened in 'rb' mode.
       Filenames ending in .gz or .bz2 will be uncompressed.
    comments : string, optional
       The character used to indicate the start of a comment.
    delimiter : string, optional
       The string used to separate values.  The default is whitespace.
    create_using : Graph container, optional,
       Use specified container to build graph.  The default is networkx.Graph,
       an undirected graph.
    nodetype : int, float, str, Python type, optional
       Convert node data from strings to specified type
    data : bool or list of (label,type) tuples
       Tuples specifying dictionary key names and types for edge data
    edgetype : int, float, str, Python type, optional OBSOLETE
       Convert edge data from strings to specified type and use as 'weight'
    encoding: string, optional
       Specify which encoding to use when reading file.

    Returns
    -------
    G : graph
       A networkx Graph or other type specified with create_using

    Examples
    --------
    >>> from networkx.algorithms import bipartite
    >>> G = nx.path_graph(4)
    >>> G.add_nodes_from([0, 2], bipartite=0)
    >>> G.add_nodes_from([1, 3], bipartite=1)
    >>> bipartite.write_edgelist(G, "test.edgelist")
    >>> G = bipartite.read_edgelist("test.edgelist")

    >>> fh = open("test.edgelist", "rb")
    >>> G = bipartite.read_edgelist(fh)
    >>> fh.close()

    >>> G = bipartite.read_edgelist("test.edgelist", nodetype=int)

    Edgelist with data in a list:

    >>> textline = "1 2 3"
    >>> fh = open("test.edgelist", "w")
    >>> d = fh.write(textline)
    >>> fh.close()
    >>> G = bipartite.read_edgelist(
    ...     "test.edgelist", nodetype=int, data=(("weight", float),)
    ... )
    >>> list(G)
    [1, 2]
    >>> list(G.edges(data=True))
    [(1, 2, {'weight': 3.0})]

    See parse_edgelist() for more examples of formatting.

    See Also
    --------
    parse_edgelist

    Notes
    -----
    Since nodes must be hashable, the function nodetype must return hashable
    types (e.g. int, float, str, frozenset - or tuples of those, etc.)
    c                 3   s    | ]}|  V  qd S r    )decode)r   r   r   r   r   r#   ]  s    z read_edgelist.<locals>.<genexpr>)r   r   rG   rH   r   )r   )	r   r   r   rG   rH   r   edgetyper   rF   r   rQ   r   r     s   Pr   )r   r   Tr   )r   T)r   NNNT)r   NNNTNr   )__doc____all__networkxr8   networkx.utilsr   r   r   r   r   r   r   r   r   r   <module>   s&    
1D

x