
    wg                     |   d dl mZ d dlZg dZej
                  d        Z ej
                  d      dd       Z ej
                  d      dd       Z ej
                  d      d	        Z	 ej
                  d      d
        Z
 G d d      Z G d d      Zd Z G d d      Z G d dej                        Zy)    )defaultdictN)check_planarity	is_planarPlanarEmbeddingc                 "    t        | d      d   S )a$  Returns True if and only if `G` is planar.

    A graph is *planar* iff it can be drawn in a plane without
    any edge intersections.

    Parameters
    ----------
    G : NetworkX graph

    Returns
    -------
    bool
       Whether the graph is planar.

    Examples
    --------
    >>> G = nx.Graph([(0, 1), (0, 2)])
    >>> nx.is_planar(G)
    True
    >>> nx.is_planar(nx.complete_graph(5))
    False

    See Also
    --------
    check_planarity :
        Check if graph is planar *and* return a `PlanarEmbedding` instance if True.
    F)counterexampler   )r   )Gs    b/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/networkx/algorithms/planarity.pyr   r      s    < 1U3A66    T)returns_graphc                 d    t        |       }|j                         }||rdt        |       fS yd|fS )ad  Check if a graph is planar and return a counterexample or an embedding.

    A graph is planar iff it can be drawn in a plane without
    any edge intersections.

    Parameters
    ----------
    G : NetworkX graph
    counterexample : bool
        A Kuratowski subgraph (to proof non planarity) is only returned if set
        to true.

    Returns
    -------
    (is_planar, certificate) : (bool, NetworkX graph) tuple
        is_planar is true if the graph is planar.
        If the graph is planar `certificate` is a PlanarEmbedding
        otherwise it is a Kuratowski subgraph.

    Examples
    --------
    >>> G = nx.Graph([(0, 1), (0, 2)])
    >>> is_planar, P = nx.check_planarity(G)
    >>> print(is_planar)
    True

    When `G` is planar, a `PlanarEmbedding` instance is returned:

    >>> P.get_data()
    {0: [1, 2], 1: [0], 2: [0]}

    Notes
    -----
    A (combinatorial) embedding consists of cyclic orderings of the incident
    edges at each vertex. Given such an embedding there are multiple approaches
    discussed in literature to drawing the graph (subject to various
    constraints, e.g. integer coordinates), see e.g. [2].

    The planarity check algorithm and extraction of the combinatorial embedding
    is based on the Left-Right Planarity Test [1].

    A counterexample is only generated if the corresponding parameter is set,
    because the complexity of the counterexample generation is higher.

    See also
    --------
    is_planar :
        Check for planarity without creating a `PlanarEmbedding` or counterexample.

    References
    ----------
    .. [1] Ulrik Brandes:
        The Left-Right Planarity Test
        2009
        http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.217.9208
    .. [2] Takao Nishizeki, Md Saidur Rahman:
        Planar graph drawing
        Lecture Notes Series on Computing: Volume 12
        2004
    FFNT)LRPlanaritylr_planarityget_counterexampler	   r   planarity_state	embeddings       r
   r   r   )   sE    ~ "!nO,,.I,Q/// Yr   c                 d    t        |       }|j                         }||rdt        |       fS yd|fS )z-Recursive version of :meth:`check_planarity`.Fr   T)r   lr_planarity_recursiveget_counterexample_recursiver   s       r
   check_planarity_recursiver   u   sD     "!nO668I6q999 Yr   c                 `   t        j                  |       } t        |       d   rt        j                  d      t        j                         }| D ]\  }t	        | |         }|D ]G  }| j                  ||       t        |       d   s$| j                  ||       |j                  ||       I ^ |S )a  Obtains a Kuratowski subgraph.

    Raises nx.NetworkXException if G is planar.

    The function removes edges such that the graph is still not planar.
    At some point the removal of any edge would make the graph planar.
    This subgraph must be a Kuratowski subgraph.

    Parameters
    ----------
    G : NetworkX graph

    Returns
    -------
    subgraph : NetworkX graph
        A Kuratowski subgraph that proves that G is not planar.

    r   !G is planar - no counter example.)nxGraphr   NetworkXExceptionlistremove_edgeadd_edger	   subgraphunbrsvs        r
   r   r      s    * 	Aq!""#FGG xxzH (AaDz 	(AMM!Qq!!$

1a !!!Q'		(( Or   c                 `   t        j                  |       } t        |       d   rt        j                  d      t        j                         }| D ]\  }t	        | |         }|D ]G  }| j                  ||       t        |       d   s$| j                  ||       |j                  ||       I ^ |S )z0Recursive version of :meth:`get_counterexample`.r   r   )r   r   r   r   r   r   r    r!   s        r
   r   r      s    
 	A #A&""#FGG xxzH (AaDz 	(AMM!Q(+A.

1a !!!Q'		(( Or   c                   *    e Zd ZdZddZd Zd Zd Zy)IntervalzRepresents a set of return edges.

    All return edges in an interval induce a same constraint on the contained
    edges, which means that all edges must either have a left orientation or
    all edges must have a right orientation.
    Nc                      || _         || _        y Nlowhigh)selfr,   r-   s      r
   __init__zInterval.__init__   s    	r   c                 >    | j                   du xr | j                  du S )zCheck if the interval is emptyNr+   r.   s    r
   emptyzInterval.empty   s    xx45DII$55r   c                 B    t        | j                  | j                        S )zReturns a copy of this interval)r(   r,   r-   r1   s    r
   copyzInterval.copy   s    $)),,r   c                 z    | j                          xr) |j                  | j                     |j                  |   kD  S )z0Returns True if interval I conflicts with edge b)r2   lowptr-   )r.   br   s      r
   conflictingzInterval.conflicting   s=     

 L%%dii0?3H3H3KK	
