U
    :vfL                     @   s   d Z ddlZddlZddlmZ ddlZddlmZ dddgZ	G dd	 d	Z
G d
d de
ZG dd de
ZG dd dZG dd deZG dd deZdddZedddddZdd Zd ddZdS )!z-
Text-based visual representations of graphs
    N)defaultdict)	open_file
forest_strgenerate_network_textwrite_network_textc                   @   s$   e Zd ZdZdZdZdZdZdZdS )_AsciiBaseGlyphs+z+--     z:   z|   N	__name__
__module____qualname__emptynewtree_lastnewtree_midendof_forestwithin_forestwithin_tree r   r   ;/tmp/pip-unpacked-wheel-_lngutwb/networkx/readwrite/text.pyr      s   r   c                   @   s   e Zd ZdZdZdZdS )AsciiDirectedGlyphszL-> z|-> z<-Nr   r   r   lastmidbackedger   r   r   r   r      s   r   c                   @   s   e Zd ZdZdZdZdS )AsciiUndirectedGlyphszL-- z|-- -Nr   r   r   r   r   r      s   r   c                   @   s$   e Zd ZdZdZdZdZdZdZdS )_UtfBaseGlyphsu   ╙u
   ╙── u
   ╟── r	   u   ╎   u   │   Nr
   r   r   r   r   r   #   s   r   c                   @   s   e Zd ZdZdZdZdS )UtfDirectedGlyphsu
   └─╼ u
   ├─╼ u   ╾Nr   r   r   r   r   r   /   s   r   c                   @   s   e Zd ZdZdZdZdS )UtfUndirectedGlyphsu
   └── u
   ├── u   ─Nr   r   r   r   r   r   5   s   r   TFc                 #   sd     }|r&|rtnt} j} j}n|r.tnt} j} j}t|t	rN|n|rXdnd|dkrt|j
d V  nt jdkr|j
V  n|dkrt }t|d fddt|D ddd }	td	d
 }
