o
    hC                     @   s  d Z ddlZddlmZ g dZdd ZeddId	d
ZdJddZdKddZ		dLddZ
ed										dMddZeZed	dNddZed	dNddZ	dOdd Zd!d" Zd#d$ ZdPd%d&ZdQd'd(ZdQd)d*ZdJd+d,ZdRd/d0ZdSd2d3Zed4			5	6	7	8dTdd9d:d;Zed4	dUd<d=d>d=d.d.dddd.d.ddd?d@dAZdVdBdCZdVdDdEZddddFdGdHZdS )Wa  
******
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                 C   sh   dd l }t| tjst }||  |} |d u r||}n||}t||kr0d}t|| |fS )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msg r"   k/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/networkx/drawing/layout.py_process_params*   s   

r$         c                 C   sJ   ddl }t| ||\} }|t| || }||j}tt| |}|S )aN  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.

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

    Examples
    --------
    >>> G = nx.lollipop_graph(4, 3)
    >>> pos = nx.random_layout(G)

    r   N)r   r$   randr   astypefloat32dictzip)r   r   r   seedr   posr"   r"   r#   r   ?   s   'r      c                 C   s   ddl }|dk rtdt| ||\} }td|d }t| dkr%i }|S t| dkr5tj| |i}|S |ddt| d dd d |j	 }|
|j}||||||t| |fg}t||d| }tt| |}|S )ab  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.

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

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

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> pos = nx.circular_layout(G)

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

    r   Nr&   zcannot handle dimensions < 2r.   scale)r   r   r$   maxr   r   utilsarbitrary_elementlinspacepir(   r)   column_stackcossinr   r   r*   r+   )r   r1   r   r   r   paddimsr-   thetar"   r"   r#   r   p   s&   *("r   c                 C   s  ddl }|dkrtdt| ||\} }t| dkri S t| dkr*tj| |iS |du r3t| g}|t| }t|d dkrDd}n|}|du rQ|jt| }|}	i }
|D ]5}|j	dd|j t|d|j
d|	 }||||||g | }|
t|| ||7 }|	|7 }	qW|
S )	a  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.

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

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

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> shells = [[0], [1, 2, 3]]
    >>> pos = nx.shell_layout(G, shells)

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

    r   Nr&   can only handle 2 dimensionsr.           F)endpointdtype)r   r   r$   r   r   r3   r4   listr6   r5   r)   r7   r8   r9   updater+   )r   nlistrotater1   r   r   r   radius_bumpradiusfirst_thetanposnodesr;   r-   r"   r"   r#   r
      s8   0
"
r
   verticalUUUUUU?c                    s8  ddl }|dvrd}t|t| |dd\} }t| dkri S d}|| }	|	d |d f}
t|  fdd	| D }t | }|dt }||	t|}|d|t }|d|t|}|	||g|
 }|	||g|
 }|
||g}t||d
| }|dkr|dddddf }tt||}|S )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 : list or container
        Nodes in one node set of the bipartite graph.
        This set will be placed on left or top.

    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.

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

    Examples
    --------
    >>> G = nx.bipartite.gnmk_random_graph(3, 5, 10, seed=123)
    >>> top = nx.bipartite.sets(G)[0]
    >>> pos = nx.bipartite_layout(G, top)

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

    r   NrI   
horizontal,align must be either vertical or horizontal.r&   r   r   r.   c                    s   g | ]}| vr|qS r"   r"   ).0vtopr"   r#   
<listcomp>J  s    z$bipartite_layout.<locals>.<listcomp>r0   rL   r/   )r   r   r$   r   r*   fromkeysr@   repeatr5   r7   concatenater   r+   )r   rH   alignr1   r   aspect_ratior   r!   heightwidthoffsetbottomleft_xsright_xsleft_ysright_ystop_pos
bottom_posr-   r"   rQ   r#   r     s2   ,
r   
   2   -C6?weightc                    s  ddl }t| ||	\} }|dur:|du rtd|D ]
}||vr$tdqdd t| D  | fdd|D }|durrtdd	 | D }|dkrOd
}|
t| |	| | }t| D ]\}}||v rp||| ||< q_nd}d
}t| dkr~i S t| d
krt	j
|  |iS z1t| dk rtt	j| |dd}|du r|dur|j\}}||| }t|||||||	|
}W n/ ty   t	j| |d}|du r|dur|j\}}||| }t|||||||	|
}Y nw |du r|durt||d| }tt| |}|S )a  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.

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

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> pos = nx.spring_layout(G)

    # The same using longer but equivalent function name
    >>> pos = nx.fruchterman_reingold_layout(G)
    r   Nz'nodes are fixed without positions givenc                 S      i | ]\}}||qS r"   r"   rO   inoder"   r"   r#   