r   )NN)__name__
__module____qualname____doc__r/   r2   r4   r8    r   r
   r(   r(      s    6-
r   r(   c                   <    e Zd ZdZ e        e       fdZd Zd Zy)ConflictPairzRepresents a different constraint between two intervals.

    The edges in the left interval must have a different orientation than
    the one in the right interval.
    c                      || _         || _        y r*   leftright)r.   rB   rC   s      r
   r/   zConflictPair.__init__   s    	
r   c                 L    | j                   }| j                  | _         || _        y)zSwap left and right intervalsNrA   )r.   temps     r
   swapzConflictPair.swap   s    yyJJ	
r   c                    | j                   j                         r#|j                  | j                  j                     S | j                  j                         r#|j                  | j                   j                     S t        |j                  | j                   j                     |j                  | j                  j                           S )z.Returns the lowest lowpoint of a conflict pair)rB   r2   r6   rC   r,   min)r.   r   s     r
   lowestzConflictPair.lowest   s    99??"((88::"((77!!$))--0/2G2G

2W
 	
r   N)r9   r:   r;   r<   r(   r/   rF   rI   r=   r   r
   r?   r?      s!     %Jhj 
r   r?   c                     | sy| d   S )z(Returns the element on top of the stack.Nr=   )ls    r
   top_of_stackrM      s    R5Lr   c                   f    e Zd ZdZg dZd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zy)r   z5A class to maintain the state during planarity check.)r	   rootsheightr6   lowpt2nesting_depthparent_edgeDGadjsordered_adjsrefsideSstack_bottom
lowpt_edgeleft_ref	right_refr   c                    t        j                         | _        | j                  j                  |j                         |j
                  D ]0  }|d   |d   k7  s| j                  j                  |d   |d          2 g | _        t        d       | _	        i | _
        i | _        i | _        t        d       | _        t        j                         | _        | j                  j                  |j                         i | _        i | _        t        d       | _        t        d       | _        g | _        i | _        i | _        i | _        i | _        t3               | _        y )Nr      c                       y r*   r=   r=   r   r
   <lambda>z&LRPlanarity.__init__.<locals>.<lambda>%      r   c                       y r*   r=   r=   r   r
   ra   z&LRPlanarity.__init__.<locals>.<lambda>,  rb   r   c                       y r*   r=   r=   r   r
   ra   z&LRPlanarity.__init__.<locals>.<lambda>5  rb   r   c                       y)Nr_   r=   r=   r   r
   ra   z&LRPlanarity.__init__.<locals>.<lambda>6  rb   r   )r   r   r	   add_nodes_fromnodesedgesr    rO   r   rP   r6   rQ   rR   rS   DiGraphrT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r   r   )r.   r	   es      r
   r/   zLRPlanarity.__init__  s   agg& 	,Atqt|!ad+	, 
 ",/
 '|4 **,qww'	|,	*	 (*r   c                      j                   j                         dkD  r< j                   j                         d j                   j                         z  dz
  kD  ry j                   D ]'  t         j                             j                  <   )  j                   D ]M   j
                     d j
                  <    j                  j                          j                         O d _         d _	        d _         j                  D ]-  t         j                      fd       j                  <   /  j                  D ]   j                        r y d _        d _        d _        d _        d _         j                  j$                  D ]0  } j'                  |       j(                  |   z   j(                  |<   2  j*                  j-                   j                  j.                          j                  D ]c  t         j                      fd       j                  <   d} j                     D ]"  } j*                  j1                  ||	       |}$ e d _
        d _        d _         j                  D ]   j5                          d _        d _        d _        d _        d _        d _         j*                  S )
