
    sh                    P   S r SSKrSSKJr  / SQrS r\" S5      S0S j5       rS1S
 jr S2S jr	      S3S jr
\" S5                 S4SSS.S jj5       r\r\" S5       S5S j5       r\" S5               S6S j5       rS r       S7S jrS rS rS8S jrS9S jrS9S jrS1S jr      S:S  jr S;S! jr\" S"5            S<SSS#.S$ jj5       r\" S"5      \R4                  " SS%S&0S'9 S=S(SS)SSSSSSSSSSSS*.S+ jj5       5       rS>S, jrS>S- jrSS	SSS..S/ jrg)?a  
******
Layout
******

Node positioning algorithms for graph drawing.

For `random_layout()` the possible resulting shape
is a square of side [0, scale] (default: [0, 1])
Changing `center` shifts the layout by that amount.

For the other layout routines, the extent is
[center - scale, center + scale] (default: [-1, 1]).

Warning: Most layout routines have only been tested in 2-dimensions.

    N)np_random_state)bipartite_layoutcircular_layoutforceatlas2_layoutkamada_kawai_layoutrandom_layoutrescale_layoutrescale_layout_dictshell_layoutspring_layoutspectral_layoutplanar_layoutfruchterman_reingold_layoutspiral_layoutmultipartite_layout