<dictcomp>      z!spring_layout.<locals>.<dictcomp>c                    s   g | ]
}| v r | qS r"   r"   )rO   rj   nfixedr"   r#   rS     s    z!spring_layout.<locals>.<listcomp>c                 s   s    | ]
}|D ]}|V  qqd S Nr"   )rO   pos_tupcoordr"   r"   r#   	<genexpr>  s    z spring_layout.<locals>.<genexpr>r.     frf   r?   rf   r0   )r   r$   r   	enumerater   r2   valuesr'   r   r   r3   r4   rH   to_scipy_sparse_arrayshapesqrt_sparse_fruchterman_reingoldto_numpy_array_fruchterman_reingoldr   r*   r+   )r   kr-   fixed
iterations	thresholdrf   r1   r   r   r,   r   rj   dom_sizepos_arrri   nAnnodes_r"   rm   r#   r   ]  sd   `

	r      c              
   C   s  dd l }z| j\}	}
W n ty } zd}t||d }~ww |d u r1|j||	|| jd}n|| j}|d u rB|	d|	 }t
t
|jd t|jd  t
|jd t|jd  d }||d  }|j|jd |jd |jd f| jd}t|D ]u}|d d |jd d f ||jd d d d f  }|jj|dd}|j|d	d |d
 |d||| |d  | | |  }|jj|dd}||d	k d|}|d||| }|d urd||< ||7 }||8 }|j||	 |k r |S q|S )Nr   9fruchterman_reingold() takes an adjacency matrix as inputr?         ?r.   皙?r/   axis{Gz?)outz
ijk,ij->ikr&   zij,i->ijr=   )r   rz   AttributeErrorr   NetworkXErrorr   r'   r?   r(   r{   r2   Tminr   rangenewaxislinalgnormclipeinsumwhere)r   r   r-   r   r   r   r   r,   r   r   r   errr!   tdtdelta	iterationdistancedisplacementlength	delta_posr"   r"   r#   r~     sF   >(0r~   c              
   C   s:  dd l }dd l}	z| j\}
}W n ty# } zd}t||d }~ww z|  } W n ty;   |	j|  } Y nw |d u rM|j	|
|
|| jd}n|| j}|d u rYg }|d u rd|d|
 }tt|jd t|jd  t|jd t|jd  d }||d  }|||
f}t|D ]}|d9 }t| jd D ]G}||v rq|| | j}||d jdd}||d	k d	|}| | }|d d |f  ||| |d  || |   jdd7  < q||d jdd}||d	k d|}|| | j}||7 }||8 }|j||
 |k r |S q|S )
Nr   r   r   r   r.   r   r&   r   r   )r   scipyrz   r   r   r   tolilsparse	coo_arrayr   r'   r?   r(   r{   r2   r   r   r   r   sumr   
getrowviewtoarrayr   r   )r   r   r-   r   r   r   r   r,   r   spr   r   r   r!   r   r   r   r   ri   r   r   Air   r   r"   r"   r#   r|   9  s^   >r|   c              	      s:  ddl }t| ||\} }t| }|dkri S |du r#ttj| |d}d|||f }	t| D ]#\}
}||vr9q0|| }t| D ]\}}||vrJqA|| |	|
 |< qAq0 du r||dkrct| |d n|dkrnt	| |d ntt