zExecute the LR planarity test.

        Returns
        -------
        embedding : dict
            If the graph is planar an embedding is returned. Otherwise None.
                 Nr   c                 &    j                   | f   S r*   rR   xr.   r%   s    r
   ra   z*LRPlanarity.lr_planarity.<locals>.<lambda>b      $*<*<aV*D r   keyc                 &    j                   | f   S r*   rp   rq   s    r
   ra   z*LRPlanarity.lr_planarity.<locals>.<lambda>v  rs   r   ccw)r	   ordersizer   rU   rP   rO   appenddfs_orientationrQ   rT   sortedrV   dfs_testingr6   rY   rZ   r[   rh   signrR   r   rf   rg   add_half_edgerW   dfs_embeddingrS   r\   r]   rX   r.   rj   previous_nodewr%   s   `   @r
   r   zLRPlanarity.lr_planarityB  s    66<<>A$&&++-!dfflln2Dq2H"H  	+Aq	?DIIaL	+  	(A{{1~%!"A

!!!$$$Q'		( 	  	A#)
 D$Da 	
  	A##A&	
 
  	IA$(IIaL43E3Ea3H$HDq!	I 	%%dggmm4 		"A#)
 D$Da  !M&&q) ",,Q},E !"		" !  	"Aq!	" 
 	~~r   c                 n     j                   j                         dkD  r< j                   j                         d j                   j                         z  dz
  kD  ry j                   D ]M   j                     d j                  <    j                  j                          j                         O d _          j                  D ]-  t         j                      fd       j                  <   /  j                  D ]   j                        r y  j                  j                  D ]0  } j                  |       j                  |   z   j                  |<   2  j                  j                   j                  j                           j                  D ]c  t         j                      fd       j                  <   d} j                     D ]"  } j                  j#                  ||	       |}$ e  j                  D ]   j%                           j                  S )
z*Recursive version of :meth:`lr_planarity`.rl   rm   rn   Nr   c                 &    j                   | f   S r*   rp   rq   s    r
   ra   z4LRPlanarity.lr_planarity_recursive.<locals>.<lambda>  rs   r   rt   c                 &    j                   | f   S r*   rp   rq   s    r
   ra   z4LRPlanarity.lr_planarity_recursive.<locals>.<lambda>  rs   r   rw   )r	   ry   rz   rP   rO   r{   dfs_orientation_recursiverT   r}   rV   dfs_testing_recursiverh   sign_recursiverR   r   rf   rg   r   dfs_embedding_recursiver   s   `   @r
   r   z"LRPlanarity.lr_planarity_recursive  s   66<<>A$&&++-!dfflln2Dq2H"H  	2A{{1~%!"A

!!!$..q1		2   	A#)
 D$Da 	
  	A--a0	  	SA$($7$7$:T=O=OPQ=R$RDq!	S 	%%dggmm4 		"A#)
 D$Da  !M&&q) ",,Q},E !"		"  	,A((+	, ~~r   c                    |g}t        d       }t        d       }|r|j                         }| j                  |   }| j                  |   ||   d D ]  }||f}||   s||f| j                  j
                  v s||f| j                  j
                  v r||xx   dz  cc<   P| j                  j                  ||       | j                  |   | j                  |<   | j                  |   | j                  |<   | j                  |   X|| j                  |<   | j                  |   dz   | j                  |<   |j                  |       |j                  |       d||<    nx| j                  |   | j                  |<   d| j                  |   z  | j                  |<   | j                  |   | j                  |   k  r| j                  |xx   dz  cc<   || j                  |   | j                  |   k  rPt        | j                  |   | j                  |         | j                  |<   | j                  |   | j                  |<   n| j                  |   | j                  |   kD  r4t        | j                  |   | j                  |         | j                  |<   n3t        | j                  |   | j                  |         | j                  |<   ||xx   dz  cc<    |ryy)z=Orient the graph by DFS, compute lowpoints and nesting order.c                       yNr   r=   r=   r   r
   ra   z-LRPlanarity.dfs_orientation.<locals>.<lambda>  rb   r   c                       yNFr=   r=   r   r
   ra   z-LRPlanarity.dfs_orientation.<locals>.<lambda>  rb   r   Nr_   Trl   )r   poprS   rU   rT   rh   r    rP   r6   rQ   r{   rR   rH   )r.   r%   	dfs_stackind	skip_initrj   r   vws           r
   r|   zLRPlanarity.dfs_orientation  sq    C	)$.	A  #AYYq\#a&(+ &V }1v.1a&DGGMM2IA! GG$$Q*%)[[^DJJrN&*kk!nDKKO{{1~-.0((+)-Q!);A!((+!((+(,	")-Q