bfs_layout
arf_layoutc                 "   SS K n[        U [        R                  5      (       d(  [        R                  " 5       nUR	                  U 5        Un Uc  UR                  U5      nOUR                  U5      n[        U5      U:w  a  Sn[        U5      eX4$ )Nr   z;length of center coordinates must match dimension of layout)	numpy
isinstancenxGraphadd_nodes_fromzerosasarraylen
ValueError)Gcenterdimnpempty_graphmsgs         k/Users/tiagomarins/Projetos/claudeai/copy_bank/venv/lib/python3.13/site-packages/networkx/drawing/layout.py_process_paramsr%   *   sw    a""hhj""1%~#F#
6{cKo9          c                     SSK n[        XU5      u  pUR                  [        U 5      U5      U-   nUR	                  UR
                  5      n[        [        X5      5      nUb  [        R                  " XU5        U$ )a  Position nodes uniformly at random in the unit square.

For every node, a position is generated by choosing each of dim
coordinates uniformly at random on the interval [0.0, 1.0).

NumPy (http://scipy.org) is required for this function.

Parameters
----------
G : NetworkX graph or list of nodes
    A position will be assigned to every node in G.

center : array-like or None
    Coordinate pair around which to center the layout.

dim : int
    Dimension of layout.

seed : int, RandomState instance or None  optional (default=None)
    Set the random state for deterministic node layouts.
    If int, `seed` is the seed used by the random number generator,
    if numpy.random.RandomState instance, `seed` is the random
    number generator,
    if None, the random number generator is the RandomState instance used
    by numpy.random.

store_pos_as : str, default None
    If non-None, the position of each node will be stored on the graph as
    an attribute with this string as its name, which can be accessed with
    ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.

Returns
-------
pos : dict
    A dictionary of positions keyed by node

Examples
--------
>>> from pprint import pprint
>>> G = nx.lollipop_graph(4, 3)
>>> pos = nx.random_layout(G)
>>> # suppress the returned dict and store on the graph directly
>>> _ = nx.random_layout(G, seed=42, store_pos_as="pos")
>>> pprint(nx.get_node_attributes(G, "pos"))
{0: array([0.37454012, 0.9507143 ], dtype=float32),
 1: array([0.7319939, 0.5986585], dtype=float32),
 2: array([0.15601864, 0.15599452], dtype=float32),
 3: array([0.05808361, 0.8661761 ], dtype=float32),
 4: array([0.601115 , 0.7080726], dtype=float32),
 5: array([0.02058449, 0.96990985], dtype=float32),
 6: array([0.83244264, 0.21233912], dtype=float32)}
r   N)
r   r%   randr   astypefloat32dictzipr   set_node_attributes)r   r   r    seedstore_pos_asr!   poss          r$   r   r   ?   sj    l 3/IA
))CFC
 6
)C
**RZZ
 C
s1{
C
q|4Jr&      c           	         SSK nUS:  a  [        S5      e[        XU5      u  p[        SUS-
  5      n[	        U 5      S:X  a  0 nO[	        U 5      S:X  a"  [
        R                  R                  U 5      U0nOUR                  SS[	        U 5      S-   5      SS S-  UR                  -  nUR                  UR                  5      nUR                  UR                  U5      UR                  U5      UR                  [	        U 5      U45      /5      n[!        XqS9U-   n[#        [%        X5      5      nUb  [
        R&                  " XU5        U$ )af  Position nodes on a circle.

Parameters
----------
G : NetworkX graph or list of nodes
    A position will be assigned to every node in G.

scale : number (default: 1)
    Scale factor for positions.

center : array-like or None
    Coordinate pair around which to center the layout.

dim : int
    Dimension of layout.
    If dim>2, the remaining dimensions are set to zero
    in the returned positions.
    If dim<2, a ValueError is raised.

store_pos_as : str, default None
    If non-None, the position of each node will be stored on the graph as
    an attribute with this string as its name, which can be accessed with
    ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.

Returns
-------
pos : dict
    A dictionary of positions keyed by node

Raises
------
ValueError
    If dim < 2

Examples
--------
>>> from pprint import pprint
>>> G = nx.path_graph(4)
>>> pos = nx.circular_layout(G)
>>> # suppress the returned dict and store on the graph directly
>>> _ = nx.circular_layout(G, store_pos_as="pos")
>>> pprint(nx.get_node_attributes(G, "pos"))
{0: array([9.99999986e-01, 2.18556937e-08]),
 1: array([-3.57647606e-08,  1.00000000e+00]),
 2: array([-9.9999997e-01, -6.5567081e-08]),
 3: array([ 1.98715071e-08, -9.99999956e-01])}


Notes
-----
This algorithm currently only works in two dimensions and does not
try to minimize edge crossings.

r   Nr(   zcannot handle dimensions < 2r3   scale)r   r   r%   maxr   r   utilsarbitrary_elementlinspacepir+   r,   column_stackcossinr   r	   r-   r.   r/   )	r   r7   r   r    r1   r!   paddimsr2   thetas	            r$   r   r      s$   p 
Qw7883/IA!cAgG
1v{	Q1xx))!,f5 Aq#a&1*-cr2Q6>RZZ(ooVVE]BFF5M288SVW4E+FG
 S.73q;
q|4Jr&   c           	         SSK nUS:w  a  [        S5      e[        XU5      u  p[        U 5      S:X  a  0 $ [        U 5      S:X  a!  [        R
                  R                  U 5      U0$ Uc  [        U 5      /nU[        U5      -  n[        US   5      S:X  a  Sn	OUn	Uc  UR                  [        U5      -  nUn
0 nU H  nUR                  SSUR                  -  [        U5      SUR                  S9U
-   nXR                  UR                  U5      UR                  U5      /5      -  U-   nUR                  [        X5      5        X-  n	X-  n
M     Ub  [        R                   " XU5        U$ )	ah  Position nodes in concentric circles.

Parameters
----------
G : NetworkX graph or list of nodes
    A position will be assigned to every node in G.

nlist : list of lists
   List of node lists for each shell.

rotate : angle in radians (default=pi/len(nlist))
   Angle by which to rotate the starting position of each shell
   relative to the starting position of the previous shell.
   To recreate behavior before v2.5 use rotate=0.

scale : number (default: 1)
    Scale factor for positions.

center : array-like or None
    Coordinate pair around which to center the layout.

dim : int
    Dimension of layout, currently only dim=2 is supported.
    Other dimension values result in a ValueError.

store_pos_as : str, default None
    If non-None, the position of each node will be stored on the graph as
    an attribute with this string as its name, which can be accessed with
    ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.

Returns
-------
pos : dict
    A dictionary of positions keyed by node

Raises
------
ValueError
    If dim != 2

Examples
--------
>>> from pprint import pprint
>>> G = nx.path_graph(4)
>>> shells = [[0], [1, 2, 3]]
>>> pos = nx.shell_layout(G, shells)
>>> # suppress the returned dict and store on the graph directly
>>> _ = nx.shell_layout(G, shells, store_pos_as="pos")
>>> pprint(nx.get_node_attributes(G, "pos"))
{0: array([0., 0.]),
 1: array([-5.00000000e-01, -4.37113883e-08]),
 2: array([ 0.24999996, -0.43301272]),
 3: array([0.24999981, 0.43301281])}

Notes
-----
This algorithm currently only works in two dimensions and does not
try to minimize edge crossings.

r   Nr(   can only handle 2 dimensionsr3           F)endpointdtype)r   r   r%   r   r   r9   r:   listr<   r;   r,   r=   r>   r?   updater.   r/   )r   nlistrotater7   r   r    r1   r!   radius_bumpradiusfirst_thetanposnodesrA   r2   s                  r$   r   r      sb   ~ 
ax7883/IA
1v{	
1v{**1-v66}a	#e*$K
58} ~U#KD KK1ruu9c%j5

KS 	 urvve}'EFFOCO$  
q5Kr&   verticalc                 F   SSK nUS;  a  Sn[        U5      e[        XSS9u  p[        U 5      S:X  a  0 $ Sn	XY-  n
U
S-  U	S-  4nUc-  [        R
                  R                  U 5      u  p[        U 5      nO0[        U5      n[        U 5      U-
  n[        U5      [        U5      -   nUR                  S[        U5      5      nUR                  U
[        U5      5      nUR                  SU	[        U5      5      nUR                  SU	[        U5      5      nUR                  UU/5      U-
  nUR                  UU/5      U-
  nUR                  UU/5      n[        UUS9U-   nUS	:X  a  USS2SSS
24   n[        [        UU5      5      nUb  [        R                   " U UU5        U$ )a  Position nodes in two straight lines.

Parameters
----------
G : NetworkX graph or list of nodes
    A position will be assigned to every node in G.

nodes : collection of nodes
    Nodes in one node set of the graph. This set will be placed on
    left or top. If `None` (the default), a node set is chosen arbitrarily
    if the graph if bipartite.

align : string (default='vertical')
    The alignment of nodes. Vertical or horizontal.

scale : number (default: 1)
    Scale factor for positions.

center : array-like or None
    Coordinate pair around which to center the layout.

aspect_ratio : number (default=4/3):
    The ratio of the width to the height of the layout.

store_pos_as : str, default None
    If non-None, the position of each node will be stored on the graph as
    an attribute with this string as its name, which can be accessed with
    ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.

Returns
-------
pos : dict
    A dictionary of positions keyed by node.

Raises
------
NetworkXError
    If ``nodes=None`` and `G` is not bipartite.

Examples
--------
>>> G = nx.complete_bipartite_graph(3, 3)
>>> pos = nx.bipartite_layout(G)

The ordering of the layout (i.e. which nodes appear on the left/top) can
be specified with the `nodes` parameter:

>>> top, bottom = nx.bipartite.sets(G)
>>> pos = nx.bipartite_layout(G, nodes=bottom)  # "bottom" set appears on the left

`store_pos_as` can be used to store the node positions for the computed layout
directly on the nodes:

>>> _ = nx.bipartite_layout(G, nodes=bottom, store_pos_as="pos")
>>> from pprint import pprint
>>> pprint(nx.get_node_attributes(G, "pos"))
{0: array([ 1.  , -0.75]),
 1: array([1., 0.]),
 2: array([1.  , 0.75]),
 3: array([-1.  , -0.75]),
 4: array([-1.,  0.]),
 5: array([-1.  ,  0.75])}


The ``bipartite_layout`` function can be used with non-bipartite graphs
by explicitly specifying how the layout should be partitioned with `nodes`:

>>> G = nx.complete_graph(5)  # Non-bipartite
>>> pos = nx.bipartite_layout(G, nodes={0, 1, 2})

Notes
-----
This algorithm currently only works in two dimensions and does not
try to minimize edge crossings.

r   NrP   
horizontal,align must be either vertical or horizontal.r(   r   r    r3   r6   rS   r5   )r   r   r%   r   r   	bipartitesetsrG   setrepeatr;   r=   concatenater	   r-   r.   r/   )r   rO   alignr7   r   aspect_ratior1   r!   r#   heightwidthoffsettopbottomleft_xsright_xsleft_ysright_ystop_pos
bottom_posr2   s                        r$   r   r   B  s   l ..<oa8IA
1v{	F!Eai!$F}ll''*Q%jQ#S	DL(ii3s8$GyyF,Hkk!VSX.G{{1fc&k2Hoow01F:G(H!56?J
..':.
/C
E
*V
3C!TrT'l
s5#
C
q#|4Jr&   
   weightauto      ?)methodgravityc                D   SSK nUS;  a  [        S5      eUS:X  a  [        U 5      S:  a  SOSn[        XU	5      u  pUbs  Uc  [        S	5      eU H  nX;  d  M
  [        S	5      e   [	        U 5       VVs0 s H  u  noU_M
     nnnUR                  U Vs/ s H  oU;   d  M
  UU   PM     sn5      nUb~  [        S
 UR                  5        5       5      nUS:X  a  SnU
R                  [        U 5      U	5      U-  U-   n[	        U 5       H%  u  nnUU;   d  M  UR                  UU   5      UU'   M'     OSnSn[        U 5      S:X  a  0 $ [        U 5      S:X  aK  [        R                  R                  U R                  5       5      U0nUb  [        R                  " XU5        U$ [        U 5      S:  d  US:X  aP  [        R                  " XSS9nUc&  Ub#  UR                  u  nnUUR!                  U5      -  n[#        UUUX4XYXU5
      nOM[        R$                  " XS9nUc&  Ub#  UR                  u  nnUUR!                  U5      -  n['        UUUX4XYU
5      nUc  Ub  [)        X'S9U-   n[+        [-        X5      5      nUb  [        R                  " XU5        U$ s  snnf s  snf )a4  Position nodes using Fruchterman-Reingold force-directed algorithm.

The algorithm simulates a force-directed representation of the network
treating edges as springs holding nodes close, while treating nodes
as repelling objects, sometimes called an anti-gravity force.
Simulation continues until the positions are close to an equilibrium.

There are some hard-coded values: minimal distance between
nodes (0.01) and "temperature" of 0.1 to ensure nodes don't fly away.
During the simulation, `k` helps determine the distance between nodes,
though `scale` and `center` determine the size and place after
rescaling occurs at the end of the simulation.

Fixing some nodes doesn't allow them to move in the simulation.
It also turns off the rescaling feature at the simulation's end.
In addition, setting `scale` to `None` turns off rescaling.

Parameters
----------
G : NetworkX graph or list of nodes
    A position will be assigned to every node in G.

k : float (default=None)
    Optimal distance between nodes.  If None the distance is set to
    1/sqrt(n) where n is the number of nodes.  Increase this value
    to move nodes farther apart.

pos : dict or None  optional (default=None)
    Initial positions for nodes as a dictionary with node as keys
    and values as a coordinate list or tuple.  If None, then use
    random initial positions.

fixed : list or None  optional (default=None)
    Nodes to keep fixed at initial position.
    Nodes not in ``G.nodes`` are ignored.
    ValueError raised if `fixed` specified and `pos` not.

iterations : int  optional (default=50)
    Maximum number of iterations taken

threshold: float optional (default = 1e-4)
    Threshold for relative error in node position changes.
    The iteration stops if the error is below this threshold.

weight : string or None   optional (default='weight')
    The edge attribute that holds the numerical value used for
    the edge weight.  Larger means a stronger attractive force.
    If None, then all edge weights are 1.

scale : number or None (default: 1)
    Scale factor for positions. Not used unless `fixed is None`.
    If scale is None, no rescaling is performed.

center : array-like or None
    Coordinate pair around which to center the layout.
    Not used unless `fixed is None`.

dim : int
    Dimension of layout.

seed : int, RandomState instance or None  optional (default=None)
    Used only for the initial positions in the algorithm.
    Set the random state for deterministic node layouts.
    If int, `seed` is the seed used by the random number generator,
    if numpy.random.RandomState instance, `seed` is the random
    number generator,
    if None, the random number generator is the RandomState instance used
    by numpy.random.

store_pos_as : str, default None
    If non-None, the position of each node will be stored on the graph as
    an attribute with this string as its name, which can be accessed with
    ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.

method : str  optional (default='auto')
    The method to compute the layout.
    If 'force', the force-directed Fruchterman-Reingold algorithm [1]_ is used.
    If 'energy', the energy-based optimization algorithm [2]_ is used with absolute
    values of edge weights and gravitational forces acting on each connected component.
    If 'auto', we use 'force' if ``len(G) < 500`` and 'energy' otherwise.

gravity: float optional (default=1.0)
    Used only for the method='energy'.
    The positive coefficient of gravitational forces per connected component.

Returns
-------
pos : dict
    A dictionary of positions keyed by node

Examples
--------
>>> from pprint import pprint
>>> G = nx.path_graph(4)
>>> pos = nx.spring_layout(G)
>>> # suppress the returned dict and store on the graph directly
>>> _ = nx.spring_layout(G, seed=123, store_pos_as="pos")
>>> pprint(nx.get_node_attributes(G, "pos"))
{0: array([-0.61520994, -1.        ]),
 1: array([-0.21840965, -0.35501755]),
 2: array([0.21841264, 0.35502078]),
 3: array([0.61520696, 0.99999677])}

# The same using longer but equivalent function name
>>> pos = nx.fruchterman_reingold_layout(G)

References
----------
.. [1] Fruchterman, Thomas MJ, and Edward M. Reingold.
       "Graph drawing by force-directed placement."
       Software: Practice and experience 21, no. 11 (1991): 1129-1164.
       http://dx.doi.org/10.1002/spe.4380211102
.. [2] Hamaguchi, Hiroki, Naoki Marumo, and Akiko Takeda.
       "Initial Placement for Fruchterman--Reingold Force Model With Coordinate Newton Direction."
       arXiv preprint arXiv:2412.20317 (2024).
       https://arxiv.org/abs/2412.20317
r   N)rj   forceenergyz1the method must be either auto, force, or energy.rj     ro   rp   z'nodes are fixed without positions givenc              3   6   #    U  H  o  H  o"v   M     M     g 7fN ).0pos_tupcoords      r$   	<genexpr> spring_layout.<locals>.<genexpr>^  s     NLgUuguLs   r3   fri   rF   ri   r6   )r   r   r   r%   	enumerater   r8   valuesr*   r   r9   r:   rO   r/   to_scipy_sparse_arrayshapesqrt_sparse_fruchterman_reingoldto_numpy_array_fruchterman_reingoldr	   r-   r.   )r   kr2   fixed
iterations	thresholdri   r7   r   r    r0   r1   rl   rm   r!   nodeinfixeddom_sizepos_arrnAnnodes_s                           r$   r   r     s   N 00LMMFSLh3/IA;FGGD !JKK  *316ga'6

UMUTfnLF4LUMN
NCJJLNNq=H))CFC(83f<aLDAqCxZZA/
 ! 
1v{	
1v{xx))!'')4f=#""1<8
 1v}(*$$QSA9*IFA2776?*A*q'5idG
 a/9*IFA2776?*A#q'5id
 }*S.7
s1{
C
q|4Jg 7Ms   5J	J#	J   c                    SS K n U R                  u  pUc*  UR                  UR                  X5      U R                  S9nOUR                  U R                  5      nUc  UR                  SU	-  5      n[        [        UR                  S   5      [        UR                  S   5      -
  [        UR                  S   5      [        UR                  S   5      -
  5      S-  nXS-   -  nUR                  UR                  S   UR                  S   UR                  S   4U R                  S9n[        U5       H  nUS S 2UR                  S S 24   X(R                  S S 2S S 24   -
  nUR                   R#                  USS9nUR%                  US	S US
9  UR'                  SXU-  US-  -  U U-  U-  -
  5      nUR                   R#                  USS9nUR)                  US	:  SU5      nUR'                  SUUU-  5      nUb  SUU'   UU-  nX-  nUR                   R#                  U5      U	-  U:  d  M    U$    U$ ! [         a  nSn[        R                  " U5      UeS nAff = f)Nr   9fruchterman_reingold() takes an adjacency matrix as inputrF   rk   r3   皙?r5   axis{Gz?)outz
ijk,ij->ikr(   zij,i->ijrD   )r   r   AttributeErrorr   NetworkXErrorr   r*   rF   r+   r   r8   Tminr   rangenewaxislinalgnormclipeinsumwhere)r   r   r2   r   r   r   r    r0   r!   r   r   errr#   tdtdelta	iterationdistancedisplacementlength	delta_poss                        r$   r   r     sD    -GG	
 {jj6/qwwj? jj! 	yGGC&L!
 	CaMCaM)3suuQx=3suuQx=+HICOA 
1n	BHHciilCIIaL#))A,?qwwHOE :&	Arzz1$%JJ1,<(==99>>%b>1
$(3yy%a%(A+"5Hq8H"H
 26&4-f5IIj,F
C	"Iey	IINN9%.);J/ '. Jc  -Is#,-s   H7 7
IIIc
                    SS K n
SS Kn U R                  u  pUc*  U
R                  UR                  X5      U R                  S9nOUR                  U R                  5      nUc  / nUc  U
R                  SU-  5      nUS:X  a  [        XXX4XVU	5	      $  U R                  5       n [        [        UR                   S   5      [#        UR                   S   5      -
  [        UR                   S   5      [#        UR                   S   5      -
  5      S-  nUUS-   -  nU
R%                  Xl45      n['        U5       GHB  nUS-  n['        U R                  S   5       H  nUU;   a  M  UU   U-
  R                   nU
R                  US-  R)                  SS	95      nU
R+                  US
:  S
U5      nU R-                  U5      R/                  5       nUS S 2U4==   UX-  US-  -  UU-  U-  -
  -  R)                  SS	9-  ss'   M     U
R                  US-  R)                  SS	95      nU
R+                  US
:  SU5      nUU-  U-  R                   nUU-  nUU-  nU
R0                  R3                  U5      U-  U:  d  GMB    U$    U$ ! [         a  nSn[        R
                  " U5      UeS nAff = f! [         a-    UR                  R                  U 5      R                  5       n  GN<f = f)Nr   r   r   rk   rp   r3   r   r(   r   r   )r   scipyr   r   r   r   r   r*   rF   r+   r   _energy_fruchterman_reingoldtolilsparse	coo_arrayr8   r   r   r   r   sumr   
getrowviewtoarrayr   r   )r   r   r2   r   r   r   r    r0   rl   rm   r!   spr   r   r   r#   r   r   r   r   r   r   r   Air   r   s                             r$   r   r     s     -GG	
 {jj6/qwwj? jj! } 	yGGC&L!+qu)'
 	

-GGI 	CaMCaM)3suuQx=3suuQx=+HICOA 
j1n	B88SM*L:&	qwwqz"AEzVc\$$Ewwq~~1~56Hxx4x@Ha((*BA1,rH}q/@@Acqck #  ,/..A.67&4-f5!A%.11	y	RIINN9%.);J7 '6 JC  -Is#,-6  -YY  #**,-s)   I= J( =
J%J  J%(3KKc	                 .  ^ ^^^^^^^^^^ SS K mSS Kn	TS::  a  [        S5      e T R                  5       m TR                  T 5      m T T R                  -   S-  m U	R
                  R                  R                  T SS9u  mmTR                  T5      mSmU UUUUUUUUUU4S jn
XVS.nU	R                  R                  XR                  5       S	S
US9R                  R!                  TT45      $ ! [         a    U	R
                  R                  T 5      m  Nf = f)Nr   zthe gravity must be positive.r(   F)directedrq   c           
        > U R                  TT45      nTR                  TT45      nSn[        STT5       H  n[        UT-   T5      nXU2TR                  S S 24   UTR                  S S 2S S 24   -
  nTR                  Xf-  SS9nTR                  US5      nTR                  U5      nTXE U-  n	STR                  SU	T-  TS-  U-  -
  U5      -  X$U& UTR                  X-  5      ST-  -  -  nUTS-  TR                  TR                  U5      5      -  -  nM     TR                  TT45      n
TR                  R                  U
TU5        U
TS S 2TR                  4   -  S-
  nUTUT   -  -  nUTS-  TR                  TTR                  R                  US	S9S-  -  5      -  -  nSUT'   X2R                  5       4$ )
NrD   r   r(   r   绽|=z
ij,ijk->ikr'         ?r3   )reshaper   r   r   r   r   maximumr   r   logaddatr   r   ravel)xr2   gradcostlrr   	distance2r   Adcentersdelta0r   	batchsizebincountr    r   rm   r   labelsn_componentsr   r!   s               r$   _cost_FR._energy_fruchterman_reingold.<locals>._cost_FRB  s   ii&xx&q&),AA	M6*A!RZZ*+c"**a2B.CCEu}15I

9e4Iwwy)H1("BBIIlBFQTI=M4MuUUD1IBFF2>*a!e44DAqD266"&&"2333D -" ((L#./
		'63'8ArzzM22S8&.((#x"))..a.2PTU2U'U VVVUZZ\!!r&   )maxitergtolL-BFGS-BT)rl   jacoptions)r   r   r   tocsrr   r   	csr_arrayabsr   csgraphconnected_componentsr   optimizeminimizer   r   r   )r   r   r   r2   r   r   r   r    rm   r   r   r   r   r   r   r   r!   s   ``` `  ``   @@@@@r$   r   r   )  s    
 !|8::#GGI
 	q	A	
QSSAA99,,AA!eATL&{{6"HI" "> %8G;;))+jdG   aW  #II"#s   C, ,%DDc                    SSK n[        XU5      u  p[        U 5      n	U	S:X  a  0 $ Uc  [        [        R
                  " XS95      nSUR                  X45      -  n
[        U 5       H4  u  pX;  a  M  X   n[        U 5       H  u  pX;  a  M  X   X   U'   M     M6     UcN  US:  a
  [        XS9nO>US:X  a
  [        XS9nO.[        [        XR                  SS[        U 5      5      5      5      nUR                  U  Vs/ s H  nUU   PM
     sn5      n[        U
UU5      n[        X$S	9U-   n[        [        X5      5      nUb  [        R                  " XU5        U$ s  snf )
a  Position nodes using Kamada-Kawai path-length cost-function.

Parameters
----------
G : NetworkX graph or list of nodes
    A position will be assigned to every node in G.

dist : dict (default=None)
    A two-level dictionary of optimal distances between nodes,
    indexed by source and destination node.
    If None, the distance is computed using shortest_path_length().

pos : dict or None  optional (default=None)
    Initial positions for nodes as a dictionary with node as keys
    and values as a coordinate list or tuple.  If None, then use
    circular_layout() for dim >= 2 and a linear layout for dim == 1.

weight : string or None   optional (default='weight')
    The edge attribute that holds the numerical value used for
    the edge weight.  If None, then all edge weights are 1.

scale : number (default: 1)
    Scale factor for positions.

center : array-like or None
    Coordinate pair around which to center the layout.

dim : int
    Dimension of layout.

store_pos_as : str, default None
    If non-None, the position of each node will be stored on the graph as
    an attribute with this string as its name, which can be accessed with
    ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.

Returns
-------
pos : dict
    A dictionary of positions keyed by node

Examples
--------
>>> from pprint import pprint
>>> G = nx.path_graph(4)
>>> pos = nx.kamada_kawai_layout(G)
>>> # suppress the returned dict and store on the graph directly
>>> _ = nx.kamada_kawai_layout(G, store_pos_as="pos")
>>> pprint(nx.get_node_attributes(G, "pos"))
{0: array([0.99996577, 0.99366857]),
 1: array([0.32913544, 0.33543827]),
 2: array([-0.33544334, -0.32910684]),
 3: array([-0.99365787, -1.        ])}
r   Nr|   g    .Ar'   )r    r(   r3   r6   )r   r%   r   r-   r   shortest_path_lengthonesr}   r   r   r.   r;   array_kamada_kawai_solver	   r/   )r   distr2   ri   r7   r   r    r1   r!   nNodesdist_mtxrownrrdistcolncr   r   s                     r$   r   r   g  sU   ~ 3/IAVF{	|B++A=>RWWf-..HQ<> |GC!&HM# $	   {!8+CAX!!-Cs1kk!QA789Chh*1A*+G
h
5C

*V
3C
s1{
C
q|4J +s   >Ec                     SS K nSS KnSnUSXR                  U R                  S   5      S-  -   -  XR4nUR                  R                  [        UR                  5       SUSS9nUR                  R                  SU45      $ )Nr   MbP?r3   r   T)rl   argsr   r5   )
r   r   eyer   r   r   _kamada_kawai_costfnr   r   r   )r   r   r    r!   r   meanwtcostargs	optresults           r$   r   r     s    
 FAFF8>>!+<$=$DDEvSH$$ % I ;;Cy))r&   c           	      ^   UR                   S   nU R                  XT45      nUS S 2UR                  S S 24   XaR                  S S 2S S 24   -
  nUR                  R	                  USS9nUR                  SUSXR                  U5      S-  -   -  5      n	X-  S-
  n
SXR                  U5      '   SUR                  U
S	-  5      -  nUR                  S
X*U	5      UR                  SX*U	5      -
  nUR                  USS9nUSU-  UR                  US	-  5      -  -  nXU-  -  nXR                  5       4$ )Nr   r5   r   zijk,ij->ijkr3   r   rk   r   r(   zij,ij,ijk->ikzij,ij,ijk->jk)
r   r   r   r   r   r   r   diag_indicesr   r   )pos_vecr!   invdist
meanweightr    r   r   r   nodesep	directionr_   r   r   sumposs                 r$   r   r     s6   ]]1Foovm,GArzz1$%

Aq0@(AAEiinnUn,G		-Wvvf~PT?T5T0UVI$F&'F??6"#	""D99_gyABII)E D
 VVG!V$FC*rvvfai000DD**,r&   c                 >   SSK n[        XU5      u  p[        U 5      S::  a  [        U 5      S:X  a  UR                  / 5      nOV[        U 5      S:X  a  UR                  U/5      nO4UR                  UR	                  U5      UR                  U5      S-  /5      n[        [        X5      5      $  [        U 5      S:  a  [        e[        R                  " XSS9nU R                  5       (       a  XR                  U5      -   n[        X5      n[#        XrS
9U-   n[        [        X5      5      nUb  [        R$                  " XU5        U$ ! [        [        4 aE    [        R                  " XS	9nU R                  5       (       a  XR                  -  n[!        X5      n Nf = f)a  Position nodes using the eigenvectors of the graph Laplacian.

Using the unnormalized Laplacian, the layout shows possible clusters of
nodes which are an approximation of the ratio cut. If dim is the number of
dimensions then the positions are the entries of the dim eigenvectors
corresponding to the ascending eigenvalues starting from the second one.

Parameters
----------
G : NetworkX graph or list of nodes
    A position will be assigned to every node in G.

weight : string or None   optional (default='weight')
    The edge attribute that holds the numerical value used for
    the edge weight.  If None, then all edge weights are 1.

scale : number (default: 1)
    Scale factor for positions.

center : array-like or None
    Coordinate pair around which to center the layout.

dim : int
    Dimension of layout.

store_pos_as : str, default None
    If non-None, the position of each node will be stored on the graph as
    an attribute with this string as its name, which can be accessed with
    ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.

Returns
-------
pos : dict
    A dictionary of positions keyed by node

Examples
--------
>>> from pprint import pprint
>>> G = nx.path_graph(4)
>>> pos = nx.spectral_layout(G)
>>> # suppress the returned dict and store on the graph directly
>>> _ = nx.spectral_layout(G, store_pos_as="pos")
>>> pprint(nx.get_node_attributes(G, "pos"))
{0: array([-1.        ,  0.76536686]),
 1: array([-0.41421356, -0.76536686]),
 2: array([ 0.41421356, -0.76536686]),
 3: array([1.        , 0.76536686])}


Notes
-----
Directed graphs will be considered as undirected graphs when
positioning the nodes.

For larger graphs (>500 nodes) this will use the SciPy sparse
eigenvalue solver (ARPACK).
r   Nr(   r3          @rq   dr{   r|   r6   )r   r%   r   r   r   r-   r.   r   r   r   is_directed	transpose_sparse_spectralImportErrorr   r   	_spectralr	   r/   )	r   ri   r7   r   r    r1   r!   r2   r   s	            r$   r   r     sY   v 3/IA
1v{q6Q;((2,CVq[((F8$C((BHHSM288F+;c+ABCCCK   q6C<$$QSA==??LLO#Aq& 
*V
3C
s1{
C
q|4J $  a/==??HA s   .AE AFFc                 r   SS K n U R                  u  p4UR                  X0R                  S9UR                  U SS9-  nXp-
  nUR                  R                  U5      u  pUR                  U	5      SUS-    nUR                  U
S S 2U4   5      $ ! [         a  nSn[        R                  " U5      UeS nAff = f)Nr   z-spectral() takes an adjacency matrix as inputr   r3   r   )r   r   r   r   r   identityrF   r   r   eigargsortreal)r   r    r!   r   r   r   r#   DLeigenvalueseigenvectorsindexs               r$   r  r  ]  s     -GG	 	F''*RVVAAV->>A	A "		a 0KJJ{#Aa0E77<5)**  -=s#,-s   B 
B6B11B6c                    SS K nSS Kn U R                  u  pEUR                  R                  UR                  R                  U R                  SS9SXD5      5      nX-
  n	US-   n
[        SU
-  S-   [        UR                  U5      5      5      nUR                  R                  R                  XSUS9u  pUR                  U5      SU
 nUR!                  US S 2U4   5      $ ! [         a  nSn[        R
                  " U5      UeS nAff = f)Nr   z4sparse_spectral() takes an adjacency matrix as inputr3   r   r(   SM)whichncv)r   r   r   r   r   r   r   r   spdiagsr   r8   intr   r   eigshr  r	  )r   r    r!   r   r   r   r   r#   r
  r  r   r  r  r  r  s                  r$   r  r  r  s     -GG	 			BII--aeeemQOPA	AaA
a!eaiRWWV_-
.C "		 0 0 6 6q4S 6 QKJJ{#Aa(E77<5)**  -Ds#,-s   C! !
D	+DD	c                 Z   SSK nUS:w  a  [        S5      e[        XU5      u  p[        U 5      S:X  a  0 $ [	        U [
        R                  5      (       a  U nO5[
        R                  " U 5      u  pvU(       d  [
        R                  " S5      e[
        R                  " U5      n[        U5      n	UR                  U	 V
s/ s H  oU
   PM	     sn
5      nUR                  UR                  5      n[        XS9U-   n[        [!        X5      5      nUb  [
        R"                  " XU5        U$ s  sn
f )a  Position nodes without edge intersections.

Parameters
----------
G : NetworkX graph or list of nodes
    A position will be assigned to every node in G. If G is of type
    nx.PlanarEmbedding, the positions are selected accordingly.

scale : number (default: 1)
    Scale factor for positions.

center : array-like or None
    Coordinate pair around which to center the layout.

dim : int
    Dimension of layout.

store_pos_as : str, default None
    If non-None, the position of each node will be stored on the graph as
    an attribute with this string as its name, which can be accessed with
    ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.

Returns
-------
pos : dict
    A dictionary of positions keyed by node

Raises
------
NetworkXException
    If G is not planar

Examples
--------
>>> from pprint import pprint
>>> G = nx.path_graph(4)
>>> pos = nx.planar_layout(G)
>>> # suppress the returned dict and store on the graph directly
>>> _ = nx.planar_layout(G, store_pos_as="pos")
>>> pprint(nx.get_node_attributes(G, "pos"))
{0: array([-0.77777778, -0.33333333]),
 1: array([ 1.        , -0.33333333]),
 2: array([0.11111111, 0.55555556]),
 3: array([-0.33333333,  0.11111111])}
r   Nr(   rC   zG is not planar.r6   )r   r   r%   r   r   r   PlanarEmbeddingcheck_planarityNetworkXExceptioncombinatorial_embedding_to_posrG   vstackr+   float64r	   r-   r.   r/   )r   r7   r   r    r1   r!   	embedding	is_planarr2   	node_listr   s              r$   r   r     s   \ 
ax7883/IA
1v{	!R''((	!11!4	&&'9::

+
+I
6CYI
))Y/YVY/
0C
**RZZ
 C

*V
3C
s9"
#C
q|4J 0s   <D(Fc           	      L   SSK nUS:w  a  [        S5      e[        XU5      u  p[        U 5      S:X  a  0 $ [        U 5      S:X  a=  [        R
                  R                  U 5      U0nUb  [        R                  " XU5        U$ / nU(       am  Sn	Sn
UnXX-  -  -  n[        [        U 5      5       HE  nX-  nXU-  -  nUR                  UR                  U5      U-  UR                  U5      U-  /5        MG     OcUR                  [        U 5      [        S9nXN-  nUR                  XR                  UR                  U5      UR                  U5      /5      -  5      n[!        UR                  U5      US9U-   n[#        [%        X5      5      nUb  [        R                  " XU5        U$ )	a  Position nodes in a spiral layout.

Parameters
----------
G : NetworkX graph or list of nodes
    A position will be assigned to every node in G.

scale : number (default: 1)
    Scale factor for positions.

center : array-like or None
    Coordinate pair around which to center the layout.

dim : int, default=2
    Dimension of layout, currently only dim=2 is supported.
    Other dimension values result in a ValueError.

resolution : float, default=0.35
    The compactness of the spiral layout returned.
    Lower values result in more compressed spiral layouts.

equidistant : bool, default=False
    If True, nodes will be positioned equidistant from each other
    by decreasing angle further from center.
    If False, nodes will be positioned at equal angles
    from each other by increasing separation further from center.

store_pos_as : str, default None
    If non-None, the position of each node will be stored on the graph as
    an attribute with this string as its name, which can be accessed with
    ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.

Returns
-------
pos : dict
    A dictionary of positions keyed by node

Raises
------
ValueError
    If dim != 2

Examples
--------
>>> from pprint import pprint
>>> G = nx.path_graph(4)
>>> pos = nx.spiral_layout(G)
>>> nx.draw(G, pos=pos)
>>> # suppress the returned dict and store on the graph directly
>>> _ = nx.spiral_layout(G, store_pos_as="pos")
>>> pprint(nx.get_node_attributes(G, "pos"))
{0: array([-0.64153279, -0.68555087]),
 1: array([-0.03307913, -0.46344795]),
 2: array([0.34927952, 0.14899882]),
 3: array([0.32533239, 1.        ])}

Notes
-----
This algorithm currently only works in two dimensions.

r   Nr(   rC   r3   r   r   r6   )r   r   r%   r   r   r9   r:   r/   r   appendr>   r?   arangefloatr  r   r	   r-   r.   )r   r7   r   r    
resolutionequidistantr1   r!   r2   chordsteprA   r   r   r   angles                   r$   r   r     s   L 
ax7883/IA
1v{	
1v{xx))!,f5#""1<8

C$,''s1vAAQYEJJu)266%=1+<=>  yyQuy-!ll4((BFF5M266%=+I"JJK
#e
4v
=C
s1{
C
q|4Jr&   c                 N   SSK nUS;  a  Sn[        U5      e[        XSS9u  p[        U 5      S:X  a  0 $  [        U 5      [	        S UR                  5        5       5      :w  a  [        R                  " S5      e  [        [        UR                  5       5      5      n	Sn
/ n[        U	5      n[!        U	R                  5       5       H  u  p[        U5      nUR#                  X5      nUR%                  SU[&        S
9nUS-
  S-  US-
  S-  4nUR)                  UU/5      U-
  nU
c  Un
OUR+                  U
U/5      n
UR-                  U5        M     [/        XS9U-   n
US:X  a  U
SS2SSS24   n
[        [1        X5      5      n
Ub  [        R2                  " X
U5        U
$ ! [         aj    [        R                  " X5      n[        U5      [        U 5      :w  a  [        R                  " S	U 35      e[        R                  R                  U5      n GNf = f! [         a    Un	 GNf = f)a  Position nodes in layers of straight lines.

Parameters
----------
G : NetworkX graph or list of nodes
    A position will be assigned to every node in G.

subset_key : string or dict (default='subset')
    If a string, the key of node data in G that holds the node subset.
    If a dict, keyed by layer number to the nodes in that layer/subset.

align : string (default='vertical')
    The alignment of nodes. Vertical or horizontal.

scale : number (default: 1)
    Scale factor for positions.

center : array-like or None
    Coordinate pair around which to center the layout.

store_pos_as : str, default None
    If non-None, the position of each node will be stored on the graph as
    an attribute with this string as its name, which can be accessed with
    ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.

Returns
-------
pos : dict
    A dictionary of positions keyed by node.

Examples
--------
>>> G = nx.complete_multipartite_graph(28, 16, 10)
>>> pos = nx.multipartite_layout(G)
>>> # suppress the returned dict and store on the graph directly
>>> G = nx.complete_multipartite_graph(28, 16, 10)
>>> _ = nx.multipartite_layout(G, store_pos_as="pos")

or use a dict to provide the layers of the layout

>>> G = nx.Graph([(0, 1), (1, 2), (1, 3), (3, 4)])
>>> layers = {"a": [0], "b": [1], "c": [2, 3], "d": [4]}
>>> pos = nx.multipartite_layout(G, subset_key=layers)

Notes
-----
This algorithm currently only works in two dimensions and does not
try to minimize edge crossings.

Network does not need to be a complete multipartite graph. As long as nodes
have subset_key data, they will be placed in the corresponding layers.

r   NrR   rT   r(   rU   c              3   8   #    U  H  n[        U5      v   M     g 7frs   r   ru   rO   s     r$   rx   &multipartite_layout.<locals>.<genexpr>  s     E1DU1D   z4all nodes must be in one subset of `subset_key` dictz'all nodes need a subset_key attribute: r   r3   r6   rS   r5   )r   r   r%   r   r   r~   r   r   r   get_node_attributesr9   groupsr-   sorteditems	TypeErrorr}   rY   r"  r#  r=   rZ   extendr	   r.   r/   )r   
subset_keyr[   r7   r   r1   r!   r#   node_to_subsetlayersr2   rO   r^   r   layerr]   xsysr_   	layer_poss                       r$   r   r   E  s   p ..<oa8IA
1v{	5q6SE1B1B1DEEE""F  FfZ--/01 CEKEfmmo.UYYq!YYq&Y.19/FQJ!#34OORH-6	;C..#y!12CU / 
*V
3C!TrT'l
s5
C
q|4JK  5//>~#a&(""9*F  XX__^4
5  s%   AF ;"H A0HHH$#H$r0   )r0   r1   c                  ^ SSK n	SSKn
US::  a  Sn[        U5      e[        R                  " XS9nUc  UnO2U R                  5        H  nX;  d  M
  X   R                  5       X'   M      [        U 5      nUS:X  a  U$ U
R                  X45      U
R                  U5      -
  n[        U 5       VVs0 s H  u  noU_M
     snnmU R                  5        H%  u  nnUU:w  d  M  U4S jUU4 5       u  nnX?UU4'   M'     U
R                  [        UR                  5       5      5      nX*R                  U5      -  nUS-   nSnUU:  a  USS2U
R                   4   UU
R                      -
  nU
R"                  R%                  USS9S	U
R                   4   nU	R'                  5          U	R)                  S
5        US	U
R                   4   U-  UU-  U-  -
  nSSS5        U
R+                  WSS9nUUU-  -  nU
R"                  R%                  USS9R-                  5       nUU:  a  OUS-  nUU:  a  M  [/        [1        U R                  5       U5      5      nUb  [        R2                  " XU5        U$ s  snnf ! , (       d  f       N= f)a  Arf layout for networkx

The attractive and repulsive forces (arf) layout [1] improves the spring
layout in three ways. First, it prevents congestion of highly connected nodes
due to strong forcing between nodes. Second, it utilizes the layout space
more effectively by preventing large gaps that spring layout tends to create.
Lastly, the arf layout represents symmetries in the layout better than the
default spring layout.

Parameters
----------
G : nx.Graph or nx.DiGraph
    Networkx graph.
pos : dict
    Initial  position of  the nodes.  If set  to None  a
    random layout will be used.
scaling : float
    Scales the radius of the circular layout space.
a : float
    Strength of springs between connected nodes. Should be larger than 1.
    The greater a, the clearer the separation of unconnected sub clusters.
etol : float
    Gradient sum of spring forces must be larger than `etol` before successful
    termination.
dt : float
    Time step for force differential equation simulations.
max_iter : int
    Max iterations before termination of the algorithm.
seed : int, RandomState instance or None  optional (default=None)
    Set the random state for deterministic node layouts.
    If int, `seed` is the seed used by the random number generator,
    if numpy.random.RandomState instance, `seed` is the random
    number generator,
    if None, the random number generator is the RandomState instance used
    by numpy.random.
store_pos_as : str, default None
    If non-None, the position of each node will be stored on the graph as
    an attribute with this string as its name, which can be accessed with
    ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.

Returns
-------
pos : dict
    A dictionary of positions keyed by node.

Examples
--------
>>> G = nx.grid_graph((5, 5))
>>> pos = nx.arf_layout(G)
>>> # suppress the returned dict and store on the graph directly
>>> G = nx.grid_graph((5, 5))
>>> _ = nx.arf_layout(G, store_pos_as="pos")

References
----------
.. [1] "Self-Organization Applied to Dynamic Network Layout", M. Geipel,
        International Journal of Modern Physics C, 2007, Vol 18, No 10,
        pp. 1537-1549.
        https://doi.org/10.1142/S0129183107011558 https://arxiv.org/abs/0704.1748
r   Nr3   z'The parameter a should be larger than 1)r0   c              3   .   >#    U  H
  nTU   v   M     g 7frs   rt   )ru   r   
node_orders     r$   rx   arf_layout.<locals>.<genexpr>  s     6v!
1vs   r5   r   .ignore)warningsr   r   r   r   rO   copyr   r   r   r}   edgesr   rG   r~   r   r   r   r   catch_warningssimplefilternansumr   r-   r.   r/   )r   r2   scalingaetolr   max_iterr0   r1   rA  r!   r#   pos_tmpr   NKr   r   yidxjdxprhoerrorn_iterdiffr   changer>  s                               @r$   r   r     sZ   R Av7oq,G
{GGID#M..0	 
 	AAAv
 	"&&)#A)216ga'6J	1661v6HCc3hK  	

4

%&A GGAJ
C 1HEF
$,BJJ!BJJ-/IINN4bN)#rzz/: $$&!!(+sBJJ'$.q4?F ' 6*	Vb[		vB/335H! $," s1779a 
!C
q|4JK 7* '&s   .I(/I..
I<r1      )
edge_attrsmutates_inputd   r   )rJ  jitter_tolerancescaling_ratiorm   distributed_actionstrong_gravity	node_mass	node_sizeri   dissuade_hubslinlogr0   r    r1   c          	      0   SSK n[        U 5      S:X  a  0 $ Uc>  [        R                  " XUS9nUR	                  [        UR                  5       5      5      nO[        U5      [        U 5      :X  a4  UR	                  U  Vs/ s H  nUU   R                  5       PM     sn5      nOUR	                  [        UR                  5       5      5      nUR                  SS9nUR                  SS9nUR                  nUUR                  [        U 5      U5      UU-
  -  -   n[        U 5       H$  u  nnUU;   d  M  UU   R                  5       UU'   M&     UR                  [        U 5      5      nUR                  [        U 5      5      nSnU	c  0 n	OSnUc  0 n[        U 5       HB  u  nnUR                  UU R                  U5      S-   5      UU'   U	R                  US5      UU'   MD     [        U 5      nUR                  UU45      nUR                  UU45      nUR                  UU45      n[        R                   " X
S9nS	 nSn Sn!Sn"Sn#[#        U5       GH  n$USS2S4   US   -
  n%UR$                  R'                  U%S
S9n&U(       aQ  UR)                  SU&-   5      * U&-  nUR+                  US5        UR-                  SUU5      nUR-                  SU%U5      nOUR-                  SU%U5      * nU(       a  UUSS2S4   -  nUSS2S4   US   -  n'U(       a  U&USS2S4   * US   -
  -  n&U&S-  n(UR+                  U'S5        UR+                  U(S5        U'U(-  U-  n)UR-                  SU%U)5      nUUR/                  USS9-
  n*U(       a  U* USS2S4   -  U*-  nO]UR1                  SSS9   U*UR$                  R'                  U*S
S9SS2S4   -  n+SSS5        UR3                  W+SS9n+U* USS2S4   -  U+-  nUU-   U-   n,U"UUR$                  R'                  UU,-
  S
S9-  R5                  5       -  n"U#SU-  UR$                  R'                  UU,-   S
S9-  R5                  5       -  n#U" UU"U#U U!U5      u  n n!U(       aq  UR$                  R'                  U,S
S9n-UU--  n.SU -  SUR7                  U U.-  5      -   -  n)UR9                  U)U--  SUR;                  U-R<                  5      -  5      U--  n)O7UUR$                  R'                  U,S
S9-  n.U SUR7                  U U.-  5      -   -  n)U,U)SS2S4   -  n/UU/-  n[?        U/5      R5                  5       S:  d  GM    O   [A        [C        U U5      5      nUb  [        RD                  " XU5        U$ s  snf ! , (       d  f       GN= f)aj  Position nodes using the ForceAtlas2 force-directed layout algorithm.

This function applies the ForceAtlas2 layout algorithm [1]_ to a NetworkX graph,
positioning the nodes in a way that visually represents the structure of the graph.
The algorithm uses physical simulation to minimize the energy of the system,
resulting in a more readable layout.

Parameters
----------
G : nx.Graph
    A NetworkX graph to be laid out.
pos : dict or None, optional
    Initial positions of the nodes. If None, random initial positions are used.
max_iter : int (default: 100)
    Number of iterations for the layout optimization.
jitter_tolerance : float (default: 1.0)
    Controls the tolerance for adjusting the speed of layout generation.
scaling_ratio : float (default: 2.0)
    Determines the scaling of attraction and repulsion forces.
gravity : float (default: 1.0)
    Determines the amount of attraction on nodes to the center. Prevents islands
    (i.e. weakly connected or disconnected parts of the graph)
    from drifting away.
distributed_action : bool (default: False)
    Distributes the attraction force evenly among nodes.
strong_gravity : bool (default: False)
    Applies a strong gravitational pull towards the center.
node_mass : dict or None, optional
    Maps nodes to their masses, influencing the attraction to other nodes.
node_size : dict or None, optional
    Maps nodes to their sizes, preventing crowding by creating a halo effect.
weight : string or None, optional (default: None)
    The edge attribute that holds the numerical value used for
    the edge weight. If None, then all edge weights are 1.
dissuade_hubs : bool (default: False)
    Prevents the clustering of hub nodes.
linlog : bool (default: False)
    Uses logarithmic attraction instead of linear.
seed : int, RandomState instance or None  optional (default=None)
    Used only for the initial positions in the algorithm.
    Set the random state for deterministic node layouts.
    If int, `seed` is the seed used by the random number generator,
    if numpy.random.RandomState instance, `seed` is the random
    number generator,
    if None, the random number generator is the RandomState instance used
    by numpy.random.
dim : int (default: 2)
    Sets the dimensions for the layout. Ignored if `pos` is provided.
store_pos_as : str, default None
    If non-None, the position of each node will be stored on the graph as
    an attribute with this string as its name, which can be accessed with
    ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.

Examples
--------
>>> import networkx as nx
>>> G = nx.florentine_families_graph()
>>> pos = nx.forceatlas2_layout(G)
>>> nx.draw(G, pos=pos)
>>> # suppress the returned dict and store on the graph directly
>>> pos = nx.forceatlas2_layout(G, store_pos_as="pos")
>>> _ = nx.forceatlas2_layout(G, store_pos_as="pos")

References
----------
.. [1] Jacomy, M., Venturini, T., Heymann, S., & Bastian, M. (2014).
       ForceAtlas2, a continuous graph layout algorithm for handy network
       visualization designed for the Gephi software. PloS one, 9(6), e98679.
       https://doi.org/10.1371/journal.pone.0098679
r   N)r    r0   r   FTr3   r|   c                    SSK nSUR                  U 5      -  nUR                  U5      nSn	Sn
[        XU-  U S-  -  5      nU[        X5      -  nX-  S:  a  XJ:  a  US-  n[        X5      nUS:X  a  UR                  nO
X-  U-  U-  nXU-  :  a  XJ:  a  US-  nOUS	:  a  US
-  nSnU[        X-
  X-  5      -   nX44$ )a!  Computes the scaling factor for the force in the ForceAtlas2 layout algorithm.

This   helper  function   adjusts   the  speed   and
efficiency  of the  layout generation  based on  the
current state of  the system, such as  the number of
nodes, current swing, and traction forces.

Parameters
----------
n : int
    Number of nodes in the graph.
swing : float
    The current swing, representing the oscillation of the nodes.
traction : float
    The current traction force, representing the attraction between nodes.
speed : float
    The current speed of the layout generation.
speed_efficiency : float
    The efficiency of the current speed, influencing how fast the layout converges.
jitter_tolerance : float
    The tolerance for jitter, affecting how much speed adjustment is allowed.

Returns
-------
tuple
    A tuple containing the updated speed and speed efficiency.

Notes
-----
This function is a part of the ForceAtlas2 layout algorithm and is used to dynamically adjust the
layout parameters to achieve an optimal and stable visualization.

r   Ng?rh   r(   r   r   gffffff?  g?)r   r   r   r8   inf)r   swingtractionspeedspeed_efficiencyr[  r!   
opt_jitter
min_jitter
max_jittermin_speed_efficiencyotherjittertarget_speedmax_rises                  r$   estimate_factor+forceatlas2_layout.<locals>.estimate_factor  s    D 	 BGGAJ&
WWZ(

#JX 51 <=!C
$::c!6 C' 2FA:66L!4x?%GLH$$6 C' T\#L0(2BCC&&r&   r5   zij, ij -> ijzijk, ij -> ikr(   r@  )divideinvalid)nanr   r   g      $@r   )#r   r   r   r   r   rG   r~   rB  r8   r   sizer*   r}   r   getdegreer   r   r   r   r   fill_diagonalr   meanerrstate
nan_to_numr   r   minimumr   r   r   r-   r.   r/   )0r   r2   rJ  r[  r\  rm   r]  r^  r_  r`  ri   ra  rb  r0   r    r1   r!   r   r   pos_initmax_posmin_posrO  massrx  adjust_sizesr   	gravities
attraction	repulsionr   rs  ri  rj  rg  rh  r   rU  r   tmpd2factorpos_centeredunit_vecrH   dfswingingfactored_updates0                                                   r$   r   r   >  s   v 
1v{	
{q5((4

-.	SSV	((;CINN,;< 88D./,,A,&,,A,&llDIIc!fc2g6GHH"1ICs{"4y~~/ & 88CFD88CFD L		q\	TMM$(:;S	MM$*S	 " 	AA!S"I1c(#J!S"I
!+A>'@ EEH8_q$w'$-/99>>$R>0 &&X..9JZ+>:qAJ?D*EJ ))OT1==J$q$w-'J 1d7md4j(agd33Hq[
a 
Q(m+IIotV<	 q!99 44=0<?I Hh?'"))..B.*OPQSWPW*XX @}}X1}5H 44=08;I i')3 	$&(8rBBGGIIS4Z"))..61A."KKPPRR"1#
 R0BbyH5[A0@(A$ABFZZTBGGBHH4E-EFKFbiinnV"n==Ha"''%(*:";;<F 6!T'?2?"##%-O R s1g
C
q|4Ji <X @?s   >V"%V
V	c                     SSK nX R                  SS9-  n UR                  U 5      R                  5       nUS:  a  XU-  -  n U $ )a(  Returns scaled position array to (-scale, scale) in all axes.

The function acts on NumPy arrays which hold position information.
Each position is one row of the array. The dimension of the space
equals the number of columns. Each coordinate in one column.

To rescale, the mean (center) is subtracted from each axis separately.
Then all values are scaled so that the largest magnitude value
from all axes equals `scale` (thus, the aspect ratio is preserved).
The resulting NumPy Array is returned (order of rows unchanged).

Parameters
----------
pos : numpy array
    positions to be scaled. Each row is a position.

scale : number (default: 1)
    The size of the resulting extent in all directions.

attribute : str, default None
    If non-None, the position of each node will be stored on the graph as
    an attribute named `attribute` which can be accessed with
    `G.nodes[...][attribute]`. The function still returns the dictionary.

Returns
-------
pos : numpy array
    scaled positions. Each row is a position.

See Also
--------
rescale_layout_dict
r   Nr   )r   r|  r   r8   )r2   r7   r!   lims       r$   r	   r	   Y  sI    D  888C
&&+//
C
Qws{Jr&   c                     SSK nU (       d  0 $ UR                  [        U R                  5       5      5      n[	        X1S9n[        [        X5      5      $ )a  Return a dictionary of scaled positions keyed by node

Parameters
----------
pos : A dictionary of positions keyed by node

scale : number (default: 1)
    The size of the resulting extent in all directions.

Returns
-------
pos : A dictionary of positions keyed by node

Examples
--------
>>> import numpy as np
>>> pos = {0: np.array((0, 0)), 1: np.array((1, 1)), 2: np.array((0.5, 0.5))}
>>> nx.rescale_layout_dict(pos)
{0: array([-1., -1.]), 1: array([1., 1.]), 2: array([0., 0.])}

>>> pos = {0: np.array((0, 0)), 1: np.array((-1, 1)), 2: np.array((-0.5, 0.5))}
>>> nx.rescale_layout_dict(pos, scale=2)
{0: array([ 2., -2.]), 1: array([-2.,  2.]), 2: array([0., 0.])}

See Also
--------
rescale_layout
r   Nr6   )r   r   rG   r~   r	   r-   r.   )r2   r7   r!   pos_vs       r$   r
   r
     sA    : 	HHT#**,'(E5.EC  r&   )r[   r7   r   r1   c                B   [        XS5      u  p[        [        [        R                  " X5      5      5      n[        U 5      [        S UR                  5        5       5      :w  a  [        R                  " S5      e[        XX#US9nUb  [        R                  " XU5        U$ )a\  Position nodes according to breadth-first search algorithm.

Parameters
----------
G : NetworkX graph
    A position will be assigned to every node in G.

start : node in `G`
    Starting node for bfs

center : array-like or None
    Coordinate pair around which to center the layout.

store_pos_as : str, default None
    If non-None, the position of each node will be stored on the graph as
    an attribute with this string as its name, which can be accessed with
    ``G.nodes[...][store_pos_as]``. The function still returns the dictionary.

Returns
-------
pos : dict
    A dictionary of positions keyed by node.

Examples
--------
>>> from pprint import pprint
>>> G = nx.path_graph(4)
>>> pos = nx.bfs_layout(G, 0)
>>> # suppress the returned dict and store on the graph directly
>>> _ = nx.bfs_layout(G, 0, store_pos_as="pos")
>>> pprint(nx.get_node_attributes(G, "pos"))
{0: array([-1.,  0.]),
 1: array([-0.33333333,  0.        ]),
 2: array([0.33333333, 0.        ]),
 3: array([1., 0.])}



Notes
-----
This algorithm currently only works in two dimensions and does not
try to minimize edge crossings.

r(   c              3   8   #    U  H  n[        U5      v   M     g 7frs   r+  r,  s     r$   rx   bfs_layout.<locals>.<genexpr>  s     =_ESZZ_r.  zwbfs_layout didn't include all nodes. Perhaps use input graph:
        G.subgraph(nx.node_connected_component(G, start)))r5  r[   r7   r   )r%   r-   r}   r   
bfs_layersr   r   r~   r   r   r/   )r   startr[   r7   r   r1   r7  r2   s           r$   r   r     s    Z  1-IA )BMM!345F
1v=V]]_===H
 	
 	EvC 
q|4Jr&   )Nr(   NN)r3   Nr(   N)NNr3   Nr(   N)NrP   r3   NgUUUUUU?N)NNN2   -C6?ri   r3   Nr(   NN)NNNr  r  r(   N)	NNNr  r  r(   Nrp   rk   )NNri   r3   Nr(   N)ri   r3   Nr(   N)r(   )r3   Nr(   gffffff?FN)subsetrP   r3   NN)Nr3   g?gư>r   re  rs   )r3   )__doc__networkxr   networkx.utilsr   __all__r%   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r   r   r   _dispatchabler   r	   r
   r   rt   r&   r$   <module>r     sL  $  *(* > >BRl KOi\ 

~B  

		H H HV ,  PT: :z  
		U Up;@ 

	cL*, 2^B+*+6FV 	l` RVm`  			E 
E EP Xnb5IJ 	V 		#V K Vr*Z#!L #-AdQU @r&   