| |ddt|  | fd	d
| D }t|	|| t |d|  tt
|  S )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.

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

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> pos = nx.kamada_kawai_layout(G)
    r   Nrv   g    .Ar%   )r   r&   r.   c                       g | ]} | qS r"   r"   )rO   r   r-   r"   r#   rS         z'kamada_kawai_layout.<locals>.<listcomp>r0   )r   r$   r   r*   r   shortest_path_lengthonesrw   r   r   r+   r5   array_kamada_kawai_solver   )r   distr-   rf   r1   r   r   r   nNodesdist_mtxrownrrdistcolncr   r"   r   r#   r     s6   +r   c                 C   sb   dd l }dd l}d}|d| || jd d   ||f}|jjt| d|dd}|j	d|fS )Nr   MbP?r.   zL-BFGS-BT)methodargsjacr/   )
r   r   eyerz   optimizeminimize_kamada_kawai_costfnravelxreshape)r   r   r   r   r   meanwtcostargs	optresultr"   r"   r#   r     s   $r   c              	   C   s  |j d }| ||f}|d d |jd d f ||jd d d d f  }|jj|dd}|d|d|||d   }	|| d }
d|
||< d||
d	  }|d
||
|	|d||
|	 }|j|dd}|d| ||d	  7 }||| 7 }||	 fS )Nr   r/   r   zijk,ij->ijkr.   r   r         ?r&   zij,ij,ijk->ikzij,ij,ijk->jk)
rz   r   r   r   r   r   r   diag_indicesr   r   )pos_vecr   invdist
meanweightr   r   r   r   nodesep	directionr[   costgradsumposr"   r"   r#   r     s   
0 r   c              	   C   s*  ddl }t| ||\} }t| dkrAt| dkr|g }nt| dkr+||g}n|||||d g}tt| |S z"t| dk rJttj	| |dd}| 
 r]||| }t||}W n  ttfy   tj| |d	}| 
 r|||j7 }t||}Y nw t||d
| }tt| |}|S )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.

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

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> pos = nx.spectral_layout(G)

    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&   r.          @rs   dru   rv   r0   )r   r$   r   r   r   r*   r+   r   r   ry   is_directed	transpose_sparse_spectralImportErrorr}   r   	_spectralr   )r   rf   r1   r   r   r   r-   r   r"   r"   r#   r     s2   -
r   c              
   C   s   dd l }z| j\}}W n ty } zd}t||d }~ww |j|| jd|j| dd }||  }|j	|\}	}
|
|	d|d  }||
d d |f S )Nr   z-spectral() takes an adjacency matrix as inputr   r.   r   )r   rz   r   r   r   identityr?   r   r   eigargsortreal)r   r   r   r   r   r   r!   DLeigenvalueseigenvectorsindexr"   r"   r#   r   M  s   r   c              
   C   s   dd l }dd l}z| j\}}W n ty# } zd}t||d }~ww |j|j| j	ddd||}||  }	|d }
t
d|
 d t||}|jjj|	|
d|d\}}||d|
 }||d d |f S )Nr   z4sparse_spectral() takes an adjacency matrix as inputr.   r   r&   SM)whichncv)r   r   rz   r   r   r   r   	csr_arrayspdiagsr   r2   intr{   r   eigshr   r   )r   r   r   r   r   r   r   r!   r   r   r   r   r   r   r   r"   r"   r#   r   b  s    "r   c                    s   ddl }|dkrtdt| ||\} }t| dkri S t| tjr%| }nt| \}}|s3tdt	| t
|}| fdd|D   |j t |d|  tt| S )	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.

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

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

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> pos = nx.planar_layout(G)
    r   Nr&   r<   zG is not planar.c                    r   r"   r"   )rO   r   r   r"   r#   rS     r   z!planar_layout.<locals>.<listcomp>r0   )r   r   r$   r   r   r   PlanarEmbeddingcheck_planarityNetworkXExceptioncombinatorial_embedding_to_posr@   vstackr(   float64r   r*   r+   )r   r1   r   r   r   	embedding	is_planar	node_listr"   r   r#   r   }  s"   !

r   ffffff?Fc              	   C   s(  ddl }|dkrtdt| ||\} }t| dkri S t| dkr*tj| |iS g }|rad}d}	|}
|
||	|
  7 }
