
    h                     h   S SK Jr  S SKr/ SQr\R
                  S 5       r\R
                  " SS9SS j5       r\R
                  " SS9SS j5       r\R
                  " SS9S	 5       r	\R
                  " SS9S
 5       r
 " S S5      r " S S5      rS r " S S5      r " S S\R                  5      rg)    )defaultdictN)check_planarity	is_planarPlanarEmbeddingc                     [        U SS9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    O/var/www/html/env/lib/python3.13/site-packages/networkx/algorithms/planarity.pyr   r      s    < 1U3A66    T)returns_graphc                 p    [        U 5      nUR                  5       nUc  U(       a  S[        U 5      4$ gSU4$ )a  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                 p    [        U 5      nUR                  5       nUc  U(       a  S[        U 5      4$ gSU4$ )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                 |   [         R                  " U 5      n [        U 5      S   (       a  [         R                  " S5      e[         R                  " 5       nU  Ha  n[	        X   5      nU HK  nU R                  X$5        [        U 5      S   (       d  M)  U R                  X$5        UR                  X$5        MM     Mc     U$ )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ADzAMM!q!!$$

1 !!!'	   Or   c                 |   [         R                  " U 5      n [        U 5      S   (       a  [         R                  " S5      e[         R                  " 5       nU  Ha  n[	        X   5      nU HK  nU R                  X$5        [        U 5      S   (       d  M)  U R                  X$5        UR                  X$5        MM     Mc     U$ )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ADzAMM!(+A..

1 !!!'	   Or   c                   4    \ rS rSrSrS	S jrS rS rS rSr	g)
Interval   zRepresents 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                     Xl         X l        g Nlowhigh)selfr-   r.   s      r
   __init__Interval.__init__   s    	r   c                 H    U R                   SL =(       a    U R                  SL $ )zCheck if the interval is emptyNr,   r/   s    r
   emptyInterval.empty   s    xx45DII$55r   c                 B    [        U R                  U R                  5      $ )zReturns a copy of this interval)r(   r-   r.   r3   s    r
   copyInterval.copy   s    $)),,r   c                     U R                  5       (       + =(       a)    UR                  U R                     UR                  U   :  $ )z0Returns True if interval I conflicts with edge b)r4   lowptr.   )r/   br   s      r
   conflictingInterval.conflicting   s=     

 L%%dii0?3H3H3KK	
r   )r.   r-   )NN)
__name__
__module____qualname____firstlineno____doc__r0   r4   r7   r<   __static_attributes__ r   r
   r(   r(      s    6-
r   r(   c                   F    \ rS rSrSr\" 5       \" 5       4S jrS rS rSr	g)ConflictPair   zRepresents 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                     Xl         X l        g r+   leftright)r/   rJ   rK   s      r
   r0   ConflictPair.__init__   s    	
r   c                 J    U R                   nU R                  U l         Xl        g)zSwap left and right intervalsNrI   )r/   temps     r
   swapConflictPair.swap   s    yyJJ	
r   c                    U R                   R                  5       (       a#  UR                  U R                  R                     $ U R                  R                  5       (       a#  UR                  U R                   R                     $ [        UR                  U R                   R                     UR                  U R                  R                     5      $ )z.Returns the lowest lowpoint of a conflict pair)rJ   r4   r:   rK   r-   min)r/   r   s     r
   lowestConflictPair.lowest   s    99??"((88::"((77!!$))--0/2G2G

2W
 	
r   rI   N)
r>   r?   r@   rA   rB   r(   r0   rO   rS   rC   rD   r   r
   rF   rF      s!     %Jhj 
r   rF   c                     U (       d  gU S   $ )z(Returns the element on top of the stack.NrD   )ls    r
   top_of_stackrX      s    R5Lr   c                   n    \ rS rSrSr/ SQrS rS rS rS r	S r
S	 rS
 rS rS rS rS rS rS rSrg)r   i  z5A class to maintain the state during planarity check.)r	   rootsheightr:   lowpt2nesting_depthparent_edgeDGadjsordered_adjsrefsideSstack_bottom