2 *+TZZ^);""2&;;r?T[[^3&&r*a/* =zz"~

15),TZZ]DKKO)LA(,

2

1B$**Q-7),T[[^TZZ^)LA),T[[^T[[_)MAA!M&	 r   c                    | j                   |   }| j                  |   D ]K  }||f| j                  j                  v s||f| j                  j                  v r9||f}| j                  j	                  ||       | j
                  |   | j                  |<   | j
                  |   | j                  |<   | j
                  |   @|| j                   |<   | j
                  |   dz   | j
                  |<   | j                  |       n| j
                  |   | j                  |<   d| j                  |   z  | j                  |<   | j                  |   | j
                  |   k  r| j                  |xx   dz  cc<   |U| j                  |   | j                  |   k  rQt        | j                  |   | j                  |         | j                  |<   | j                  |   | j                  |<   | j                  |   | j                  |   kD  r5t        | j                  |   | j                  |         | j                  |<   t        | j                  |   | j                  |         | j                  |<   N y)z-Recursive version of :meth:`dfs_orientation`.Nr_   rl   )rS   r	   rT   rh   r    rP   r6   rQ   r   rR   rH   )r.   r%   rj   r   r   s        r
   r   z%LRPlanarity.dfs_orientation_recursive  s   Q 	JA1v&1a&DGGMM*AQBGGQ"![[^DJJrN"kk!nDKKO{{1~%&(  #!%Q!!3A..q1!%Q

2 &'B%7Dr"{{2Q/""2&!+& }::b>DJJqM1%(AB%HDKKN$(JJrNDJJqMZZ^djjm3%(QB%HDKKN%(QR%IDKKN9	Jr   c           	         |g}t        d       }t        d       }|rn|j                         }| j                  |   }d}| j                  |   ||   d D ]  }||f}||   st	        | j
                        | j                  |<   || j                  |   k(  r+|j                  |       |j                  |       d||<   d} n|| j                  |<   | j
                  j                  t        t        ||                   | j                  |   | j                  |   k  rF|| j                  |   d   k(  r| j                  |   | j                  |<   n| j                  ||      s y||xx   dz  cc<    |s|| j                  |       |rny)	zTest for LR partition.c                       yr   r=   r=   r   r
   ra   z)LRPlanarity.dfs_testing.<locals>.<lambda>  rb   r   c                       yr   r=   r=   r   r
   ra   z)LRPlanarity.dfs_testing.<locals>.<lambda>  rb   r   FNTrC   r   r_   )r   r   rS   rV   rM   rY   rZ   r{   r[   r?   r(   r6   rP   add_constraintsremove_back_edges)	r.   r%   r   r   r   rj   
skip_finalr   eis	            r
   r~   zLRPlanarity.dfs_testing  s    C	)$.	A  #AJ&&q)#a&(3 V },8,@D%%b)T--a00!((+!((+(,	"%)
.0+l"b9I&JK ::b>DKKN2D--a033-1__R-@*#33B:#(A!36 =**1-I L r   c           	      N   | j                   |   }| j                  |   D ]  }||f}t        | j                        | j                  |<   || j                   |   k(  r| j                  |      s@ y|| j                  |<   | j                  j                  t        t        ||                   | j                  |   | j                  |   k  s|| j                  |   d   k(  r| j                  |   | j                  |<   | j                  ||      r y || j                  |       y)z)Recursive version of :meth:`dfs_testing`.Fr   r   T)rS   rV   rM   rY   rZ   r   r[   r{   r?   r(   r6   rP   r   r   )r.   r%   rj   r   r   s        r
   r   z!LRPlanarity.dfs_testing_recursiveG  s   Q""1% 	%AQB$0$8Db!T%%a((11!4 &(#l"b1ABC zz"~A.))!,Q//)-)<DOOA&//A6$#	%( =""1%r   c                    t               }	 | j                  j                         }|j                  j	                         s|j                          |j                  j	                         sy| j                  |j                  j                     | j                  |   kD  r|j                  j	                         r |j                  j                         |_        n7|j                  j                  | j                  |j                  j                  <   |j                  j                  |j                  _        n0| j                  |   | j                  |j                  j                  <   t        | j                        | j                  |   k(  rnt        | j                        j                  j                  ||       s0t        | j                        j                  j                  ||       r| j                  j                         }|j                  j                  ||       r|j                          |j                  j                  ||       ry|j                  j                  | j                  |j                  j                  <   |j                  j                  %|j                  j                  |j                  _        |j                  j	                         r |j                  j                         |_        n7|j                  j                  | j                  |j                  j                  <   |j                  j                  |j                  _        t        | j                        j                  j                  ||       rt        | j                        j                  j                  ||       r|j                  j	                         r|j                  j	                         s| j                  j!                  |       y)NTF)r?   rY   r   rB   r2   rF   r6   rC   r,   r4   r-   rW   r[   rM   rZ   r8   r{   )r.   r   rj   PQs        r
   r   zLRPlanarity.add_constraintsb  s   N

A66<<>66<<>zz!''++&A677==?ggllnAG,-GGLLDHHQWW[[)ggkk(,(:%DFF#t'8'8'<<! $ 466"''33B=FFB

%B%B& 

Aww""2t,ww""2t,$%GGLLDHHQWW[[!ww{{&ggkkvv||~'(vv{{$AFFJ# 466"''33B=FFB

%B%B&& 177==?FFMM!r   c                 Z   |d   }| j                   rt        | j                         j                  |       | j                  |   k(  r| j                   j	                         }|j
                  j                  #d| j                  |j
                  j                  <   | j                   r5t        | j                         j                  |       | j                  |   k(  r| j                   r| j                   j	                         }|j
                  j                  |j
                  j                  d   |k(  re| j                  |j
                  j                     |j
                  _        |j
                  j                  |j
                  j                  d   |k(  re|j
                  j                  |j
                  j                  k|j                  j                  | j                  |j
                  j                  <   d| j                  |j
                  j                  <   d |j
                  _        |j                  j                  |j                  j                  d   |k(  re| j                  |j                  j                     |j                  _        |j                  j                  |j                  j                  d   |k(  re|j                  j                  |j                  j                  k|j
                  j                  | j                  |j                  j                  <   d| j                  |j                  j                  <   d |j                  _        | j                   j                  |       | j                  |   | j                  |   k  rt        | j                         j
                  j                  }t        | j                         j                  j                  }|1|| j                  |   | j                  |   kD  r|| j                  |<   y || j                  |<   y y )Nr   rK   r_   )rY   rM   rI   rP   r   rB   r,   rX   r-   rW   rC   r{   r6   )r.   rj   r#   r   hlhrs         r
   r   zLRPlanarity.remove_back_edges  s   aD ffdff-44T:dkk!nL

Avvzz%(*		!&&**% ffdff-44T:dkk!nL
 66

A&&++)affkk!n.A"hhqvv{{3 &&++)affkk!n.Avv{{"qvvzz'='(ww{{$(*		!&&**%!
'',,*qww||A!/C#xx5 '',,*qww||A!/Cww||#(?()

%)+		!''++&"FFMM! ::a=4;;q>)dff%**//Bdff%++00B~2:B$**R.1P   *r   c                 x   |g}t        d       }|r(|j                         }| j                  |   ||   d D ]  }||xx   dz  cc<   ||f}|| j                  |   k(  r^| j                  j                  ||       || j                  |<   || j                  |<   |j                  |       |j                  |        nz| j                  |   dk(  r,| j                  j                  ||| j                  |          | j                  j                  ||| j                  |          || j                  |<    |r'yy)zCompletes the embedding.c                       yr   r=   r=   r   r
   ra   z+LRPlanarity.dfs_embedding.<locals>.<lambda>  rb   r   Nr_   rw   cw)r   r   rV   rS   r   add_half_edge_firstr\   r]   r{   rX   r   )r.   r%   r   r   r   r   s         r
   r   zLRPlanarity.dfs_embedding  s'    C	)$A&&q)#a&(3 -A!V))!,,NN66q!<'(DMM!$()DNN1%$$Q'$$Q'yy})44Qt~~a?P4Q44QdmmA>N4O+,a(#- r   c                    | j                   |   D ]  }||f}|| j                  |   k(  rL| j                  j                  ||       || j                  |<   || j
                  |<   | j                  |       e| j                  |   dk(  r,| j                  j                  ||| j
                  |          | j                  j                  ||| j                  |          || j                  |<    y)z+Recursive version of :meth:`dfs_embedding`.r_   rw   r   N)	rV   rS   r   r   r\   r]   r   rX   r   )r.   r%   r   r   s       r
   r   z#LRPlanarity.dfs_embedding_recursive  s    ""1% 	)AQBT%%a((221a8#$a $%q!,,Q/99R=A%NN00A4>>!;L0M NN00A$--:J0K'(DMM!$	)r   c                 v   |g}t        d       }|r|j                         }| j                  |   Q|j                  |       |j                  | j                  |          | j                  |   ||<   d| j                  |<   n'| j                  |xx   | j                  ||      z  cc<   |r| j                  |   S )z:Resolve the relative side of an edge to the absolute side.c                       y r*   r=   r=   r   r
   ra   z"LRPlanarity.sign.<locals>.<lambda>  rb   r   N)r   r   rW   r{   rX   )r.   rj   r   old_refs       r
   r   zLRPlanarity.sign  s     C	l+Axx{&  #  !-!XXa[
"		!		'!* 55  yy|r   c                     | j                   |   J| j                  |   | j                  | j                   |         z  | j                  |<   d| j                   |<   | j                  |   S )z"Recursive version of :meth:`sign`.N)rW   rX   r   )r.   rj   s     r
   r   zLRPlanarity.sign_recursive  sX    88A;"99Q<$*=*=dhhqk*JJDIIaLDHHQKyy|r   N)r9   r:   r;   r<   	__slots__r/   r   r   r|   r   r~   r   r   r   r   r   r   r   r=   r   r
   r   r     sW    ?I*&+PM^-^3jJB/b6*X%!N-:)$(r   r   c                        e Zd ZdZd fd	Zd Zd Zd Zd Zd Z	d	 Z
ddd
 fd
Zd Zd Zd Zd Zd Zd Zd Zd ZddZd Zd fd	Z xZS )r   a   Represents a planar graph with its planar embedding.

    The planar embedding is given by a `combinatorial embedding
    <https://en.wikipedia.org/wiki/Graph_embedding#Combinatorial_embedding>`_.

    .. note:: `check_planarity` is the preferred way to check if a graph is planar.

    **Neighbor ordering:**

    In comparison to a usual graph structure, the embedding also stores the
    order of all neighbors for every vertex.
    The order of the neighbors can be given in clockwise (cw) direction or
    counterclockwise (ccw) direction. This order is stored as edge attributes
    in the underlying directed graph. For the edge (u, v) the edge attribute
    'cw' is set to the neighbor of u that follows immediately after v in
    clockwise direction.

    In order for a PlanarEmbedding to be valid it must fulfill multiple
    conditions. It is possible to check if these conditions are fulfilled with
    the method :meth:`check_structure`.
    The conditions are:

    * Edges must go in both directions (because the edge attributes differ)
    * Every edge must have a 'cw' and 'ccw' attribute which corresponds to a
      correct planar embedding.

    As long as a PlanarEmbedding is invalid only the following methods should
    be called:

    * :meth:`add_half_edge`
    * :meth:`connect_components`

    Even though the graph is a subclass of nx.DiGraph, it can still be used
    for algorithms that require undirected graphs, because the method
    :meth:`is_directed` is overridden. This is possible, because a valid
    PlanarGraph must have edges in both directions.

    **Half edges:**

    In methods like `add_half_edge` the term "half-edge" is used, which is
    a term that is used in `doubly connected edge lists
    <https://en.wikipedia.org/wiki/Doubly_connected_edge_list>`_. It is used
    to emphasize that the edge is only in one direction and there exists
    another half-edge in the opposite direction.
    While conventional edges always have two faces (including outer face) next
    to them, it is possible to assign each half-edge *exactly one* face.
    For a half-edge (u, v) that is oriented such that u is below v then the
    face that belongs to (u, v) is to the right of this half-edge.

    See Also
    --------
    is_planar :
        Preferred way to check if an existing graph is planar.

    check_planarity :
        A convenient way to create a `PlanarEmbedding`. If not planar,
        it returns a subgraph that shows this.

    Examples
    --------

    Create an embedding of a star graph (compare `nx.star_graph(3)`):

    >>> G = nx.PlanarEmbedding()
    >>> G.add_half_edge(0, 1)
    >>> G.add_half_edge(0, 2, ccw=1)
    >>> G.add_half_edge(0, 3, ccw=2)
    >>> G.add_half_edge(1, 0)
    >>> G.add_half_edge(2, 0)
    >>> G.add_half_edge(3, 0)

    Alternatively the same embedding can also be defined in counterclockwise
    orientation. The following results in exactly the same PlanarEmbedding:

    >>> G = nx.PlanarEmbedding()
    >>> G.add_half_edge(0, 1)
    >>> G.add_half_edge(0, 3, cw=1)
    >>> G.add_half_edge(0, 2, cw=3)
    >>> G.add_half_edge(1, 0)
    >>> G.add_half_edge(2, 0)
    >>> G.add_half_edge(3, 0)

    After creating a graph, it is possible to validate that the PlanarEmbedding
    object is correct:

    >>> G.check_structure()

    Nc                     t        |   dd|i| | j                  | _        | j                  | _        | j                  | _        y )Nincoming_graph_datar=   )superr/   _PlanarEmbedding__forbiddenr    add_edges_fromadd_weighted_edges_from)r.   r   attr	__class__s      r
   r/   zPlanarEmbedding.__init__Z  sB    I-@IDI(("..'+'7'7$r   c                     t        d      )zForbidden operation

        Any edge additions to a PlanarEmbedding should be done using
        method `add_half_edge`.
        z=Use `add_half_edge` method to add edges to a PlanarEmbedding.)NotImplementedError)r.   argskwargss      r
   __forbiddenzPlanarEmbedding.__forbidden`  s     "K
 	
r   c                 R    i }| D ]  }t        | j                  |            ||<   ! |S )a  Converts the adjacency structure into a better readable structure.

        Returns
        -------
        embedding : dict
            A dict mapping all nodes to a list of neighbors sorted in
            clockwise order.

        See Also
        --------
        set_data

        )r   neighbors_cw_order)r.   r   r%   s      r
   get_datazPlanarEmbedding.get_dataj  s7     	 	<A 7 7 :;IaL	<r   c                 h    |D ]-  }d}t        ||         D ]  }| j                  |||       |} / y)a\  Inserts edges according to given sorted neighbor list.

        The input format is the same as the output format of get_data().

        Parameters
        ----------
        data : dict
            A dict mapping all nodes to a list of neighbors sorted in
            clockwise order.

        See Also
        --------
        get_data

        Nr   )reversedr   )r.   datar%   rW   r   s        r
   set_datazPlanarEmbedding.set_data}  sJ       	ACd1g& ""1aC"0	r   c                    	 | j                   |   D ]J  }| j                  |   }||   d   }||   d   }||= | j                   |   |= ||k7  s;|||   d<   |||   d<   L | j                  |= | j                  |= | j                   |= t	        j                  |        y# t        $ r}t	        j
                  d| d      |d}~ww xY w)a  Remove node n.

        Removes the node n and all adjacent edges, updating the
        PlanarEmbedding to account for any resulting edge removal.
        Attempting to remove a non-existent node will raise an exception.

        Parameters
        ----------
        n : node
           A node in the graph

        Raises
        ------
        NetworkXError
           If n is not in the graph.

        See Also
        --------
        remove_nodes_from

        r   rx   z	The node   is not in the planar embedding.N)_pred_succ_nodeKeyErrorr   NetworkXError_clear_cache)r.   nr#   succs_uun_cwun_ccwerrs          r
   remove_nodezPlanarEmbedding.remove_node  s    ,	ZZ] 2**Q-
4( E*AJJJqM!$:,2GEN5),1GFOD)2 

1

1

1
 		  	""A3>?	s   A	B 9B 	C$B>>Cc                 R    |D ]"  }|| j                   v s| j                  |       $ y)a  Remove multiple nodes.

        Parameters
        ----------
        nodes : iterable container
            A container of nodes (list, dict, set, etc.).  If a node
            in the container is not in the graph it is silently ignored.

        See Also
        --------
        remove_node

        Notes
        -----
        When removing nodes from an iterator over the graph you are changing,
        a `RuntimeError` will be raised with message:
        `RuntimeError: dictionary changed size during iteration`. This
        happens when the graph's underlying dictionary is modified during
        iteration. To avoid this error, evaluate the iterator into a separate
        object, e.g. by using `list(iterator_of_nodes)`, and pass this
        object to `G.remove_nodes_from`.

        N)r   r   )r.   rg   r   s      r
   remove_nodes_fromz!PlanarEmbedding.remove_nodes_from  s,    0  	$ADJJ  #	$r   c              #      K   | j                   |   }|syt        t        |            }| ||   d   }||k7  r| ||   d   }||k7  ryyw)zGenerator for the neighbors of v in clockwise order.

        Parameters
        ----------
        v : node

        Yields
        ------
        node

        Nr   )r   nextr   )r.   r%   succs
start_nodecurrent_nodes        r
   r   z"PlanarEmbedding.neighbors_cw_order  se      

1(5/*
Z(.L( .t4L L(s   A	AAr   rx   c                   | j                   j                  |      }|rt        t        | j                   |               }|a||vrt	        j
                  d      |t	        j
                  d      ||   d   }t        
|   ||||       |||   d<   |||   d<   ||k7  }n^|G||vrt	        j
                  d      ||   d   }	t        
|   |||	|       |||	   d<   |||   d<   d}nt	        j
                  d	      |r|j                  |      ||<   yy||t	        j
                  d
      t        
|   ||||       y)a  Adds a half-edge from `start_node` to `end_node`.

        If the half-edge is not the first one out of `start_node`, a reference
        node must be provided either in the clockwise (parameter `cw`) or in
        the counterclockwise (parameter `ccw`) direction. Only one of `cw`/`ccw`
        can be specified (or neither in the case of the first edge).
        Note that specifying a reference in the clockwise (`cw`) direction means
        inserting the new edge in the first counterclockwise position with
        respect to the reference (and vice-versa).

        Parameters
        ----------
        start_node : node
            Start node of inserted edge.
        end_node : node
            End node of inserted edge.
        cw, ccw: node
            End node of reference edge.
            Omit or pass `None` if adding the first out-half-edge of `start_node`.


        Raises
        ------
        NetworkXException
            If the `cw` or `ccw` node is not a successor of `start_node`.
            If `start_node` has successors, but neither `cw` or `ccw` is provided.
            If both `cw` and `ccw` are specified.

        See Also
        --------
        connect_components
        Nz!Invalid clockwise reference node.z$Only one of cw/ccw can be specified.rx   r   r   z(Invalid counterclockwise reference node.TzLNode already has out-half-edge(s), either cw or ccw reference node required.zInvalid reference node.)rx   r   )	r   getr   r   r   r   r   r    r   )r.   r   end_noder   rx   r   leftmost_nbrref_ccwmove_leftmost_nbr_to_endref_cwr   s             r
   r   zPlanarEmbedding.add_half_edge  s   D 

z*J)? @AL~U?**+NOO?**+QRR)E* X"' J'/gt$#+b	%  ,.+=(e#**+UVVsD) X&c J'/fe$#+c
4 +/(&&b  ( ',ii&=l#	 ( ~&&'@AAGZxHMr   c                    | D ]z  }	 t        | j                  |            }t        | |         }||k7  rd}t        j                  |      | |   D ]+  }| j                  ||      rd}t        j                  |       | t               }t        j                  |       D ]  }t        |      dk(  rt        |      }	d}
d}|D ]<  }| j                  |      D ]&  }|
dz  }
||f|vs|dz  }| j                  |||       ( > |
dz  }|	|z
  |z   dk7  ssd}t        j                  |       y# t        $ r }d| }t        j                  |      |d}~ww xY w)	a(  Runs without exceptions if this object is valid.

        Checks that the following properties are fulfilled:

        * Edges go in both directions (because the edge attributes differ).
        * Every edge has a 'cw' and 'ccw' attribute which corresponds to a
          correct planar embedding.

        Running this method verifies that the underlying Graph must be planar.

        Raises
        ------
        NetworkXException
            This exception is raised with a short explanation if the
            PlanarEmbedding is invalid.
        z5Bad embedding. Missing orientation for a neighbor of Nz3Bad embedding. Edge orientations not set correctly.z-Bad embedding. Opposite half-edge is missing.r_   r   rl   z7Bad embedding. The graph does not match Euler's formula)	setr   r   r   r   has_edgeconnected_componentslentraverse_face)r.   r%   sorted_nbrsr   msgunsorted_nbrsr   counted_half_edges	component	num_nodesnum_half_edges	num_faces	num_edgess                r
   check_structurezPlanarEmbedding.check_structure;  s   $  	4A9!$"9"9!"<=
  QLMm+K**3//!W 4}}Q*IC..s33	4	4$ !U006 	0I9~"IINI E003 EA"a'N1v%77!Q	**1a1CDEE '!+I9$y0A5O**3//'	0!  9MaSQ**3/S89s   D++	E4EEc                 ,    | j                  |||       y)a  Adds a half-edge from start_node to end_node.

        The half-edge is added counter clockwise next to the existing half-edge
        (start_node, reference_neighbor).

        Parameters
        ----------
        start_node : node
            Start node of inserted edge.
        end_node : node
            End node of inserted edge.
        reference_neighbor: node
            End node of reference edge.

        Raises
        ------
        NetworkXException
            If the reference_neighbor does not exist.

        See Also
        --------
        add_half_edge
        add_half_edge_cw
        connect_components

        r   Nr   r.   r   r   reference_neighbors       r
   add_half_edge_ccwz!PlanarEmbedding.add_half_edge_ccwu  s    6 	:x4FGr   c                 ,    | j                  |||       y)ax  Adds a half-edge from start_node to end_node.

        The half-edge is added clockwise next to the existing half-edge
        (start_node, reference_neighbor).

        Parameters
        ----------
        start_node : node
            Start node of inserted edge.
        end_node : node
            End node of inserted edge.
        reference_neighbor: node
            End node of reference edge.

        Raises
        ------
        NetworkXException
            If the reference_neighbor does not exist.

        See Also
        --------
        add_half_edge
        add_half_edge_ccw
        connect_components
        rw   Nr   r   s       r
   add_half_edge_cwz PlanarEmbedding.add_half_edge_cw  s    4 	:x5GHr   c                    	 | j                   |   }| j                   |   }||   d   }||   d   }||   d   }||   d   }||= | j                  |   |= ||= | j                  |   |= ||k7  r|||   d<   |||   d<   ||k7  r|||   d<   |||   d<   t        j
                  |        y# t        $ r"}	t        j                  d| d| d      |	d}	~	ww xY w)a  Remove the edge between u and v.

        Parameters
        ----------
        u, v : nodes
        Remove the half-edges (u, v) and (v, u) and update the
        edge ordering around the removed edge.

        Raises
        ------
        NetworkXError
        If there is not an edge between u and v.

        See Also
        --------
        remove_edges_from : remove a collection of edges
        r   rx   z	The edge -r   N)r   r   r   r   r   r   )
r.   r#   r%   r   succs_vuv_cwuv_ccwvu_cwvu_ccwr   s
             r
   r   zPlanarEmbedding.remove_edge  s   $	jjmGjjmGAJt$EQZ&FAJt$EQZ&F


1a 


1a Ez(.u%(-%Ez(.u%(-%
 		  	""A3as"BC	s   BB& &	C/CCc                     |D ]=  }|dd \  }}|| j                   v s|| j                   |   v s,| j                  ||       ? y)a  Remove all edges specified in ebunch.

        Parameters
        ----------
        ebunch: list or container of edge tuples
            Each pair of half-edges between the nodes given in the tuples
            will be removed from the graph. The nodes can be passed as:

                - 2-tuples (u, v) half-edges (u, v) and (v, u).
                - 3-tuples (u, v, k) where k is ignored.

        See Also
        --------
        remove_edge : remove a single edge

        Notes
        -----
        Will fail silently if an edge in ebunch is not in the graph.

        Examples
        --------
        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
        >>> ebunch = [(1, 2), (2, 3)]
        >>> G.remove_edges_from(ebunch)
        Nrl   )r   r   )r.   ebunchrj   r#   r%   s        r
   remove_edges_fromz!PlanarEmbedding.remove_edges_from  sN    4  	'ARa5DAq DJJ1

1#5  A&	'r   c                 X   || j                   v r1| j                   |   r"t        t        | j                   |               }nd}| j                  |||       || j                   v r1| j                   |   r"t        t        | j                   |               }nd}| j                  |||       y)a;  Adds half-edges for (v, w) and (w, v) at some position.

        This method should only be called if v and w are in different
        components, or it might break the embedding.
        This especially means that if `connect_components(v, w)`
        is called it is not allowed to call `connect_components(w, v)`
        afterwards. The neighbor orientations in both directions are
        all set correctly after the first call.

        Parameters
        ----------
        v : node
        w : node

        See Also
        --------
        add_half_edge
        Nr   )r   r   r   r   )r.   r%   r   rW   s       r
   connect_componentsz"PlanarEmbedding.connect_components  s    & 

?tzz!}x

1./CC1aC(

?tzz!}x

1./CC1aC(r   c                     | j                   j                  |      }|rt        t        |            nd}| j	                  |||       y)at  Add a half-edge and set end_node as start_node's leftmost neighbor.

        The new edge is inserted counterclockwise with respect to the current
        leftmost neighbor, if there is one.

        Parameters
        ----------
        start_node : node
        end_node : node

        See Also
        --------
        add_half_edge
        connect_components
        Nr   )r   r   r   r   r   )r.   r   r   r   r   s        r
   r   z#PlanarEmbedding.add_half_edge_first  s?      

z* 16tHUO,4:xLAr   c                      | |   |   d   }||fS )zReturns the following half-edge left of a face.

        Parameters
        ----------
        v : node
        w : node

        Returns
        -------
        half-edge : tuple
        rx   r=   )r.   r%   r   new_nodes       r
   next_face_half_edgez#PlanarEmbedding.next_face_half_edge,  s      71:e$({r   c                 <   |
t               }|g}|j                  ||f       |}|}| |   |   d   }||k7  s||k7  r`|j                  |       | j                  ||      \  }}||f|v rt	        j
                  d      |j                  ||f       ||k7  rZ||k7  r`|S )a  Returns nodes on the face that belong to the half-edge (v, w).

        The face that is traversed lies to the right of the half-edge (in an
        orientation where v is below w).

        Optionally it is possible to pass a set to which all encountered half
        edges are added. Before calling this method, this set must not include
        any half-edges that belong to the face.

        Parameters
        ----------
        v : node
            Start node of half-edge.
        w : node
            End node of half-edge.
        mark_half_edges: set, optional
            Set to which all encountered half-edges are added.

        Returns
        -------
        face : list
            A list of nodes that lie on this face.
        r   z&Bad planar embedding. Impossible face.)r   addr{   r	  r   r   )r.   r%   r   mark_half_edges
face_nodes	prev_nodecur_nodeincoming_nodes           r
   r   zPlanarEmbedding.traverse_face;  s    0 "!eOS
QF#	Q
4(!myM9h'"&":":9h"OIx8$7**+STTH 56 !myM9 r   c                      y)zA valid PlanarEmbedding is undirected.

        All reverse edges are contained, i.e. for every existing
        half-edge (v, w) the half-edge in the opposite direction (w, v) is also
        contained.
        Fr=   r1   s    r
   is_directedzPlanarEmbedding.is_directedf  s     r   c                    |du rt         j                  j                  |       S | j                         }|j                  j                  | j                         |j                  d | j                  j                         D               t        | j                  |+  d | j                  j                         D               |S )NTc              3   F   K   | ]  \  }}||j                         f  y wr*   )r4   ).0r   ds      r
   	<genexpr>z'PlanarEmbedding.copy.<locals>.<genexpr>t  s     F41a!QVVXFs   !c              3   x   K   | ]2  \  }}|j                         D ]  \  }}|||j                         f  4 y wr*   )itemsr4   )r  r#   r$   r%   datadicts        r
   r  z'PlanarEmbedding.copy.<locals>.<genexpr>u  sH      0
4#zz|0
 8 8==?#0
#0
s   8:)r   
graphviewsgeneric_graph_viewr   graphupdaterf   r   r  r   r   _adj)r.   as_viewr	   r   s      r
   r4   zPlanarEmbedding.copyo  s    d?==33D99NN	tzz"	F4::3C3C3EFFdnna/ 0
99??,0
 	

 r   r*   F)r9   r:   r;   r<   r/   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r	  r   r  r4   __classcell__)r   s   @r
   r   r      s    Wr8
&,'R$:5. 9=$ INV80tH:I8'R'B)<B,)V r   r   r!  )collectionsr   networkxr   __all___dispatchabler   r   r   r   r   r(   r?   rM   r   ri   r   r=   r   r
   <module>r'     s    # 
= 7 7@ %H &HV % & %# &#L % &,
 
8
 
8{ {|z	bjj z	r   