tt| D ]}|	|
 }|
|| 7 }
||	|
| |
|
| g qBn|jt| td}|| }||||	||
|g }t|||d| }tt| |}|S )	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.

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

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

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> pos = nx.spiral_layout(G)
    >>> nx.draw(G, pos=pos)

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

    r   Nr&   r<   r.   r   r   r0   )r   r   r$   r   r   r3   r4   r   appendr8   r9   arangefloatr   r   r   r*   r+   )r   r1   r   r   
resolutionequidistantr   r-   chordstepr;   r   rr   angler"   r"   r#   r     s2   ,$$r   subsetc                 C   s  ddl }|dvrd}t|t| |dd\} }t| dkri S zt| tdd | D kr4td	W n% tyZ   t	| |}t|t| krRtd
| tj
|}Y nw z
tt| }W n typ   |}Y nw d}	g }
t|}t| D ]>\}}t|}|||}|jd|td}|d d |d d f}|||g| }|	du r|}	n||	|g}	|
| qt|	|d| }	|dkr|	dddddf }	tt|
|	}	|	S )aS  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.

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

    Examples
    --------
    >>> G = nx.complete_multipartite_graph(28, 16, 10)
    >>> pos = nx.multipartite_layout(G)

    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   NrK   rM   r&   rN   c                 s       | ]}t |V  qd S ro   r   rO   rH   r"   r"   r#   rr   ?      z&multipartite_layout.<locals>.<genexpr>z4all nodes must be in one subset of `subset_key` dictz'all nodes need a subset_key attribute: r   r.   r0   rL   r/   )r   r   r$   r   r   rx   r   r   r   get_node_attributesr3   groupsr*   sorteditems	TypeErrorrw   rU   r   r   r7   rV   extendr   r+   )r   
subset_keyrW   r1   r   r   r!   node_to_subsetlayersr-   rH   rZ   ri   layerrY   xsysr[   	layer_posr"   r"   r#   r     sX   .
r   r,   皙?ư>r     r,   c                   s  ddl }ddl}	|dkrd}
t|
tj| |d}|du r |}n|  D ]}||vr2||  ||< q$t| }|dkr=|S |	||f|		| }dd t
| D  |  D ]\}}||krq fdd	||fD \}}||||f< qV|	t| }||	| }|d }d}||kr|dd|	jf ||	j  }|	jj|d
dd|	jf }|  |d |d|	jf | || |  }W d   n1 sw   Y  |	j|dd}||| 7 }|	jj|d
d }||krn|d7 }||kstt|  |S )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 ofunconnected 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.

    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

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

    Examples
    --------
    >>> G = nx.grid_graph((5, 5))
    >>> pos = nx.arf_layout(G)

    r   Nr.   z'The parameter a should be larger than 1r  c                 S   rg   r"   r"   rh   r"   r"   r#   rk     rl   zarf_layout.<locals>.<dictcomp>c                 3   s    | ]} | V  qd S ro   r"   )rO   ri   
node_orderr"   r#   rr     r  zarf_layout.<locals>.<genexpr>r/   r   .ignore)warningsr   r   r   r   rH   copyr   r   r   rw   edgesr   r@   rx   r{   r   r   r   catch_warningssimplefilternansumr   r*   r+   )r   r-   scalingaetolr   max_iterr,   r  r   r!   pos_tmprj   NKr   yidxjdxprhoerrorn_iterdiffr   changer"   r  r#   r   g  sR   @

 r   d   r   r   )r"  jitter_tolerancescaling_ratiogravitydistributed_actionstrong_gravity	node_mass	node_sizerf   dissuade_hubslinlogr,   r   c          ,      C   sF  ddl }t| dkri S |du r"tj| ||d}|t| }n;|t| }|jdd}|jdd}|j	}||