lowpt_edgeleft_ref	right_refr   c                    [         R                  " 5       U l        U R                  R                  UR                  5        UR
                   H3  nUS   US   :w  d  M  U R                  R                  US   US   5        M5     / U l        [        S 5      U l	        0 U l
        0 U l        0 U l        [        S 5      U l        [         R                  " 5       U l        U R                  R                  UR                  5        0 U l        0 U l        [        S 5      U l        [        S 5      U l        / U l        0 U l        0 U l        0 U l        0 U l        [3        5       U l        g )Nr      c                      g r+   rD   rD   r   r
   <lambda>&LRPlanarity.__init__.<locals>.<lambda>%  s    $r   c                      g r+   rD   rD   r   r
   rl   rm   ,  s    tr   c                      g r+   rD   rD   r   r
   rl   rm   5  s    tr   c                      g)Nrj   rD   rD   r   r
   rl   rm   6  s    r   )r   r   r	   add_nodes_fromnodesedgesr    rZ   r   r[   r:   r\   r]   r^   DiGraphr_   r`   ra   rb   rc   rd   re   rf   rg   rh   r   r   )r/   r	   es      r
   r0   LRPlanarity.__init__  s   agg&Atqt|!ad+  
 ",/
 '|4 **,qww'	|,	*	 (*r   c                   ^ ^ T R                   R                  5       S:  a=  T R                   R                  5       ST R                   R                  5       -  S-
  :  a  gT R                    H(  m[        T R                   T   5      T R                  T'   M*     T R                    HP  mT R
                  T   b  M  ST R
                  T'   T R                  R                  T5        T R                  T5        MR     ST l         ST l	        ST l        T R                   H,  m[        T R                  T   U U4S jS9T R                  T'   M.     T R                   H  mT R                  T5      (       a  M    g   ST l        ST l        ST l        ST l        ST l        T R                  R$                   H1  nT R'                  U5      T R(                  U   -  T R(                  U'   M3     T R*                  R-                  T R                  R.                  5        T R                   H`  m[        T R                  T   U U4S jS9T R                  T'   SnT R                  T    H  nT R*                  R1                  TX2S	9  UnM!     Mb     ST l
        ST l        ST l        T R                   H  mT R5                  T5        M     ST l        ST l        ST l        ST l        ST l        ST l        T R*                  $ )
zExecute the LR planarity test.

Returns
-------
embedding : dict
    If the graph is planar an embedding is returned. Otherwise None.
         Nr   c                 &   > TR                   TU 4   $ r+   r]   xr/   r%   s    r
   rl   *LRPlanarity.lr_planarity.<locals>.<lambda>b      $*<*<aV*Dr   keyc                 &   > TR                   TU 4   $ r+   r|   r}   s    r
   rl   r   v  r   r   ccw)r	   ordersizer   r`   r[   rZ   appenddfs_orientationr\   r_   sortedra   dfs_testingr:   rd   re   rf   rs   signr]   r   rq   rr   add_half_edgerb   dfs_embeddingr^   rg   rh   rc   r/   ru   previous_nodewr%   s   `   @r
   r   LRPlanarity.lr_planarityB  st    66<<>A$&&++-!dfflln2Dq2H"H Aq	?DIIaL  A{{1~%!"A

