
    h                     \   S r SSKrSSKrSSKJr  SSKJrJrJ	r	  / SQr
S rS r\" S5      \R                  " S	S
9SS j5       5       rS r\R                  " S	S
9 SS j5       r\" S5      \	" S5      \R                  " S	SS9SS j5       5       5       r\R                  " S	SSS9SS j5       r\R                  S 5       r\R                  " S	S
9SS j5       r\	" S5      \R                  " S	S
9        SS j5       5       r\	" S5      \R                  " S	S
9        SS j5       5       rg) a  
=================================
Travelling Salesman Problem (TSP)
=================================

Implementation of approximate algorithms
for solving and approximating the TSP problem.

Categories of algorithms which are implemented:

- Christofides (provides a 3/2-approximation of TSP)
- Greedy
- Simulated Annealing (SA)
- Threshold Accepting (TA)
- Asadpour Asymmetric Traveling Salesman Algorithm

The Travelling Salesman Problem tries to find, given the weight
(distance) between all points where a salesman has to visit, the
route so that:

- The total distance (cost) which the salesman travels is minimized.
- The salesman returns to the starting point.
- Note that for a complete graph, the salesman visits each point once.

The function `travelling_salesman_problem` allows for incomplete
graphs by finding all-pairs shortest paths, effectively converting
the problem to a complete graph problem. It calls one of the
approximate methods on that problem and then converts the result
back to the original graph using the previously found shortest paths.

TSP is an NP-hard problem in combinatorial optimization,
important in operations research and theoretical computer science.

http://en.wikipedia.org/wiki/Travelling_salesman_problem
    N)random_spanning_tree)not_implemented_forpairwisepy_random_state)traveling_salesman_problemchristofidesasadpour_atsp