t| |||   }t| D ]\}}||v r\||  ||< qL|t| }|t| }d}|	du rti }	nd}|du r|i }t| D ]\}}||| |d ||< |	|d||< qt| }|||f}|||f}|||f}tj| |
d}d	d
 }d}d} d}!d}"t|D ]P}#|dddf |d  }$|jj|$dd}%|r|d|%  |% }||d |d||}|d|$|}n|d|$| }|r||dddf  }|dddf |d  }&|r6|%|dddf  |d  7 }%|%d }'||&d ||'d |&|' | }(|d|$|(}| |dddf  | |jj|dddddf  }|r||jj|dddddf 9 }|| | })|!||jj||) dd  7 }!|"d| |jj||) dd  7 }"|||!|"|| |\}} |r||jj|)dd }*d| d|||*   }(|jj|)dd}+||(|+ d||+j |+ }(n||jj|)dd }*|d|||*   }(||)|(dddf  7 }t|)|(dddf   dk r nqtt| |S )a
  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.
    distributed_attraction : 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.
    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.

    Examples
    --------
    >>> import networkx as nx
    >>> G = nx.florentine_families_graph()
    >>> pos = nx.forceatlas2_layout(G)
    >>> nx.draw(G, pos=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   r,   r   FTr.   rv   c                 S   s   ddl }d||  }||}d}	d}
t|	|| | d  }|t|| }|| dkr9||
kr4|d9 }t||}|dkrA|j}n|| | | }||| krX||
krW|d9 }n|d	k r`|d
9 }d}|t|| ||  }||fS )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?rc   r&   r   r   gffffff?r  g?)r   r{   r   r2   inf)r   swingtractionspeedspeed_efficiencyr0  r   
opt_jitter
min_jitter
max_jittermin_speed_efficiencyotherjittertarget_speedmax_riser"   r"   r#   estimate_factorV  s.   "

z+forceatlas2_layout.<locals>.estimate_factorr/   zij, ij -> ijzijk, ij -> ikr&   r   r   g      $@g|=)r   r   r   r   r   r@   rx   r2   r   sizer'   rw   r  r   getdegreer}   r   r   r   logfill_diagonalr   r   r{   minimumr   rz   absr*   r+   ),r   r-   r"  r0  r1  r2  r3  r4  r5  r6  rf   r7  r8  r,   r   r   r   pos_initmax_posmin_posr'  rj   massrG  adjust_sizesr   	gravities
attraction	repulsionr   rF  r<  r=  r:  r;  r   r-  r   tmpd2factorrA   swingingdfr"   r"   r#   r     s   K@  $
""r   c                 C   s>   ddl }| | jdd8 } ||  }|dkr| || 9 } | S )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.

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

    See Also
    --------
    rescale_layout_dict
    r   Nr   )r   meanrM  r2   )r-   r1   r   limr"   r"   r#   r     s   r   c                 C   s<   ddl }| si S |t|  }t||d}tt| |S )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   Nr0   )r   r   r@   rx   r   r*   r+   )r-   r1   r   pos_vr"   r"   r#   r	     s   r	   )rW   r1   r   c                C   s^   t | |d\} }ttt| |}t| tdd | D kr&tdt	| ||||dS )au  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.

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

    Examples
    --------
    >>> G = nx.path_graph(4)
    >>> pos = nx.bfs_layout(G, 0)

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

    r&   c                 s   r  ro   r  r  r"   r"   r#   rr   U  r  zbfs_layout.<locals>.<genexpr>zwbfs_layout didn't include all nodes. Perhaps use input graph:
        G.subgraph(nx.node_connected_component(G, start)))r  rW   r1   r   )
r$   r*   rw   r   
bfs_layersr   r   rx   r   r   )r   startrW   r1   r   r  r"   r"   r#   r   2  s   
r   )Nr&   N)r.   Nr&   )NNr.   Nr&   )rI   r.   NrJ   )
NNNrd   re   rf   r.   Nr&   N)NNNrd   re   r&   N)NNrf   r.   Nr&   )rf   r.   Nr&   )r&   )r.   Nr&   r   F)r   rI   r.   N)Nr.   r  r  r   r  ro   )r.   )__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   r   r	   r   r"   r"   r"   r#   <module>   s    
0
D\
N =I
M

O


9
Ob	y  

(&