t |	r`|	 \}}}}|tk	r||k}|r|
|  d7  < |rj|
| rj|dk	rjd}|t||f}|	| d}||||f}|	| q|rrq܈| |s|r||jg }||jg }n||jg }||jg }n8|r||jg }||jg }n||jg }||jg }|tkrd}d}g }n dk	r0t	 j| |}nt	|}|rRt|| }|hn fdd|| D }||h|dk	rt||d kr|rtg}|hfdd|| D }|r
dk	rd fdd|D }nddd |D }dd|j|g}nd}d|||g V  t|ddd D ](\}}|dk}||||f}|	| q4qdS )aI  Generate lines in the "network text" format

    This works via a depth-first traversal of the graph and writing a line for
    each unique node encountered. Non-tree edges are written to the right of
    each node, and connection to a non-tree edge is indicated with an ellipsis.
    This representation works best when the input graph is a forest, but any
    graph can be represented.

    This notation is original to networkx, although it is simple enough that it
    may be known in existing literature. See #5602 for details. The procedure
    is summarized as follows:

    1. Given a set of source nodes (which can be specified, or automatically
    discovered via finding the (strongly) connected components and choosing one
    node with minimum degree from each), we traverse the graph in depth first
    order.

    2. Each reachable node will be printed exactly once on it's own line.

    3. Edges are indicated in one of three ways:

        a. a parent "L-style" connection on the upper left. This corresponds to
        a traversal in the directed DFS tree.

        b. a backref "<-style" connection shown directly on the right. For
        directed graphs, these are drawn for any incoming edges to a node that
        is not a parent edge. For undirected graphs, these are drawn for only
        the non-parent edges that have already been represented (The edges that
        have not been represented will be handled in the recursive case).

        c. a child "L-style" connection on the lower right. Drawing of the
        children are handled recursively.

    4. The children of each node (wrt the directed DFS tree) are drawn
    underneath and to the right of it. In the case that a child node has already
    been drawn the connection is replaced with an ellipsis ("...") to indicate
    that there is one or more connections represented elsewhere.

    5. If a maximum depth is specified, an edge to nodes past this maximum
    depth will be represented by an ellipsis.

    Parameters
    ----------
    graph : nx.DiGraph | nx.Graph
        Graph to represent

    with_labels : bool | str
        If True will use the "label" attribute of a node to display if it
        exists otherwise it will use the node value itself. If given as a
        string, then that attribute name will be used instead of "label".
        Defaults to True.

    sources : List
        Specifies which nodes to start traversal from. Note: nodes that are not
        reachable from one of these sources may not be shown. If unspecified,
        the minimal set of nodes needed to reach all others will be used.

    max_depth : int | None
        The maximum depth to traverse before stopping. Defaults to None.

    ascii_only : Boolean
        If True only ASCII characters are used to construct the visualization

    Yields
    ------
    str : a line of generated text
    labelNr   z ...   c                    s    g | ]\}}d |g | kfqS Nr   ).0idxnode)last_idxr   r   
<listcomp>   s    z)generate_network_text.<locals>.<listcomp>c                   S   s   dS )Nr   r   r   r   r   r   <lambda>       z'generate_network_text.<locals>.<lambda>TF c                    s   g | ]}| kr|qS r   r   )r#   child)
seen_nodesr   r   r'      s     c                    s   g | ]}| kr|qS r   r   r#   p)handled_parentsr   r   r'     s      z, c                    s"   g | ]}t  j| |qS r   )strnodesgetr.   )graph
label_attrr   r   r'     s   c                 S   s   g | ]}t |qS r   )r1   r.   r   r   r   r'     s      ) is_directedr   r   succpredr   r   Zadj
isinstancer1   r   lenr2   _find_sources	enumerater   setpopEllipsisappendaddr   r   r   r   r   r   r   r3   listjoinr   )r4   with_labelssources	max_depth
ascii_onlyr7   Zglyphsr8   r9   stackZnum_skipped_childrenparentr%   indentsZthis_islastskipZnext_islastZ	try_frameZthis_prefixZnext_prefixr    suffixchildrenZother_parentsZother_parents_labelsr$   r,   r   )r4   r0   r5   r&   r-   r   r   ;   s    F










r!   w
c           	      C   sf   |dkrt jj}n,t|dr$|j}nt|r2|}ntt|t| ||||dD ]}|||  qPdS )u  Creates a nice text representation of a graph

    This works via a depth-first traversal of the graph and writing a line for
    each unique node encountered. Non-tree edges are written to the right of
    each node, and connection to a non-tree edge is indicated with an ellipsis.
    This representation works best when the input graph is a forest, but any
    graph can be represented.

    Parameters
    ----------
    graph : nx.DiGraph | nx.Graph
        Graph to represent

    path : string or file or callable or None
       Filename or file handle for data output.
       if a function, then it will be called for each generated line.
       if None, this will default to "sys.stdout.write"

    with_labels : bool | str
        If True will use the "label" attribute of a node to display if it
        exists otherwise it will use the node value itself. If given as a
        string, then that attribute name will be used instead of "label".
        Defaults to True.

    sources : List
        Specifies which nodes to start traversal from. Note: nodes that are not
        reachable from one of these sources may not be shown. If unspecified,
        the minimal set of nodes needed to reach all others will be used.

    max_depth : int | None
        The maximum depth to traverse before stopping. Defaults to None.

    ascii_only : Boolean
        If True only ASCII characters are used to construct the visualization

    end : string
        The line ending character

    Examples
    --------
    >>> graph = nx.balanced_tree(r=2, h=2, create_using=nx.DiGraph)
    >>> nx.write_network_text(graph)
    ╙── 0
        ├─╼ 1
        │   ├─╼ 3
        │   └─╼ 4
        └─╼ 2
            ├─╼ 5
            └─╼ 6

    >>> # A near tree with one non-tree edge
    >>> graph.add_edge(5, 1)
    >>> nx.write_network_text(graph)
    ╙── 0
        ├─╼ 1 ╾ 5
        │   ├─╼ 3
        │   └─╼ 4
        └─╼ 2
            ├─╼ 5
            │   └─╼  ...
            └─╼ 6

    >>> graph = nx.cycle_graph(5)
    >>> nx.write_network_text(graph)
    ╙── 0
        ├── 1
        │   └── 2
        │       └── 3
        │           └── 4 ─ 0
        └──  ...

    >>> graph = nx.generators.barbell_graph(4, 2)
    >>> nx.write_network_text(graph)
    ╙── 4
        ├── 5
        │   └── 6
        │       ├── 7
        │       │   ├── 8 ─ 6
        │       │   │   └── 9 ─ 6, 7
        │       │   └──  ...
        │       └──  ...
        └── 3
            ├── 0
            │   ├── 1 ─ 3
            │   │   └── 2 ─ 0, 3
            │   └──  ...
            └──  ...

    >>> graph = nx.complete_graph(5, create_using=nx.Graph)
    >>> nx.write_network_text(graph)
    ╙── 0
        ├── 1
        │   ├── 2 ─ 0
        │   │   ├── 3 ─ 0, 1
        │   │   │   └── 4 ─ 0, 1, 2
        │   │   └──  ...
        │   └──  ...
        └──  ...

    >>> graph = nx.complete_graph(3, create_using=nx.DiGraph)
    >>> nx.write_network_text(graph)
    ╙── 0 ╾ 1, 2
        ├─╼ 1 ╾ 2
        │   ├─╼ 2 ╾ 0
        │   │   └─╼  ...
        │   └─╼  ...
        └─╼  ...
    Nwrite)rE   rF   rG   rH   )sysstdoutrQ   hasattrcallable	TypeErrortyper   )	r4   pathrE   rF   rG   rH   end_writeliner   r   r   r   !  s    v


c           
         s      rtt }t |}dd | D }|jd } jD ]}|| }|| | qDg }| D ]8}|j| dkrl|| }t	| fddd}	||	 qln, fdd	t
 D }t| fd
dd}|S )zR
    Determine a minimal set of nodes such that the entire graph is reachable
    c                 S   s   i | ]
}|g qS r   r   )r#   snr   r   r   
<dictcomp>  s      z!_find_sources.<locals>.<dictcomp>mappingr   c                    s
    j |  S r"   )	in_degreenr4   r   r   r)     r*   z_find_sources.<locals>.<lambda>keyc                    s    g | ]}t | fd ddqS )c                    s
    j |  S r"   Zdegreer`   rb   r   r   r)     r*   z*_find_sources.<locals>.<listcomp>.<lambda>rc   )min)r#   ccrb   r   r   r'     s   z!_find_sources.<locals>.<listcomp>c                    s
    j |  S r"   re   r`   rb   r   r   r)     r*   )r7   rC   nxZstrongly_connected_componentsZcondensationr2   r4   rA   r_   rf   Zconnected_componentssorted)