!!!$$$Q'	  	 A#)
 D$Da  
 A##A&& 
 
 A$(IIaL43E3Ea3H$HDq!  	%%dggmm4A#)
 D$Da  !M&&q),,Q,E ! *  ! Aq!  
 	~~r   c                   ^ ^ T R                   R                  5       S:  a=  T R                   R                  5       ST R                   R                  5       -  S-
  :  a  gT R                    HP  mT R                  T   b  M  ST R                  T'   T R                  R                  T5        T R                  T5        MR     ST l         T R                   H,  m[        T R                  T   U U4S jS9T R                  T'   M.     T R                   H  mT R                  T5      (       a  M    g   T R                  R                   H1  nT R                  U5      T R                  U   -  T R                  U'   M3     T R                  R                  T R                  R                   5        T R                   H`  m[        T R                  T   U U4S jS9T R                  T'   SnT R                  T    H  nT R                  R#                  TX2S	9  UnM!     Mb     T R                   H  mT R%                  T5        M     T R                  $ )
z*Recursive version of :meth:`lr_planarity`.rx   ry   rz   Nr   c                 &   > TR                   TU 4   $ r+   r|   r}   s    r
   rl   4LRPlanarity.lr_planarity_recursive.<locals>.<lambda>  r   r   r   c                 &   > TR                   TU 4   $ r+   r|   r}   s    r
   rl   r     r   r   r   )r	   r   r   r[   rZ   r   dfs_orientation_recursiver_   r   ra   dfs_testing_recursivers   sign_recursiver]   r   rq   rr   r   dfs_embedding_recursiver   s   `   @r
   r   "LRPlanarity.lr_planarity_recursive  s   66<<>A$&&++-!dfflln2Dq2H"H A{{1~%!"A

!!!$..q1	   A#)
 D$Da  
 A--a00  A$($7$7$:T=O=OPQ=R$RDq!  	%%dggmm4A#)
 D$Da  !M&&q),,Q,E ! *  A((+  ~~r   c                    U/n[        S 5      n[        S 5      nU(       Ga  UR                  5       nU R                  U   nU R                  U   X1   S  GH  nX4nXG   (       Gd  X4U R                  R
                  ;   d  Xa4U R                  R
                  ;   a  X1==   S-  ss'   MU  U R                  R                  X5        U R                  U   U R                  U'   U R                  U   U R                  U'   U R                  U   cV  XpR                  U'   U R                  U   S-   U R                  U'   UR                  U5        UR                  U5        SXG'     GO}U R                  U   U R                  U'   SU R                  U   -  U R                  U'   U R                  U   U R                  U   :  a  U R                  U==   S-  ss'   Ub  U R                  U   U R                  U   :  aP  [        U R                  U   U R                  U   5      U R                  U'   U R                  U   U R                  U'   OU R                  U   U R                  U   :  a4  [        U R                  U   U R                  U   5      U R                  U'   O3[        U R                  U   U R                  U   5      U R                  U'   X1==   S-  ss'   GM     U(       a  GM  gg)z=Orient the graph by DFS, compute lowpoints and nesting order.c                      gNr   rD   rD   r   r
   rl   -LRPlanarity.dfs_orientation.<locals>.<lambda>      !r   c                      gNFrD   rD   r   r
   rl   r         r   Nrj   Trx   )r   popr^   r`   r_   rs   r    r[   r:   r\   r   r]   rR   )r/   r%   	dfs_stackind	skip_initru   r   vws           r
   r   LRPlanarity.dfs_orientation  s\    C	)$.	A  #AYYq\#&(+V }}v.1&DGGMM2I! 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!M ,	 ir   c                    U R                   U   nU R                  U    GHT  nX4U R                  R                  ;   d  X14U R                  R                  ;   a  M<  X4nU R                  R	                  X5        U R
                  U   U R                  U'   U R
                  U   U R                  U'   U R
                  U   c?  X@R                   U'   U R
                  U   S-   U R
                  U'   U R                  U5        OU R
                  U   U R                  U'   SU R                  U   -  U R                  U'   U R                  U   U R
                  U   :  a  U R                  U==   S-  ss'   Uc  GMY  U R                  U   U R                  U   :  aR  [        U R                  U   U R                  U   5      U R                  U'   U R                  U   U R                  U'   GM  U R                  U   U R                  U   :  a6  [        U R                  U   U R                  U   5      U R                  U'   GM!  [        U R                  U   U R                  U   5      U R                  U'   GMW     g)z-Recursive version of :meth:`dfs_orientation`.Nrj   rx   )r^   r	   r_   rs   r    r[   r:   r\   r   r]   rR   )r/   r%   ru   r   r   s        r
   r   %LRPlanarity.dfs_orientation_recursive  s   QAv&1&DGGMM*A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 r   c           	      B   U/n[        S 5      n[        S 5      nU(       Ga|  UR                  5       nU R                  U   nSnU R                  U   X1   S  GH  nX4nXH   (       d  [	        U R
                  5      U R                  U'   XR                  U   :X  a*  UR                  U5        UR                  U5        SXH'   Sn  OXR                  U'   U R
                  R                  [        [        X5      S95        U R                  U   U R                  U   :  aJ  XpR                  U   S   :X  a  U R                  U   U R                  U'   OU R                  X5      (       d    gX1==   S-  ss'   GM      U(       d  Ub  U R                  U5        U(       a  GM|  g)	zTest for LR partition.c                      gr   rD   rD   r   r
   rl   )LRPlanarity.dfs_testing.<locals>.<lambda>  r   r   c                      gr   rD   rD   r   r
   rl   r     r   r   FNTrK   r   rj   )r   r   r^   ra   rX   rd   re   r   rf   rF   r(   r:   r[   add_constraintsremove_back_edges)	r/   r%   r   r   r   ru   
skip_finalr   eis	            r
   r   LRPlanarity.dfs_testing  ss    C	)$.	A  #AJ&&q)#&(3V },8,@D%%b)--a00!((+!((+(,	%)
.0+l"9I&JK ::b>DKKN2--a033-1__R-@*#33B::#(!3 46 =**1-I iL r   c           	      b   U R                   U   nU R                  U    H  nX4n[        U R                  5      U R                  U'   X@R                   U   :X  a  U R                  U5      (       d    gO9X@R                  U'   U R                  R                  [        [        XD5      S95        U R                  U   U R                  U   :  d  M  X0R                  U   S   :X  a  U R                  U   U R                  U'   M  U R                  XB5      (       a  M    g   Ub  U R                  U5        g)z)Recursive version of :meth:`dfs_testing`.Fr   r   T)r^   ra   rX   rd   re   r   rf   r   rF   r(   r:   r[   r   r   )r/   r%   ru   r   r   s        r
   r   !LRPlanarity.dfs_testing_recursiveG  s   Q""1%AB$0$8Db!%%a((11!44  5 ')#l"1ABC zz"~A.))!,Q//)-)<DOOA&//66$# &( =""1%r   c                    [        5       n U R                  R                  5       nUR                  R	                  5       (       d  UR                  5         UR                  R	                  5       (       d  gU R                  UR                  R                     U R                  U   :  a  UR                  R	                  5       (       a   UR                  R                  5       Ul        O7UR                  R                  U R                  UR                  R                  '   UR                  R                  UR                  l        O0U R                  U   U R                  UR                  R                  '   [        U R                  5      U R                  U   :X  a  OGM  [        U R                  5      R                  R                  X5      (       d4  [        U R                  5      R                  R                  X5      (       Ga  U R                  R                  5       nUR                  R                  X5      (       a  UR                  5         UR                  R                  X5      (       a  gUR                  R                  U R                  UR                  R                  '   UR                  R                  b%  UR                  R                  UR                  l        UR                  R	                  5       (       a   UR                  R                  5       Ul        O7UR                  R                  U R                  UR                  R                  '   UR                  R                  UR                  l        [        U R                  5      R                  R                  X5      (       a  GM  [        U R                  5      R                  R                  X5      (       a  GM  UR                  R	                  5       (       a  UR                  R	                  5       (       d  U R                  R!                  U5        g)NTF)rF   rd   r   rJ   r4   rO   r:   rK   r-   r7   r.   rb   rf   rX   re   r<   r   )r/   r   ru   PQs        r
   r   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""2,,ww""2,,$%GGLLDHHQWW[[!ww{{&ggkkvv||~~'(vv{{$AFFJ# 466"''33B==FFB

%B%B& B&& 177==??FFMM!r   c                    US   nU R                   (       a  [        U R                   5      R                  U 5      U R                  U   :X  a  U R                   R	                  5       nUR
                  R                  b#  SU R                  UR
                  R                  '   U R                   (       a7  [        U R                   5      R                  U 5      U R                  U   :X  a  M  U R                   (       Ga  U R                   R	                  5       nUR
                  R                  b  UR
                  R                  S   U:X  ah  U R                  UR
                  R                     UR
                  l        UR
                  R                  b  UR
                  R                  S   U:X  a  Mh  UR
                  R                  c  UR
                  R                  bk  UR                  R                  U R                  UR
                  R                  '   SU R                  UR
                  R                  '   S UR
                  l        UR                  R                  b  UR                  R                  S   U:X  ah  U R                  UR                  R                     UR                  l        UR                  R                  b  UR                  R                  S   U:X  a  Mh  UR                  R                  c  UR                  R                  bk  UR
                  R                  U R                  UR                  R                  '   SU R                  UR                  R                  '   S UR                  l        U R                   R                  U5        U R                  U   U R                  U   :  a  [        U R                   5      R
                  R                  n[        U R                   5      R                  R                  nUb2  Ub   U R                  U   U R                  U   :  a  X@R                  U'   g XPR                  U'   g g )Nr   rV   rj   )rd   rX   rS   r[   r   rJ   r-   rc   r.   rb   rK   r   r:   )r/   ru   r#   r   hlhrs         r
   r   LRPlanarity.remove_back_edges  s   aD ffdff-44T:dkk!nL

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

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   U/n[        S 5      nU(       Ga#  UR                  5       nU R                  U   X1   S  H  nX1==   S-  ss'   X4nXPR                  U   :X  a[  U R                  R                  XA5        X@R                  U'   X@R                  U'   UR                  U5        UR                  U5          OuU R                  U   S:X  a)  U R                  R                  XAU R                  U   S9  M  U R                  R                  XAU R                  U   S9  XR                  U'   M     U(       a  GM"  gg)zCompletes the embedding.c                      gr   rD   rD   r   r
   rl   +LRPlanarity.dfs_embedding.<locals>.<lambda>  r   r   Nrj   r   cw)r   r   ra   r^   r   add_half_edge_firstrg   rh   r   rc   r   )r/   r%   r   r   r   r   s         r
   r   LRPlanarity.dfs_embedding  s    C	)$A&&q)#&(3!V))!,,NN66q<'(MM!$()NN1%$$Q'$$Q'yy})44Qt~~a?P4Q44QdmmA>N4O+,a(# 4 ir   c                    U R                   U    H  nX4nX0R                  U   :X  aJ  U R                  R                  X!5        X R                  U'   X R
                  U'   U R                  U5        Mb  U R                  U   S:X  a)  U R                  R                  X!U R
                  U   S9  M  U R                  R                  X!U R                  U   S9  XR                  U'   M     g)z+Recursive version of :meth:`dfs_embedding`.rj   r   r   N)	ra   r^   r   r   rg   rh   r   rc   r   )r/   r%   r   r   s       r
   r   #LRPlanarity.dfs_embedding_recursive  s    ""1%AB%%a((2218#$a $%q!,,Q/99R=A%NN004>>!;L0M NN00$--:J0K'(MM!$ &r   c                    U/n[        S 5      nU(       a  UR                  5       nU R                  U   bP  UR                  U5        UR                  U R                  U   5        U R                  U   X1'   SU R                  U'   O&U R                  U==   U R                  X1      -  ss'   U(       a  M  U R                  U   $ )z:Resolve the relative side of an edge to the absolute side.c                      g r+   rD   rD   r   r
   rl   "LRPlanarity.sign.<locals>.<lambda>  s    dr   N)r   r   rb   r   rc   )r/   ru   r   old_refs       r
   r   LRPlanarity.sign  s     C	l+Axx{&  #  !-!XXa[
"		!		'* 55 i yy|r   c                     U R                   U   bJ  U R                  U   U R                  U R                   U   5      -  U R                  U'   SU R                   U'   U R                  U   $ )z"Recursive version of :meth:`sign`.N)rb   rc   r   )r/   ru   s     r
   r   LRPlanarity.sign_recursive  sX    88A;"99Q<$*=*=dhhqk*JJDIIaLDHHQKyy|r   )r_   r	   rd   r`   r   r[   rg   r:   r\   rf   r]   ra   r^   rb   rh   rZ   rc   re   N)r>   r?   r@   rA   rB   	__slots__r0   r   r   r   r   r   r   r   r   r   r   r   r   rC   rD   r   r
   r   r     sW    ?I*&+PM^-^3jJB/b6*X%!N-:)$(r   r   c                      ^  \ rS rSrSrSU 4S jjrS rS rS rS r	S	 r
S
 rSSS.U 4S jjrS rS rS rS rS rS rS rS rSS jrS rSU 4S jjrSrU =r$ )r   i   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U ]  " SSU0UD6  U R                  U l        U R                  U l        U R                  U l        g )Nincoming_graph_datarD   )superr0   _PlanarEmbedding__forbiddenr    add_edges_fromadd_weighted_edges_from)r/   r   attr	__class__s      r
   r0   PlanarEmbedding.__init__Z  sB    I-@IDI(("..'+'7'7$r   c                     [        S5      e)zjForbidden 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
   __forbiddenPlanarEmbedding.__forbidden`  s     "K
 	
r   c                 T    0 nU  H  n[        U R                  U5      5      X'   M!     U$ )zConverts 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_dataPlanarEmbedding.get_dataj  s0     	A 7 7 :;IL r   c                 f    U H+  nSn[        X   5       H  nU R                  X$US9  UnM     M-     g)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%   rb   r   s        r
   set_dataPlanarEmbedding.set_data}  s<      ACdg&""1C"0 ' r   c                     U R                   U    HG  nU R                  U   nX1   S   nX1   S   nX1	 U R                   U   U	 X:w  d  M9  XSU   S'   XCU   S'   MI     U R                  U	 U R                  U	 U R                   U	 [        R                  " U 5        g! [         a   n[        R
                  " SU S35      UeSnAff = f)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   r   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_nodePlanarEmbedding.remove_node  s    ,	ZZ]**Q-
4( E*JJJqM!$:,2EN5),1FOD) # 

1

1

1
 		  	""A3>?	s   AB 
9B 
C$B??Cc                 Z    U H%  nX R                   ;   d  M  U R                  U5        M'     g)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/   rr   r   s      r
   remove_nodes_from!PlanarEmbedding.remove_nodes_from  s%    0 AJJ  # r   c              #      #    U R                   U   nU(       d  g[        [        U5      5      nUv   X#   S   nX4:w  a  Uv   X$   S   nX4:w  a  M  gg7f)zjGenerator 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   "PlanarEmbedding.neighbors_cw_order  s\      

1(5/*
(.( .t4L (s   AAAr   r   c                  > U R                   R                  U5      nU(       a  [        [        U R                   U   5      5      nUb\  X5;  a  [        R
                  " S5      eUb  [        R
                  " S5      eXS   S   n[        T
U ]  XX7S9  X%U   S'   X%U   S'   X6:g  nOZUbA  XE;  a  [        R
                  " S5      eXT   S   n	[        T
U ]  XXS9  X%U	   S'   X%U   S'   SnO[        R
                  " S	5      eU(       a  UR                  U5      XV'   ggUc  Ub  [        R
                  " S
5      e[        T
U ]  XX"S9  g)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.r   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.)r   r   )	r   getr   r   r   r   r   r    r   )r/   r   end_noder   r   r   leftmost_nbrref_ccwmove_leftmost_nbr_to_endref_cwr   s             r
   r   PlanarEmbedding.add_half_edge  sb   D 

z*J)? @AL~?**+NOO?**+QRR)E* " J'/gt$#+b	%  ,.+=(#**+UVVD) & J'/fe$#+c
4 +/(&&b  ( ',ii&=#	 ( ~&&'@AAGZxMr   c                    U  H  n [        U R                  U5      5      n[        X   5      nX%:w  a  Sn[        R                  " U5      eX    H1  nU R                  Xa5      (       a  M  Sn[        R                  " U5      e   M     [        5       n[        R                  " U 5       H  n[        U5      S:X  a  M  [        U5      n	Sn
SnU H@  nU R                  U5       H(  nU
S-  n
X4U;  d  M  US-  nU R                  XU5        M*     MB     U
S-  nX-
  U-   S:w  d  M{  Sn[        R                  " U5      e   g! [         a!  nSU 3n[        R                  " U5      UeSnAff = f)	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.rj   r   rx   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_structurePlanarEmbedding.check_structure;  st   $ A9!$"9"9!"<=
  LM+K**3//W}}Q**IC..s33	  $ !U006I9~"IINI003A"a'Nv%77!Q	**11CD 4  '!+I$y0A5O**3//' 7!  9MaSQ**3/S89s   D>>
E)E$$E)c                 $    U R                  XUS9  g)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_ccw!PlanarEmbedding.add_half_edge_ccwu  s    6 	:4FGr   c                 $    U R                  XUS9  g)a  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
r   Nr  r  s       r
   add_half_edge_cw PlanarEmbedding.add_half_edge_cw  s    4 	:5GHr   c                     U R                   U   nU R                   U   nX2   S   nX2   S   nXA   S   nXA   S   nX2	 U R                  U   U	 XA	 U R                  U   U	 X%:w  a  XcU   S'   XSU   S'   X:w  a  XU   S'   XtU   S'   [        R
                  " U 5        g! [         a#  n	[        R                  " SU SU S35      U	eSn	A	ff = f)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   r   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   PlanarEmbedding.remove_edge  s    $	jjmGjjmGJt$EZ&FJt$EZ&F


1a 


1a z(.u%(-%z(.u%(-%
 		  	""A3as"BC	s   BB 
C
'CC
c                     U H@  nUSS u  p4X0R                   ;   d  M  X@R                   U   ;   d  M/  U R                  X45        MB     g)ai  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)
Nrx   )r   r   )r/   ebunchru   r#   r%   s        r
   remove_edges_from!PlanarEmbedding.remove_edges_from  sA    4 ARa5DA JJ1

1#5  & r   c                 `   XR                   ;   a6  U R                   U   (       a"  [        [        U R                   U   5      5      nOSnU R                  XUS9  X R                   ;   a6  U R                   U   (       a"  [        [        U R                   U   5      5      nOSnU R                  X!US9  g)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   rb   s       r
   connect_components"PlanarEmbedding.connect_components  s    & 

?tzz!}x

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

?tzz!}x

1./CC1C(r   c                     U R                   R                  U5      nU(       a  [        [        U5      5      OSnU R	                  XUS9  g)a  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   #PlanarEmbedding.add_half_edge_first  s=      

z* 16tHUO,4:LAr   c                     X   U   S   nX#4$ )z|Returns the following half-edge left of a face.

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

Returns
-------
half-edge : tuple
r   rD   )r/   r%   r   new_nodes       r
   next_face_half_edge#PlanarEmbedding.next_face_half_edge,  s     71:e${r   c                 <   Uc
  [        5       nU/nUR                  X45        UnUnX   U   S   nXa:w  d  XW:w  aa  UR                  U5        U R                  XV5      u  pVXV4U;   a  [        R
                  " S5      eUR                  XV45        Xa:w  a  MZ  XW:w  a  Ma  U$ )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   r8  r   r   )r/   r%   r   mark_half_edges
face_nodes	prev_nodecur_nodeincoming_nodes           r
   r  PlanarEmbedding.traverse_face;  s    0 "!eOS
QF#	
4(my9h'"&":":9"OI$7**+STT 56 my9 r   c                     g)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.
FrD   r3   s    r
   is_directedPlanarEmbedding.is_directedf  s     r   c                   > USL a  [         R                  R                  U 5      $ U R                  5       nUR                  R                  U R                  5        UR                  S U R                  R                  5        5       5        [        U R                  U]+  S U R                  R                  5        5       5        U$ )NTc              3   H   #    U  H  u  pXR                  5       4v   M     g 7fr+   )r7   ).0r   ds      r
   	<genexpr>'PlanarEmbedding.copy.<locals>.<genexpr>t  s     F3E41!VVX3Es    "c              3   ~   #    U  H3  u  pUR                  5         H  u  p4XUR                  5       4v   M     M5     g 7fr+   )itemsr7   )rG  r#   r$   r%   datadicts        r
   rI  rJ  u  s9      0
,#zz| 8==?#+ $,s   ;=)r   
graphviewsgeneric_graph_viewr   graphupdaterq   r   rL  r   r   _adj)r/   as_viewr	   r   s      r
   r7   PlanarEmbedding.copyo  s    d?==33D99NN	tzz"	F4::3C3C3EFFdnna/ 0
99??,0
 	

 r   )r    r   r   r+   F)r>   r?   r@   rA   rB   r0   r   r   r   r   r   r   r   r  r   r#  r   r/  r2  r   r8  r  rC  r7   rC   __classcell__)r   s   @r
   r   r      s    Wr8
&,'R$:5. 9=$ IN INV80tH:I8'R'B)<B,)V r   r   rU  )collectionsr   networkxr   __all___dispatchabler   r   r   r   r   r(   rF   rX   r   rt   r   rD   r   r
   <module>r[     s    # 
= 7 7@ %H &HV % & %# &#L % &,
 
8
 
8{ {|z	bjj z	r   