greedy_tspsimulated_annealing_tspthreshold_accepting_tspc                 p    UR                  [        S[        U 5      S-
  5      SS9u  p#X   X   sX'   X'   U $ )a  Swap two nodes in `soln` to give a neighbor solution.

Parameters
----------
soln : list of nodes
    Current cycle of nodes

seed : integer, random_state, or None (default)
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`.

Returns
-------
list
    The solution after move is applied. (A neighbor solution.)

Notes
-----
    This function assumes that the incoming list `soln` is a cycle
    (that the first and last element are the same) and also that
    we don't want any move to change the first node in the list
    (and thus not the last node either).

    The input list is changed as well as returned. Make a copy if needed.

See Also
--------
    move_one_node
      k)samplerangelensolnseedabs       f/var/www/html/env/lib/python3.13/site-packages/networkx/algorithms/approximation/traveling_salesman.pyswap_two_nodesr   5   s@    < ;;uQD	A.!;4DAwDGTWK    c                     UR                  [        S[        U 5      S-
  5      SS9u  p#U R                  X0R	                  U5      5        U $ )am  Move one node to another position to give a neighbor solution.

The node to move and the position to move to are chosen randomly.
The first and last nodes are left untouched as soln must be a cycle
starting at that node.

Parameters
----------
soln : list of nodes
    Current cycle of nodes

seed : integer, random_state, or None (default)
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`.

Returns
-------
list
    The solution after move is applied. (A neighbor solution.)

Notes
-----
    This function assumes that the incoming list `soln` is a cycle
    (that the first and last element are the same) and also that
    we don't want any move to change the first node in the list
    (and thus not the last node either).

    The input list is changed as well as returned. Make a copy if needed.

See Also
--------
    swap_two_nodes
r   r   r   )r   r   r   insertpopr   s       r   move_one_noder    X   sA    D ;;uQD	A.!;4DAKK88A;Kr   directedweight)
edge_attrsc                 B  ^
 [         R                  " U 5      n [        U5      nU R                  5       n U R	                  XD5        U R                  S U 5       5        [        U 5      S-
  m
[        U
4S jU R                  R                  5        5       5      (       a  [         R                  " S5      eUc  [         R                  " XS9nU R                  5       nUR                  UR                   VVs/ s H  u  pgUS-  (       a  M  UPM     snn5        [         R                  " 5       nUR!                  UR"                  5        [         R$                  " XQS9n	UR!                  U	5        ['        [         R(                  " U5      5      $ ! [         a     GN:f = fs  snnf )a  Approximate a solution of the traveling salesman problem

Compute a 3/2-approximation of the traveling salesman problem
in a complete undirected graph using Christofides [1]_ algorithm.

Parameters
----------
G : Graph
    `G` should be a complete weighted undirected graph.
    The distance between all pairs of nodes should be included.

weight : string, optional (default="weight")
    Edge data key corresponding to the edge weight.
    If any edge does not have this attribute the weight is set to 1.

tree : NetworkX graph or None (default: None)
    A minimum spanning tree of G. Or, if None, the minimum spanning
    tree is computed using :func:`networkx.minimum_spanning_tree`

Returns
-------
list
    List of nodes in `G` along a cycle with a 3/2-approximation of
    the minimal Hamiltonian cycle.

References
----------
.. [1] Christofides, Nicos. "Worst-case analysis of a new heuristic for
   the travelling salesman problem." No. RR-388. Carnegie-Mellon Univ
   Pittsburgh Pa Management Sciences Research Group, 1976.
c              3   (   #    U  H  oU4v   M
     g 7fN ).0ns     r   	<genexpr>christofides.<locals>.<genexpr>   s     7JqFJs   r   c              3   D   >#    U  H  u  p[        U5      T:g  v   M     g 7fr&   r   r(   r)   nbrdictNs      r   r*   r+      s     
=}3w<1}s    G must be a complete graph.r"   r   )nxnodes_with_selfloopsnextcopyremove_edgeremove_edges_fromStopIterationr   anyadjitemsNetworkXErrorminimum_spanning_treeremove_nodes_fromdegree
MultiGraphadd_edges_fromedgesmin_weight_matching_shortcuttingeulerian_circuit)Gr"   tree
loop_nodesnodeLvr@   MGrC   r0   s             @r   r   r      s?   F ((+J8J FFH	d!	7J77A
A

=quu{{}
===<==|''9	ADKKLKyq
KLM	Bdjj!""14Ee,,R011)   Ms   F
 4F
F


FFc                     / nU  H5  u  p#X1;   a  M  U(       d  UR                  U5        UR                  U5        M7     UR                  US   5        U$ )z"Remove duplicate nodes in the pathr   )append)circuitnodesurL   s       r   rE   rE      sK    E:LLOQ  
LLqLr   Tc                 ~  ^ Uc"  U R                  5       (       a  [        nO[        nUc  [        U R                  5      n0 m0 n[
        R                  " XS9 H  u  nu  pUTU'   XU'   M     U R                  5       (       aG  [
        R                  " U 5      (       d  [
        R                  " S5      e[
        R                  " 5       n
O[
        R                  " 5       n
U H)  nU H   nX:X  a  M
  U
R                  XTU   U   S9  M"     M+     U" U
4SU0UD6nU(       d_  [        [        U5      U4S jS9u  pUR                  U5      S-   nX   U:w  a   XS R                  U5      S-   nX   U:w  a  M   XS USU -   n/ n[        U5       H  u  pUR                  Xk   U   SS 5        M      UR!                  W5        U$ )	aV  Find the shortest path in `G` connecting specified nodes

This function allows approximate solution to the traveling salesman
problem on networks that are not complete graphs and/or where the
salesman does not need to visit all nodes.

This function proceeds in two steps. First, it creates a complete
graph using the all-pairs shortest_paths between nodes in `nodes`.
Edge weights in the new graph are the lengths of the paths
between each pair of nodes in the original graph.
Second, an algorithm (default: `christofides` for undirected and
`asadpour_atsp` for directed) is used to approximate the minimal Hamiltonian
cycle on this new graph. The available algorithms are:

 - christofides
 - greedy_tsp
 - simulated_annealing_tsp
 - threshold_accepting_tsp
 - asadpour_atsp

Once the Hamiltonian Cycle is found, this function post-processes to
accommodate the structure of the original graph. If `cycle` is ``False``,
the biggest weight edge is removed to make a Hamiltonian path.
Then each edge on the new complete graph used for that analysis is
replaced by the shortest_path between those nodes on the original graph.
If the input graph `G` includes edges with weights that do not adhere to
the triangle inequality, such as when `G` is not a complete graph (i.e
length of non-existent edges is infinity), then the returned path may
contain some repeating nodes (other than the starting node).

Parameters
----------
G : NetworkX graph
    A possibly weighted graph

nodes : collection of nodes (default=G.nodes)
    collection (list, set, etc.) of nodes to visit

weight : string, optional (default="weight")
    Edge data key corresponding to the edge weight.
    If any edge does not have this attribute the weight is set to 1.

cycle : bool (default: True)
    Indicates whether a cycle should be returned, or a path.
    Note: the cycle is the approximate minimal cycle.
    The path simply removes the biggest edge in that cycle.

method : function (default: None)
    A function that returns a cycle on all nodes and approximates
    the solution to the traveling salesman problem on a complete
    graph. The returned cycle is then used to find a corresponding
    solution on `G`. `method` should be callable; take inputs
    `G`, and `weight`; and return a list of nodes along the cycle.

    Provided options include :func:`christofides`, :func:`greedy_tsp`,
    :func:`simulated_annealing_tsp` and :func:`threshold_accepting_tsp`.

    If `method is None`: use :func:`christofides` for undirected `G` and
    :func:`asadpour_atsp` for directed `G`.

**kwargs : dict
    Other keyword arguments to be passed to the `method` function passed in.

Returns
-------
list
    List of nodes in `G` along a path with an approximation of the minimal
    path through `nodes`.

Raises
------
NetworkXError
    If `G` is a directed graph it has to be strongly connected or the
    complete version cannot be generated.

Examples
--------
>>> tsp = nx.approximation.traveling_salesman_problem
>>> G = nx.cycle_graph(9)
>>> G[4][5]["weight"] = 5  # all other weights are 1
>>> tsp(G, nodes=[3, 6])
[3, 2, 1, 0, 8, 7, 6, 7, 8, 0, 1, 2, 3]
>>> path = tsp(G, cycle=False)
>>> path in ([4, 3, 2, 1, 0, 8, 7, 6, 5], [5, 6, 7, 8, 0, 1, 2, 3, 4])
True

While no longer required, you can still build (curry) your own function
to provide parameter values to the methods.

>>> SA_tsp = nx.approximation.simulated_annealing_tsp
>>> method = lambda G, weight: SA_tsp(G, "greedy", weight=weight, temp=500)
>>> path = tsp(G, cycle=False, method=method)
>>> path in ([4, 3, 2, 1, 0, 8, 7, 6, 5], [5, 6, 7, 8, 0, 1, 2, 3, 4])
True

Otherwise, pass other keyword arguments directly into the tsp function.

>>> path = tsp(
...     G,
...     cycle=False,
...     method=nx.approximation.simulated_annealing_tsp,
...     init_cycle="greedy",
...     temp=500,
... )
>>> path in ([4, 3, 2, 1, 0, 8, 7, 6, 5], [5, 6, 7, 8, 0, 1, 2, 3, 4])
True
Nr2   zG is not strongly connectedr"   c                     > TU S      U S      $ )Nr   r   r'   )xdists    r   <lambda>,traveling_salesman_problem.<locals>.<lambda>W  s    d1Q4j16Fr   keyr   )is_directedr	   r   listrQ   r3   all_pairs_dijkstrais_strongly_connectedr=   DiGraphGraphadd_edgemaxr   indexextendrO   )rG   r"   rQ   cyclemethodkwargspathr)   dpGGrR   rL   best_GGpos	best_pathrV   s                   @r   r   r      s   ^ ~==??"F!F}QWWDD**1<	6AQQ = 	}}''**""#@AAZZ\XXZAvKKT!WQZK0   R11&1GXg&,FGmmA"la$-%%a(1,C lab/GDSM1I!CR) "Qr   
undirectedr   )r#   mutates_inputc           
        ^ SSK JnJn  SSK Jn  [	        U 5      S-
  mTS:  a  [
        R                  " S5      e[        U4S jU R                  R                  5        5       5      (       a  [
        R                  " S5      eUb%  X0R                  ;  a  [
        R                  " S
5      e[        X5      u  px[        U[        5      (       d  [        [
        R                  " XS95      $ [
        R                   " 5       n	U HH  u  pX4U	R"                  ;  d  M  [%        X
   U   U   X   U
   U   5      nU	R&                  " X40 X0D6  MJ     [)        X5      n[
        R*                  " U	5      n	U	R#                  5        V
Vs0 s H  u  pX4U" XU4   5      _M     nn
n[
        R,                  " XS5        AAS	n[         R.                  n[1        SU" U" U R3                  5       5      5      -  5       H9  n[5        U	SUS9nUR7                  U5      nUU:  d  M'  UR9                  5       nUnM;     [
        R:                  " 5       nUR#                  US9 H@  u  pnUX
   U   U   :X  a  UR&                  " X40 UU0D6  M+  UR&                  " X40 UU0D6  MB     U Vs0 s H'  nUUR=                  U5      UR?                  U5      -
  _M)     nn[
        R@                  " U US5        [
        RB                  " U S5      nUR                  5        HU  u  nnU HI  nUU4UR"                  ;  d  M  UU   S:  d  M"  [1        UU   5       H  nUR'                  UU5        M     MK     MW     [
        R                  " UUS9n[        U5      $ s  snn
f s  snf )u	  
Returns an approximate solution to the traveling salesman problem.

This approximate solution is one of the best known approximations for the
asymmetric traveling salesman problem developed by Asadpour et al,
[1]_. The algorithm first solves the Held-Karp relaxation to find a lower
bound for the weight of the cycle. Next, it constructs an exponential
distribution of undirected spanning trees where the probability of an
edge being in the tree corresponds to the weight of that edge using a
maximum entropy rounding scheme. Next we sample that distribution
$2 \lceil \ln n \rceil$ times and save the minimum sampled tree once the
direction of the arcs is added back to the edges. Finally, we augment
then short circuit that graph to find the approximate tour for the
salesman.

Parameters
----------
G : nx.DiGraph
    The graph should be a complete weighted directed graph. The
    distance between all paris of nodes should be included and the triangle
    inequality should hold. That is, the direct edge between any two nodes
    should be the path of least cost.

weight : string, optional (default="weight")
    Edge data key corresponding to the edge weight.
    If any edge does not have this attribute the weight is set to 1.

seed : integer, random_state, or None (default)
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`.

source : node label (default=`None`)
    If given, return the cycle starting and ending at the given node.

Returns
-------
cycle : list of nodes
    Returns the cycle (list of nodes) that a salesman can follow to minimize
    the total weight of the trip.

Raises
------
NetworkXError
    If `G` is not complete or has less than two nodes, the algorithm raises
    an exception.

NetworkXError
    If `source` is not `None` and is not a node in `G`, the algorithm raises
    an exception.

NetworkXNotImplemented
    If `G` is an undirected graph.

References
----------
.. [1] A. Asadpour, M. X. Goemans, A. Madry, S. O. Gharan, and A. Saberi,
   An o(log n/log log n)-approximation algorithm for the asymmetric
   traveling salesman problem, Operations research, 65 (2017),
   pp. 1043–1061

Examples
--------
>>> import networkx as nx
>>> import networkx.algorithms.approximation as approx
>>> G = nx.complete_graph(3, create_using=nx.DiGraph)
>>> nx.set_edge_attributes(
...     G,
...     {(0, 1): 2, (1, 2): 2, (2, 0): 2, (0, 2): 1, (2, 1): 1, (1, 0): 1},
...     "weight",
... )
>>> tour = approx.asadpour_atsp(G, source=0)
>>> tour
[0, 2, 1, 0]
r   )ceilexplogr   r   zG must have at least two nodesc              3   N   >#    U  H  u  p[        U5      X;   -
  T:g  v   M     g 7fr&   r-   r.   s      r   r*    asadpour_atsp.<locals>.<genexpr>  #     
N*!3w<1<(A-   "%zG is not a complete DiGraphNzGiven source node not in G.)sourcer"   )r   datademand)"mathrs   rt   rv   r   r3   r=   r:   r;   r<   rQ   held_karp_ascent
isinstancedictrE   rF   rA   rC   minrb   spanning_tree_distributionra   set_edge_attributesinfr   number_of_nodesr   sizer6   MultiDiGraph
out_degree	in_degreeset_node_attributesmin_cost_flow)rG   r"   r   r{   rs   rt   lnopt_hkz_star	z_supportrR   rL   edge_weightgammalambda_dictminimum_sampled_treeminimum_sampled_tree_weight_sampled_treesampled_tree_weightt_starrj   r)   node_demands	flow_dictvaluestargetrP   r0   s                               @r   r	   r	   d  s8   \  	A
A1u?@@

N
NNN<==fGG3<==%a0NF
 fd## R00GHH I6(ad1gfoqtAwv?Kq='<=  'y9E #I:C//:KL:K$!A63uV}--:KKL98<{  "&((1tBq0023445+IxdK*//7!<<#/#4#4#6 *=' 6 __F'--6-:aQOOA0VQK0OOA0VQK0	 ; LRR6aAv((+f.>.>q.AAA6LR1lH5   H-I $//+Fv||3v8Jvf~.AOOFF3 /  , !!&8G!!O M. Ss    N.N)r#   rq   returns_graphc           	      b  ^ ^^^^ SSK mSSKJm  U U4S jmU UUU4S jnU U4S jn0 nT  H  nSXE'   M	     A0 nT R                  SS9 H  u  pxn	U	T   XgU4'   M     U" 5       u  pU
bd  U" X5      nU
R	                  5        H  u  pXXE==   X-  -  ss'   M     T R                  SS9 H  u  pxn	XgU4   XG   -   U	T'   M     U" 5       u  pU
b  Md  [
        R                  " T 5        UnU H\  n[        U Vs/ s H  o^R                  U5      S	:X  d  M  UPM     sn5      T R                  5       :X  d  MI  UR                  T5      U4s  $    0 n[        U5      nT R                  SS9 HM  u  pxn	SnXgU4   U	T'   U H-  nXx4UR                  5       ;   d  M  US
-  nXgU4   X   U   T'   M/     UU-  XU4'   MO     0 nT R                  5       S
-
  T R                  5       -  nU H#  u  pxXU4   XU4   -   nUS:  d  M  UU-  UXx4'   M%     A[        UR                  5       5      R                  T5      U4$ s  snf )ul  
Minimizes the Held-Karp relaxation of the TSP for `G`

Solves the Held-Karp relaxation of the input complete digraph and scales
the output solution for use in the Asadpour [1]_ ASTP algorithm.

The Held-Karp relaxation defines the lower bound for solutions to the
ATSP, although it does return a fractional solution. This is used in the
Asadpour algorithm as an initial solution which is later rounded to a
integral tree within the spanning tree polytopes. This function solves
the relaxation with the branch and bound method in [2]_.

Parameters
----------
G : nx.DiGraph
    The graph should be a complete weighted directed graph.
    The distance between all paris of nodes should be included.

weight : string, optional (default="weight")
    Edge data key corresponding to the edge weight.
    If any edge does not have this attribute the weight is set to 1.

Returns
-------
OPT : float
    The cost for the optimal solution to the Held-Karp relaxation
z : dict or nx.Graph
    A symmetrized and scaled version of the optimal solution to the
    Held-Karp relaxation for use in the Asadpour algorithm.

    If an integral solution is found, then that is an optimal solution for
    the ATSP problem and that is returned instead.

References
----------
.. [1] A. Asadpour, M. X. Goemans, A. Madry, S. O. Gharan, and A. Saberi,
   An o(log n/log log n)-approximation algorithm for the asymmetric
   traveling salesman problem, Operations research, 65 (2017),
   pp. 1043–1061

.. [2] M. Held, R. M. Karp, The traveling-salesman problem and minimum
       spanning trees, Operations Research, 1970-11-01, Vol. 18 (6),
       pp.1138-1162
r   N)optimizec            	      <  > TR                  5       n [        5       n[        R                  n[	        TR                  5       5      nU R                  U5        SST[        R                  0nSST[        R                  * 0nTR                  USS9 H2  u  pgnUT   UT   :  a	  SUTUT   0nUT   UT   :  d  M)  SUTUT   0nM4     [        TR                  USS9U4S jS9n	UT   U	S   T   -   UT'   UT   U	S   T   -   UT'   [        R                  n
[        R                  " U 5       GHg  nUR                  T5      nU
[        R                  :X  a  Un
OXUT   -   UT   -
  :  a    U$ UR                   H9  u  pUS:X  d  M  UR                  " X=40 TTU   U   T   0D6  UTU   U   T   -  n  O   TW   U   nTR                  X5        [        TR                  UTS9S	 S9S   nTR                  UTS9 VVVs/ s H  u  pgoU:X  d  M  XgU4PM     nnnnU H`  u  pgnUR                  5       nUR                  " Xg40 TU0D6  X-   nUU:  a  UR!                  5         UnUU:X  d  MO  UR#                  U5        Mb     TR                  " X40 UD6  GMj     U$ s  snnnf )
zx
Find the set of minimum 1-Arborescences for G at point pi.

Returns
-------
Set
    The set of minimum 1-Arborescences
rJ   NTr|   c                    > U S   T   $ Nr   r'   )rU   r"   s    r   rW   0held_karp_ascent.<locals>.k_pi.<locals>.<lambda>S  s    !A$v,r   rY   r   r   c                     U S   $ r   r'   )rU   s    r   rW   r   o  s    qtr   )r6   setr   r   r5   __iter__remove_noderC   r   in_edgesr3   ArborescenceIteratorr   r   rb   r7   clearadd)G_1minimum_1_arborescencesminimum_1_arborescence_weightr)   min_rootmax_rootrR   rL   rj   min_in_edgemin_arb_weightarb
arb_weightr0   deg	edge_data
min_weight	min_edgesnew_arbnew_arb_weightrG   r"   s                       r   k_piheld_karp_ascent.<locals>.k_pi1  s    ffh"%%(,%  D&$((3D&488)4wwqtw,GA!y8F++"Avqy9y8F++"Avqy9	 - !**QT*28NO#F+k!nV.DD#F+k!nV.DD**3/C&)J)!+x/??(6BRRRL '&E --!8LLC&!A$q'&/)BC!A$q'&/1J ( !QIMM!QZZZ7^LQOJ)*AF)C)CgaAJ	q	)C   %a((*  5&!5!+
 "$AA+1134B1!%BB+//8 % JJq)y)S 0V '&'s   ;J
J
c                    > 0 n T H  nSX'   M	     AT" 5       n [         R                  nSnU H2  nSnUR                   H  u  pX`U   US-
  -  -  nM     Xc:  d  M.  UnUnM4     US:  a  X4$ UR                   H  u  pX==   US-
  -  ss'   M     TR                  [	        U5      S[
        S9nTR                  [	        T5      S-   [	        U5      4[
        S9n	TR                  [	        T5      S-   [
        S9n
SU
[	        T5      '   [        U5       HH  u  p[	        T5      S-
  nUR                   H  u  pUS-
  X   U'   US-  nM     SU	[	        T5         U'   MJ     TR                  XU
SS9nUR                  (       a  SU4$ GMn  )	ah  
Find the direction of ascent at point pi.

See [1]_ for more information.

Returns
-------
dict
    A mapping from the nodes of the graph which represents the direction
    of ascent.

References
----------
.. [1] M. Held, R. M. Karp, The traveling-salesman problem and minimum
   spanning trees, Operations Research, 1970-11-01, Vol. 18 (6),
   pp.1138-1162
r   Nr   r[   )dtyper   z	highs-ipm)A_eqb_eqrg   )r   r   r@   fullr   intemptyzeros	enumeratelinprogsuccess)rj   r)   r   min_k_d_weightmin_k_darborescenceweighted_costr   ca_eqr   	arb_countn_countprogram_resultrG   r   npr   s                 r   direction_of_ascent-held_karp_ascent.<locals>.direction_of_ascent  s   & AAD "&& "XXNG 7 !*11FA!qTS1W%55M 2 1%2N*G !8 !z!!..a )
 34bDA88SVaZ-D)EFc8RD88CFQJc82DDQL+45L+M'	a&1**11FA/2QwDM),qLG 2 +,SVY' ,N &--4 . N %%444O r   c                   > [         R                  nT
R                  TS9 GHg  u  p4nX44U R                  ;   a  M  [        U R	                  UTS95      S:  a  [
        e[        U R	                  UTS9R                  5       5      u  pgnU R                  " X440 TU0D6  U R                  Xg5        [        S U R                  5        5       5      S::  a  [        T
5      U R                  5       :X  as  [        R                  " U 5      (       aX  X   X   :X  d  X:X  a)  U R                  X45        U R                  " Xg40 TU0D6  GM!  X-
  X   X   -
  -  n	SU	s=:  a  U:  a  O  OU	nU R                  X45        U R                  " Xg40 TU0D6  GMj     U$ )aR  
Given the direction of ascent at pi, find the maximum distance we can go
in that direction.

Parameters
----------
k_xy : set
    The set of 1-arborescences which have the minimum rate of increase
    in the direction of ascent

d : dict
    The direction of ascent

Returns
-------
float
    The distance we can travel in direction `d`
r|   r   c              3   *   #    U  H	  u  pUv   M     g 7fr&   r'   )r(   r)   rj   s      r   r*   9held_karp_ascent.<locals>.find_epsilon.<locals>.<genexpr>  s     0-$!A-s   r   )r   r   rC   r   r   	Exceptionr5   r   rb   r7   rc   r   number_of_edgesr3   is_weakly_connected)r   rj   min_epsilone_ue_ve_wsub_usub_vsub_wepsilonrG   r"   s             r   find_epsilon&held_karp_ascent.<locals>.find_epsilon  sf   & hhWW&W1MCczQWW$ 1::c:/014"&qzz#Fz'C'L'L'N"OE%JJs1FC=1MM%'0!++-00A5Fa//11**1-- 8qv%MM#+JJu?? ;16AH+<=w,,")KMM##JJu77A 2D r   Tr|   r   r   )numpyscipyr   rC   r<   r3   _clear_cacher   r@   orderr   r5   r   )rG   r"   r   r   pi_dictr)   original_edge_weightsrR   rL   rj   
dir_ascentk_dmax_distancek_maxr   x_star
size_k_max
edge_countr   scale_factor	frequencyr   r   r   s   ``                   @@@r   r   r      se   \ R'h@5 @5H6v G
 	777%a()&	!f% &)+OJ

 #C4$$&DAJ,**J 'wwDw)GA!-!f5
BAfI *-/
 
  OOA E 111aq 0112aggi? 66&>1$$	  FUJ777%a
)a&1&	Av"a
"7A"?Q  $j01v & FGGIMQWWY.Lq6NVF^3	q=)I5FA6N  	 !&&v.669 2s   1H,
H,
c                 H  ^ ^^^ SSK Jm  SSK Jn  U UUU4S jn0 mT R                   H  u  pEnSTXE4'   M     SnSm SnT H  u  pEXE4n	U" U	5      n
X   nU
SU-   U-  :  a  U" U
SSUS	-  -   U-  -
  -  SU
-
  SUS	-  -   -  U-  -  5      nTU	==   U-  ss'   U" U	5      nSUS	-  -   U-  n[	        US
5      [	        US
5      :w  a  [
        R                  " SU SU S35      eM  US-  nM     U[        T5      :X  a  OM  T R                  SS9 H  u    poTU;   d  M  UT	 M     T$ )a  
Find the asadpour exponential distribution of spanning trees.

Solves the Maximum Entropy Convex Program in the Asadpour algorithm [1]_
using the approach in section 7 to build an exponential distribution of
undirected spanning trees.

This algorithm ensures that the probability of any edge in a spanning
tree is proportional to the sum of the probabilities of the tress
containing that edge over the sum of the probabilities of all spanning
trees of the graph.

Parameters
----------
G : nx.MultiGraph
    The undirected support graph for the Held Karp relaxation

z : dict
    The output of `held_karp_ascent()`, a scaled version of the Held-Karp
    solution.

Returns
-------
gamma : dict
    The probability distribution which approximately preserves the marginal
    probabilities of `z`.
r   )rt   ru   c                   > TR                  SS9 H  u  pnT" T	X4   5      UT
'   M     [        R                  " TT
5      n[        R                  " TU SS9n[        R                  " UT
5      nT" T	U S   U S   4   5      U-  U-  $ )a  
The value of q(e) is described in the Asadpour paper is "the
probability that edge e will be included in a spanning tree T that is
chosen with probability proportional to exp(gamma(T))" which
basically means that it is the total probability of the edge appearing
across the whole distribution.

Parameters
----------
e : tuple
    The `(u, v)` tuple describing the edge we are interested in

Returns
-------
float
    The probability that a spanning tree chosen according to the
    current values of gamma will include edge `e`.
Tr|   F)
self_loopsr   r   )rC   r3   total_spanning_tree_weightcontracted_edge)erR   rL   rj   G_KirchhoffG_eG_e_KirchhoffrG   rt   r   
lambda_keys          r   q%spanning_tree_distribution.<locals>.q[  s    ( wwDw)GA!qf.AjM *33AzB  A%855c:F 5!A$!&'-7+EEr   g?z=spanning_tree_distribution's secret attribute name for lambdaTr   r      z'Unable to modify probability for edge (z, )r|   )r   rt   rv   rC   roundr3   r=   r   )rG   zr   r   rR   rL   r   EPSILONin_range_countr   q_ez_edeltanew_q_edesired_q_erj   rt   r   r   s   `               @@@r   r   r   ;  s   : F F> E77aqf  G QJ

 DAAA$C$Ca'kS((AWq[C 778CA!O4s:< aE!A$ 7Q;#5!$k1(==**A!BqcK  >
 !#% ( SZ'9 > 777%1?* & Lr   c                 T  ^^^ [        U 5      S-
  m[        U4S jU R                  R                  5        5       5      (       a  [        R
                  " S5      eUc  [        R                  R                  U 5      nU R                  5       S:X  a  [        U R                  U5      5      nX#U/$ [        U 5      nUR                  U5        U/nUnU(       a>  X   m[        UUU4S jS9nUR                  U5        UR                  U5        U(       a  M>  UR                  US   5        U$ )a	  Return a low cost cycle starting at `source` and its cost.

This approximates a solution to the traveling salesman problem.
It finds a cycle of all the nodes that a salesman can visit in order
to visit many nodes while minimizing total distance.
It uses a simple greedy algorithm.
In essence, this function returns a large cycle given a source point
for which the total cost of the cycle is minimized.

Parameters
----------
G : Graph
    The Graph should be a complete weighted undirected graph.
    The distance between all pairs of nodes should be included.

weight : string, optional (default="weight")
    Edge data key corresponding to the edge weight.
    If any edge does not have this attribute the weight is set to 1.

source : node, optional (default: first node in list(G))
    Starting node.  If None, defaults to ``next(iter(G))``

Returns
-------
cycle : list of nodes
    Returns the cycle (list of nodes) that a salesman
    can follow to minimize total weight of the trip.

Raises
------
NetworkXError
    If `G` is not complete, the algorithm raises an exception.

Examples
--------
>>> from networkx.algorithms import approximation as approx
>>> G = nx.DiGraph()
>>> G.add_weighted_edges_from(
...     {
...         ("A", "B", 3),
...         ("A", "C", 17),
...         ("A", "D", 14),
...         ("B", "A", 3),
...         ("B", "C", 12),
...         ("B", "D", 16),
...         ("C", "A", 13),
...         ("C", "B", 12),
...         ("C", "D", 4),
...         ("D", "A", 14),
...         ("D", "B", 15),
...         ("D", "C", 2),
...     }
... )
>>> cycle = approx.greedy_tsp(G, source="D")
>>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
>>> cycle
['D', 'C', 'B', 'A', 'D']
>>> cost
31

Notes
-----
This implementation of a greedy algorithm is based on the following:

- The algorithm adds a node to the solution at every iteration.
- The algorithm selects a node not already in the cycle whose connection
  to the previous node adds the least cost to the cycle.

A greedy algorithm does not always give the best solution.
However, it can construct a first feasible solution which can
be passed as a parameter to an iterative improvement algorithm such
as Simulated Annealing, or Threshold Accepting.

Time complexity: It has a running time $O(|V|^2)$
r   c              3   N   >#    U  H  u  p[        U5      X;   -
  T:g  v   M     g 7fr&   r-   r.   s      r   r*   greedy_tsp.<locals>.<genexpr>  ry   rz   r1   r   c                 .   > TU    R                  TS5      $ )Nr   get)r)   r/   r"   s    r   rW   greedy_tsp.<locals>.<lambda>
  s    wqz~~fa/Hr   rY   r   )r   r:   r;   r<   r3   r=   utilsarbitrary_elementr   r5   	neighborsr   remover   rO   )	rG   r"   r{   neighbornodesetrf   	next_noder0   r/   s	    `     @@r   r
   r
     s    \ 	A
A

N
NNN<==~++A.aF+,&))!fGNN6HEI
,%HI	Yy!	 '
 
LLqLr   	   c
                   ^ ^^ US:X  a  [         nOUS:X  a  [        nUS:X  a#  [        T TUS9n
T R                  5       S:X  a  U
$ GO=[	        U5      n
Uc  U
S   nOX:S   :w  a  [
        R                  " S5      eU
S   U
S   :w  a  [
        R                  " S	5      e[        U
5      S
-
  [        T 5      :w  d0  [        [        T R                  U
5      5      5      [        T 5      :w  a  [
        R                  " S5      e[        T 5      S
-
  m[        U4S jT R                  R                  5        5       5      (       a  [
        R                  " S5      eT R                  5       S:X  a  [        T R                  U5      5      nX;U/$ [        U U4S j[!        U
5       5       5      nSnU
R#                  5       nUnX::  a  US:  a  US
-  n[%        U5       H  nU" X5      n[        U U4S j[!        U5       5       5      nUU-
  nUS::  a!  Un
UnX:  a  SnU
R#                  5       nUnMT  MV  [&        R(                  " U* U-  5      nUU	R+                  5       :  d  M  Un
UnM     XDU-  -  nX::  a  US:  a  M  U$ )a  Returns an approximate solution to the traveling salesman problem.

This function uses simulated annealing to approximate the minimal cost
cycle through the nodes. Starting from a suboptimal solution, simulated
annealing perturbs that solution, occasionally accepting changes that make
the solution worse to escape from a locally optimal solution. The chance
of accepting such changes decreases over the iterations to encourage
an optimal result.  In summary, the function returns a cycle starting
at `source` for which the total cost is minimized. It also returns the cost.

The chance of accepting a proposed change is related to a parameter called
the temperature (annealing has a physical analogue of steel hardening
as it cools). As the temperature is reduced, the chance of moves that
increase cost goes down.

Parameters
----------
G : Graph
    `G` should be a complete weighted graph.
    The distance between all pairs of nodes should be included.

init_cycle : list of all nodes or "greedy"
    The initial solution (a cycle through all nodes returning to the start).
    This argument has no default to make you think about it.
    If "greedy", use `greedy_tsp(G, weight)`.
    Other common starting cycles are `list(G) + [next(iter(G))]` or the final
    result of `simulated_annealing_tsp` when doing `threshold_accepting_tsp`.

weight : string, optional (default="weight")
    Edge data key corresponding to the edge weight.
    If any edge does not have this attribute the weight is set to 1.

source : node, optional (default: first node in list(G))
    Starting node.  If None, defaults to ``next(iter(G))``

temp : int, optional (default=100)
    The algorithm's temperature parameter. It represents the initial
    value of temperature

move : "1-1" or "1-0" or function, optional (default="1-1")
    Indicator of what move to use when finding new trial solutions.
    Strings indicate two special built-in moves:

    - "1-1": 1-1 exchange which transposes the position
      of two elements of the current solution.
      The function called is :func:`swap_two_nodes`.
      For example if we apply 1-1 exchange in the solution
      ``A = [3, 2, 1, 4, 3]``
      we can get the following by the transposition of 1 and 4 elements:
      ``A' = [3, 2, 4, 1, 3]``
    - "1-0": 1-0 exchange which moves an node in the solution
      to a new position.
      The function called is :func:`move_one_node`.
      For example if we apply 1-0 exchange in the solution
      ``A = [3, 2, 1, 4, 3]``
      we can transfer the fourth element to the second position:
      ``A' = [3, 4, 2, 1, 3]``

    You may provide your own functions to enact a move from
    one solution to a neighbor solution. The function must take
    the solution as input along with a `seed` input to control
    random number generation (see the `seed` input here).
    Your function should maintain the solution as a cycle with
    equal first and last node and all others appearing once.
    Your function should return the new solution.

max_iterations : int, optional (default=10)
    Declared done when this number of consecutive iterations of
    the outer loop occurs without any change in the best cost solution.

N_inner : int, optional (default=100)
    The number of iterations of the inner loop.

alpha : float between (0, 1), optional (default=0.01)
    Percentage of temperature decrease in each iteration
    of outer loop

seed : integer, random_state, or None (default)
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`.

Returns
-------
cycle : list of nodes
    Returns the cycle (list of nodes) that a salesman
    can follow to minimize total weight of the trip.

Raises
------
NetworkXError
    If `G` is not complete the algorithm raises an exception.

Examples
--------
>>> from networkx.algorithms import approximation as approx
>>> G = nx.DiGraph()
>>> G.add_weighted_edges_from(
...     {
...         ("A", "B", 3),
...         ("A", "C", 17),
...         ("A", "D", 14),
...         ("B", "A", 3),
...         ("B", "C", 12),
...         ("B", "D", 16),
...         ("C", "A", 13),
...         ("C", "B", 12),
...         ("C", "D", 4),
...         ("D", "A", 14),
...         ("D", "B", 15),
...         ("D", "C", 2),
...     }
... )
>>> cycle = approx.simulated_annealing_tsp(G, "greedy", source="D")
>>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
>>> cycle
['D', 'C', 'B', 'A', 'D']
>>> cost
31
>>> incycle = ["D", "B", "A", "C", "D"]
>>> cycle = approx.simulated_annealing_tsp(G, incycle, source="D")
>>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
>>> cycle
['D', 'C', 'B', 'A', 'D']
>>> cost
31

Notes
-----
Simulated Annealing is a metaheuristic local search algorithm.
The main characteristic of this algorithm is that it accepts
even solutions which lead to the increase of the cost in order
to escape from low quality local optimal solutions.

This algorithm needs an initial solution. If not provided, it is
constructed by a simple greedy algorithm. At every iteration, the
algorithm selects thoughtfully a neighbor solution.
Consider $c(x)$ cost of current solution and $c(x')$ cost of a
neighbor solution.
If $c(x') - c(x) <= 0$ then the neighbor solution becomes the current
solution for the next iteration. Otherwise, the algorithm accepts
the neighbor solution with probability $p = exp - ([c(x') - c(x)] / temp)$.
Otherwise the current solution is retained.

`temp` is a parameter of the algorithm and represents temperature.

Time complexity:
For $N_i$ iterations of the inner loop and $N_o$ iterations of the
outer loop, this algorithm has running time $O(N_i * N_o * |V|)$.

For more information and how the algorithm is inspired see:
http://en.wikipedia.org/wiki/Simulated_annealing
1-11-0greedyr"   r{   r   r   'source must be first node in init_cycler[   -init_cycle must be a cycle. (return to start)r   z1init_cycle should be a cycle over all nodes in G.c              3   N   >#    U  H  u  p[        U5      X;   -
  T:g  v   M     g 7fr&   r-   r.   s      r   r*   *simulated_annealing_tsp.<locals>.<genexpr>  #     RMjas7|q|,1Mrz   r1   c              3   X   >#    U  H  u  pTU   U   R                  TS 5      v   M!     g7fr   Nr  r(   rR   rL   rG   r"   s      r   r*   r#    )     B/$!qtAw{{61%%/   '*c              3   X   >#    U  H  u  pTU   U   R                  TS 5      v   M!     g7fr&  r  r'  s      r   r*   r#    +     P>Oda1Q47;;vq11>Or)  )r   r    r
   r   r]   r3   r=   r   r   nbunch_iterr:   r;   r<   r5   r  sumr   r6   r   r   rt   random)rG   
init_cycler"   r{   tempmovemax_iterationsN_inneralphar   rf   r  costcount
best_cycle	best_costiadj_soladj_costr	  rk   r0   s   ` `                  @r   r   r     sO   L u}	X1VF;!#L $ Z >1XFQx""#LMM8uRy ""#RSSu:>SV#s3q}}U/C+D'EQ'O""#VWW FQJRAEEKKMRRR""#@AA!#AKK/0Hf-- B(5/BBDEJI

!dQh
wA5'GPhw>OPPHtOEz#E!&J $I $ HHeVd]+%#E#D%  & 	u+ 
!dQh. r   c
                   ^ ^^ US:X  a  [         nOUS:X  a  [        nUS:X  a#  [        T TUS9n
T R                  5       S:X  a  U
$ GO@[	        U5      n
Uc  U
S   nOX:S   :w  a  [
        R                  " S5      eU
S   U
S   :w  a  [
        R                  " S	5      e[        U
5      S
-
  [        T 5      :w  d0  [        [        T R                  U
5      5      5      [        T 5      :w  a  [
        R                  " S5      e[        T 5      S
-
  m[        U4S jT R                  R                  5        5       5      (       a  [
        R                  " S5      eT R                  5       S:X  a!  [	        T R                  U5      5      S   nX;U/$ [        U U4S j[        U
5       5       5      nSnU
R!                  5       nUnX::  a  US
-  nSn[#        U5       HX  nU" X5      n[        U U4S j[        U5       5       5      nUU-
  nUU::  d  M7  SnUn
UnX:  d  MD  SnU
R!                  5       nUnMZ     U(       a  XDU-  -  nX::  a  M  U$ )a  Returns an approximate solution to the traveling salesman problem.

This function uses threshold accepting methods to approximate the minimal cost
cycle through the nodes. Starting from a suboptimal solution, threshold
accepting methods perturb that solution, accepting any changes that make
the solution no worse than increasing by a threshold amount. Improvements
in cost are accepted, but so are changes leading to small increases in cost.
This allows the solution to leave suboptimal local minima in solution space.
The threshold is decreased slowly as iterations proceed helping to ensure
an optimum. In summary, the function returns a cycle starting at `source`
for which the total cost is minimized.

Parameters
----------
G : Graph
    `G` should be a complete weighted graph.
    The distance between all pairs of nodes should be included.

init_cycle : list or "greedy"
    The initial solution (a cycle through all nodes returning to the start).
    This argument has no default to make you think about it.
    If "greedy", use `greedy_tsp(G, weight)`.
    Other common starting cycles are `list(G) + [next(iter(G))]` or the final
    result of `simulated_annealing_tsp` when doing `threshold_accepting_tsp`.

weight : string, optional (default="weight")
    Edge data key corresponding to the edge weight.
    If any edge does not have this attribute the weight is set to 1.

source : node, optional (default: first node in list(G))
    Starting node.  If None, defaults to ``next(iter(G))``

threshold : int, optional (default=1)
    The algorithm's threshold parameter. It represents the initial
    threshold's value

move : "1-1" or "1-0" or function, optional (default="1-1")
    Indicator of what move to use when finding new trial solutions.
    Strings indicate two special built-in moves:

    - "1-1": 1-1 exchange which transposes the position
      of two elements of the current solution.
      The function called is :func:`swap_two_nodes`.
      For example if we apply 1-1 exchange in the solution
      ``A = [3, 2, 1, 4, 3]``
      we can get the following by the transposition of 1 and 4 elements:
      ``A' = [3, 2, 4, 1, 3]``
    - "1-0": 1-0 exchange which moves an node in the solution
      to a new position.
      The function called is :func:`move_one_node`.
      For example if we apply 1-0 exchange in the solution
      ``A = [3, 2, 1, 4, 3]``
      we can transfer the fourth element to the second position:
      ``A' = [3, 4, 2, 1, 3]``

    You may provide your own functions to enact a move from
    one solution to a neighbor solution. The function must take
    the solution as input along with a `seed` input to control
    random number generation (see the `seed` input here).
    Your function should maintain the solution as a cycle with
    equal first and last node and all others appearing once.
    Your function should return the new solution.

max_iterations : int, optional (default=10)
    Declared done when this number of consecutive iterations of
    the outer loop occurs without any change in the best cost solution.

N_inner : int, optional (default=100)
    The number of iterations of the inner loop.

alpha : float between (0, 1), optional (default=0.1)
    Percentage of threshold decrease when there is at
    least one acceptance of a neighbor solution.
    If no inner loop moves are accepted the threshold remains unchanged.

seed : integer, random_state, or None (default)
    Indicator of random number generation state.
    See :ref:`Randomness<randomness>`.

Returns
-------
cycle : list of nodes
    Returns the cycle (list of nodes) that a salesman
    can follow to minimize total weight of the trip.

Raises
------
NetworkXError
    If `G` is not complete the algorithm raises an exception.

Examples
--------
>>> from networkx.algorithms import approximation as approx
>>> G = nx.DiGraph()
>>> G.add_weighted_edges_from(
...     {
...         ("A", "B", 3),
...         ("A", "C", 17),
...         ("A", "D", 14),
...         ("B", "A", 3),
...         ("B", "C", 12),
...         ("B", "D", 16),
...         ("C", "A", 13),
...         ("C", "B", 12),
...         ("C", "D", 4),
...         ("D", "A", 14),
...         ("D", "B", 15),
...         ("D", "C", 2),
...     }
... )
>>> cycle = approx.threshold_accepting_tsp(G, "greedy", source="D")
>>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
>>> cycle
['D', 'C', 'B', 'A', 'D']
>>> cost
31
>>> incycle = ["D", "B", "A", "C", "D"]
>>> cycle = approx.threshold_accepting_tsp(G, incycle, source="D")
>>> cost = sum(G[n][nbr]["weight"] for n, nbr in nx.utils.pairwise(cycle))
>>> cycle
['D', 'C', 'B', 'A', 'D']
>>> cost
31

Notes
-----
Threshold Accepting is a metaheuristic local search algorithm.
The main characteristic of this algorithm is that it accepts
even solutions which lead to the increase of the cost in order
to escape from low quality local optimal solutions.

This algorithm needs an initial solution. This solution can be
constructed by a simple greedy algorithm. At every iteration, it
selects thoughtfully a neighbor solution.
Consider $c(x)$ cost of current solution and $c(x')$ cost of
neighbor solution.
If $c(x') - c(x) <= threshold$ then the neighbor solution becomes the current
solution for the next iteration, where the threshold is named threshold.

In comparison to the Simulated Annealing algorithm, the Threshold
Accepting algorithm does not accept very low quality solutions
(due to the presence of the threshold value). In the case of
Simulated Annealing, even a very low quality solution can
be accepted with probability $p$.

Time complexity:
It has a running time $O(m * n * |V|)$ where $m$ and $n$ are the number
of times the outer and inner loop run respectively.

For more information and how algorithm is inspired see:
https://doi.org/10.1016/0021-9991(90)90201-B

See Also
--------
simulated_annealing_tsp

r  r  r  r  r   r   r   r[   r!  r   z%init_cycle is not all and only nodes.c              3   N   >#    U  H  u  p[        U5      X;   -
  T:g  v   M     g 7fr&   r-   r.   s      r   r*   *threshold_accepting_tsp.<locals>.<genexpr>  r$  rz   r1   c              3   X   >#    U  H  u  pTU   U   R                  TS 5      v   M!     g7fr&  r  r'  s      r   r*   r>    r(  r)  Fc              3   X   >#    U  H  u  pTU   U   R                  TS 5      v   M!     g7fr&  r  r'  s      r   r*   r>    r+  r)  T)r   r    r
   r   r]   r3   r=   r   r   r,  r:   r;   r<   r  r-  r   r6   r   )rG   r/  r"   r{   	thresholdr1  r2  r3  r4  r   rf   r  r5  r6  r7  r8  acceptedr9  r:  r;  r	  r0   s   ` `                  @r   r   r     s&   V u}	X1VF;!#L $ Z >1XFQx""#LMM8uRy ""#RSSu:>SV#s3q}}U/C+D'EQ'O""#JKK FQJRAEEKKMRRR""#@AA!#AKK/03Hf-- B(5/BBDEJI

!
wA5'GPhw>OPPHtOE	!  #E!&J $I   U**I' 
!* r   )r"   N)r"   NTN)r"   NNr2   )r"   Nd   r  
   rC  g{Gz?N)r"   Nr   r  rD  rC  g?N)__doc__r   networkxr3   networkx.algorithms.tree.mstr   networkx.utilsr   r   r   __all__r   r    _dispatchabler   rE   r   r	   r   r   r
   r   r   r'   r   r   <module>rK     s  "H   = I I F$N Z X&82 ' !82v
 X&7;W 'Wt \"XT:V" ;  #V"r XTNw7 Ow7t	 k k\ X&c 'cL X& 		
	a ' aH X& 	
	d ' dr   