r4   ZsccsZ	scc_graphZsupernode_to_nodesr^   ra   r\   rF   Zsccr%   r   rb   r   r<     s&    


r<   c                 C   st   d}t |t t| jdkr2t| s2tdg }|dkrF|j}n|}t	| ||||dd |dkrpd
|S dS )u  Creates a nice utf8 representation of a forest

    This function has been superseded by
    :func:`nx.readwrite.text.generate_network_text`, which should be used
    instead.

    Parameters
    ----------
    graph : nx.DiGraph | nx.Graph
        Graph to represent (must be a tree, forest, or the empty graph)

    with_labels : bool
        If True will use the "label" attribute of a node to display if it
        exists otherwise it will use the node value itself. Defaults to True.

    sources : List
        Mainly relevant for undirected forests, specifies which nodes to list
        first. If unspecified the root nodes of each tree will be used for
        directed forests; for undirected forests this defaults to the nodes
        with the smallest degree.

    write : callable
        Function to use to write to, if None new lines are appended to
        a list and returned. If set to the `print` function, lines will
        be written to stdout as they are generated. If specified,
        this function will return None. Defaults to None.

    ascii_only : Boolean
        If True only ASCII characters are used to construct the visualization

    Returns
    -------
    str | None :
        utf8 representation of the tree / forest

    Examples
    --------
    >>> graph = nx.balanced_tree(r=2, h=3, create_using=nx.DiGraph)
    >>> print(nx.forest_str(graph))
    ╙── 0
        ├─╼ 1
        │   ├─╼ 3
        │   │   ├─╼ 7
        │   │   └─╼ 8
        │   └─╼ 4
        │       ├─╼ 9
        │       └─╼ 10
        └─╼ 2
            ├─╼ 5
            │   ├─╼ 11
            │   └─╼ 12
            └─╼ 6
                ├─╼ 13
                └─╼ 14


    >>> graph = nx.balanced_tree(r=1, h=2, create_using=nx.Graph)
    >>> print(nx.forest_str(graph))
    ╙── 0
        └── 1
            └── 2

    >>> print(nx.forest_str(graph, ascii_only=True))
    +-- 0
        L-- 1
            L-- 2
    z
forest_str is deprecated as of version 3.1 and will be removed in version 3.3. Use generate_network_text or write_network_text instead.
r   z)input must be a forest or the empty graphNr+   )rE   rF   rH   rY   rP   )warningswarnDeprecationWarningr;   r2   rh   Z	is_forestZNetworkXNotImplementedrA   r   rD   )r4   rE   rF   rQ   rH   msgZprintbufrZ   r   r   r   r     s(    E

	)TNNF)NTNNFrP   )TNNF)__doc__rR   rj   collectionsr   Znetworkxrh   Znetworkx.utilsr   __all__r   r   r   r   r   r   r   r   r<   r   r   r   r   r   <module>   s:   
	       
 g       %