
    ^Mhy                        d Z ddlZddlmZ ddlmZmZ ddlmZ ddl	m
Z
mZ ddlmZ dgZ G d	 d
          Z G d d          Z G d d          Z G d d          Z G d d          Z edd          	 	 	 	 	 dd            ZdS ) z0
A Dual Annealing global optimization algorithm
    N)OptimizeResult)minimizeBounds)gammaln)check_random_state_transition_to_rng)new_bounds_to_olddual_annealingc                   ,    e Zd ZdZdZdZd Zd Zd ZdS )VisitingDistributiona@  
    Class used to generate new coordinates based on the distorted
    Cauchy-Lorentz distribution. Depending on the steps within the strategy
    chain, the class implements the strategy for generating new location
    changes.

    Parameters
    ----------
    lb : array_like
        A 1-D NumPy ndarray containing lower bounds of the generated
        components. Neither NaN or inf are allowed.
    ub : array_like
        A 1-D NumPy ndarray containing upper bounds for the generated
        components. Neither NaN or inf are allowed.
    visiting_param : float
        Parameter for visiting distribution. Default value is 2.62.
        Higher values give the visiting distribution a heavier tail, this
        makes the algorithm jump to a more distant region.
        The value range is (1, 3]. Its value is fixed for the life of the
        object.
    rng_gen : {`~numpy.random.Generator`}
        A `~numpy.random.Generator` object for generating new locations.
        (can be a `~numpy.random.RandomState` object until SPEC007 transition
         is fully complete).

    g    חA绽|=c                    || _         || _        || _        || _        ||z
  | _        t          j        d| j         z
  t          j        | j         dz
            z            | _        t          j        d| j         z
  t          j        d          z  | j         dz
  z            | _	        t          j
        t
          j                  | j        z  | j	        d| j         z
  z  z  | _        d| j         dz
  z  dz
  | _        d| j        z
  | _        t
          j        d| j        z
  z  t          j        t
          j        d| j        z
  z            z  t          j        t!          | j                            z  | _        d S )Ng      @      ?       @      @g      ?)_visiting_paramrng_genlowerupperbound_rangenpexplog_factor2_factor3sqrtpi
_factor4_p_factor5_d1sinr   _factor6)selflbubvisiting_paramr   s        ^/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/optimize/_dual_annealing.py__init__zVisitingDistribution.__init__2   sX   
  .

7 d&: :bf 3&?( ?(  ( ) )d&: :bfSkkI"&"6"< > ? ?'"%..4=8DM$&&=( ) t3c9:S@&t}!45ES4=()9+ 9+ +-/VGDH4E4E-F-FG    c                    |j         }||k     r|                     ||          }| j                            d          \  }}| j        |z  ||| j        k    <   | j         |z  ||| j         k     <   ||z   }|| j        z
  }	t          j        |	| j                  | j        z   }
t          j        |
| j                  | j        z   }|t          j	        || j        z
            | j
        k     xx         dz  cc<   nYt          j        |          }|                     |d          d         }|| j        k    r"| j        | j                                        z  }n.|| j         k     r"| j         | j                                        z  }||z
  }|||         z   ||<   ||         | j        |         z
  }	t          j        |	| j        |                   | j        |         z   }
t          j        |
| j        |                   | j        |         z   ||<   t          j	        ||         | j        |         z
            | j
        k     r||xx         | j
        z  cc<   |S )z Based on the step in the strategy chain, new coordinates are
        generated by changing all components is the same time or only
        one of them, the new values are computed with visit_fn method
           sizer      r   )r-   visit_fnr   uniform
TAIL_LIMITr   r   fmodr   fabsMIN_VISIT_BOUNDcopy)r#   xsteptemperaturedimvisitsupper_samplelower_samplex_visitabvisitindexs                r'   visitingzVisitingDistribution.visitingJ   sr   
 f#::]];44F)-)=)=1)=)E)E&L,/3/MF6DO+,150@<0OF6T_,,-qjG$*$A4+,,t/??Aga!122TZ?GBG$*$& &(,(<= > > >AGH > > > >
 gajjGMM+q11!4Et&&$,*>*>*@*@@$/)))(4<+?+?+A+AA3JE"QuX-GENE!22A4+E233d6Fu6MMAWQ(8)  *U+,GENwwu~
)   "23 3$"66r)   c                    | j                             |df          j        \  }}t          j        t          j        |          | j        dz
  z            }| j        |z  }|t          j        | j        dz
   t          j        | j        |z            z  d| j        z
  z            z  }t          j        | j        dz
  t          j        t          j	        |                    z  d| j        z
  z            }||z  S )z- Formula Visita from p. 405 of reference [2] r+   r,   r   r   )
r   normalTr   r   r   r   r   r"   r3   )r#   r8   r9   r6   yfactor1factor4dens           r'   r/   zVisitingDistribution.visit_fnp   s    |""a"1131&,,0Ds0JKLL/G+ 	
RVd*S01BFMG#5% 5% %(+d.B(BD E E 	E fd*S0BF271::4F4FFD002 3 3 3wr)   N)	__name__
__module____qualname____doc__r1   r4   r(   rB   r/    r)   r'   r   r      s[         4 JOG G G0$ $ $L    r)   r   c                   2    e Zd ZdZdZddZddZd Zd ZdS )	EnergyStatea!  
    Class used to record the energy state. At any time, it knows what is the
    currently used coordinates and the most recent best location.

    Parameters
    ----------
    lower : array_like
        A 1-D NumPy ndarray containing lower bounds for generating an initial
        random components in the `reset` method.
    upper : array_like
        A 1-D NumPy ndarray containing upper bounds for generating an initial
        random components in the `reset` method
        components. Neither NaN or inf are allowed.
    callback : callable, ``callback(x, f, context)``, optional
        A callback function which will be called for all minima found.
        ``x`` and ``f`` are the coordinates and function value of the
        latest minimum found, and `context` has value in [0, 1, 2]
      Nc                 h    d | _         d | _        d | _        d | _        || _        || _        || _        d S N)ebestcurrent_energycurrent_locationxbestr   r   callback)r#   r   r   rX   s       r'   r(   zEnergyState.__init__   s9    
" $


 r)   c                    |:|                     | j        | j        t          | j                            | _        nt          j        |          | _        d}d}|r|                    | j                  | _        | j        t          d          t          j
        | j                  sZ|t          j        k    rd}d}t          |          |                     | j        | j        | j        j                  | _        |dz  }nd}| j        1| j        *| j        | _        t          j        | j                  | _        |dS dS )	z
        Initialize current location is the search domain. If `x0` is not
        provided, a random location within the bounds is generated.
        Nr,   Tr   z$Objective function is returning NoneFznStopping algorithm because function create NaN or (+/-) infinity values even with trying new random parametersr.   )r0   r   r   lenrV   r   r5   funrU   
ValueErrorisfiniterP   MAX_REINIT_COUNTr-   rT   rW   )r#   func_wrapperr   x0
init_errorreinit_countermessages          r'   resetzEnergyState.reset   s^   
 :$+OODJ
9<TZ %4 %J %JD!! %'GBKKD!
 	<"."2"243H"I"ID"* !GHHH;t233 #![%AAA!&J7 
 %W---(/
8<
=AZ_ )8 )N )N% !#"
z!dj&8!0
WT%:;;
-  	< 	< 	< 	< 	<r)   c                     || _         t          j        |          | _        | j        |                     |||          }||rdS d S d S d S )Nz;Callback function requested to stop early by returning True)rT   r   r5   rW   rX   )r#   er6   contextvals        r'   update_bestzEnergyState.update_best   sc    
WQZZ
=$--1g..C -, ,	 %$- -r)   c                 F    || _         t          j        |          | _        d S rS   )rU   r   r5   rV   )r#   rf   r6   s      r'   update_currentzEnergyState.update_current   s      "

r)   rS   )	rJ   rK   rL   rM   r^   r(   rd   ri   rk   rN   r)   r'   rP   rP      sm         & ! ! ! !"< "< "< "<J- - -+ + + + +r)   rP   c                   *    e Zd ZdZd Zd Zd Zd ZdS )StrategyChaina  
    Class that implements within a Markov chain the strategy for location
    acceptance and local search decision making.

    Parameters
    ----------
    acceptance_param : float
        Parameter for acceptance distribution. It is used to control the
        probability of acceptance. The lower the acceptance parameter, the
        smaller the probability of acceptance. Default value is -5.0 with
        a range (-1e4, -5].
    visit_dist : VisitingDistribution
        Instance of `VisitingDistribution` class.
    func_wrapper : ObjectiveFunWrapper
        Instance of `ObjectiveFunWrapper` class.
    minimizer_wrapper: LocalSearchWrapper
        Instance of `LocalSearchWrapper` class.
    rand_gen : {None, int, `numpy.random.Generator`,
                `numpy.random.RandomState`}, optional

        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``RandomState`` instance is used,
        seeded with `seed`.
        If `seed` is already a ``Generator`` or ``RandomState`` instance then
        that instance is used.
    energy_state: EnergyState
        Instance of `EnergyState` class.

    c                    |j         | _        t          j        |j                  | _        || _        || _        || _        || _	        || _
        d| _        d| _        || _        d| _        dt          |j                  z  | _        d S )Nr   rQ   d   )rU   eminr   arrayrV   xminenergy_stateacceptance_param
visit_distr_   minimizer_wrappernot_improved_idxnot_improved_max_idx	_rand_gentemperature_steprZ   K)r#   rt   ru   r_   rv   rand_genrs   s          r'   r(   zStrategyChain.__init__   s     !/	H\:;;	( 0$(!2 !$(!! !s<8999r)   c                 D   | j                                         }dd| j        z
  || j        j        z
  z  | j        z  z
  }|dk    rd}n1t          j        t          j        |          d| j        z
  z            }||k    r>| j        	                    ||           t          j
        | j        j                  | _        | j        | j        k    rQ|dk    s| j        j        | j        k     r8| j        j        | _        t          j
        | j        j                  | _        d S d S d S )Nr           r   )ry   r0   rt   rs   rU   rz   r   r   r   rk   r5   rV   rr   rw   rx   rp   )r#   jrf   r=   rpqv_temppqvs          r'   accept_rejectzStrategyChain.accept_reject	  s%   N""$$3!66"113595JK Lr>>CC&))T**, - -C 88,,Q888 1 BCCDI  D$===Avv*9DIEE -<	GD$5$FGG			 >=EEr)   c                    |t          |dz             z  | _        | xj        dz  c_        t          | j        j        j        dz            D ] }|dk    r|dk    rd| _        nd| _        | j        	                    | j        j        ||          }| j
                            |          }|| j        j        k     r^| j                            ||           || j        j        k     r2| j                            ||d          }||r|c S d| _        d| _        n|                     |||           | j
        j        | j
        j        k    r dS d S )Nr.   r+   r   TFz8Maximum number of function call reached during annealing)floatrz   rw   rangers   rV   r-   energy_state_improvedru   rB   r_   r[   rU   rk   rT   ri   r   nfevmaxfun)r#   r7   r8   r   r=   rf   rh   s          r'   runzStrategyChain.run  s    +eD1Hoo ="t(9>BCC 	, 	,AAvv19915D..16D.o..!2A{D DG !%%g..A4$333!00G<<<t(...+777AFFC '#&JJJ15D.,-D) ""1a111 %):)AAA+ + + B/	, 	,r)   c                 6   | j         r| j                            | j        j        | j        j                  \  }}|| j        j        k     rDd| _        | j                            ||d          }||r|S | j                            ||           | j	        j
        | j	        j        k    rdS d}| j        dt          | j        j                  z  k     rZt          j        | j        | j        j        | j        j        z
  z  | j        z            }|| j                                        k    rd}| j        | j        k    rd}|r| j                            | j        | j                  \  }}t          j        |          | _        || _        d| _        | j        j        j        | _        || j        j        k     rG| j                            | j        | j        d          }||r|S | j                            ||           | j	        j
        | j	        j        k    rdS d S d S )	Nr   r.   z;Maximum number of function call reached during local searchFZ   Tr+   z=Maximum number of function call reached during dual annealing)r   rv   local_searchrs   rW   rT   rw   ri   rk   r_   r   r   r{   rZ   rV   r   r   rU   rz   ry   r0   rx   rr   rp   r5   r-   )r#   rf   r6   rh   do_lsplss         r'   r   zStrategyChain.local_search=  s@   
 % 	/)66t7H7N7;7H7NP PDAq4$***()%'33Aq!<<? #"
!00A666 %):)AAA. . 6BT.?@@@@@&!'$*;*JJL%& ' 'C dn,,....  D$===E 	1)66ty$)LLDAq

DIDI$%D!(,(9(J(OD%4$***'33Ity!- -? #"
!00A666 %):)AAA0 0	1 	1 BAr)   N)rJ   rK   rL   rM   r(   r   r   r   rN   r)   r'   rm   rm      s]         >: : :*H H H*, , ,>.1 .1 .1 .1 .1r)   rm   c                       e Zd ZddZd ZdS )ObjectiveFunWrapper    cAc                 Z    || _         || _        d| _        d| _        d| _        || _        d S )Nr   )funcargsr   ngevnhevr   )r#   r   r   r   s       r'   r(   zObjectiveFunWrapper.__init__p  s0    					r)   c                 H    | xj         dz  c_          | j        |g| j        R  S )Nr.   )r   r   r   )r#   r6   s     r'   r[   zObjectiveFunWrapper.fun{  s-    		Q		ty'TY''''r)   N)r   )rJ   rK   rL   r(   r[   rN   r)   r'   r   r   n  s7        	 	 	 	( ( ( ( (r)   r   c                   *    e Zd ZdZdZdZdZd Zd ZdS )LocalSearchWrapperz
    Class used to wrap around the minimizer used for local search
    Default local minimizer is SciPy minimizer L-BFGS-B
       ro   rQ   c                     | _         | _         j                            dd            _         j                            dd            _         j                            dd            _         j                            dd            t           _        t          t          |           }t          j        |d                    _        t          j        |d                    _         j        st           j                  }t!          t#          | j        z   j                   j                  }d j        d<   d	|i j        d
<   t          t           j         j                             j        d<   d S t+           j                  r fd}| j        d<   t+           j                  r fd}	|	 j        d<   t+           j                  r fd}
|
 j        d<   d S d S )Njachesshesspr   r   r.   zL-BFGS-Bmethodmaxiteroptionsboundsc                       j         | gR  S rS   )r   r6   r   r#   s    r'   wrapped_jacz0LocalSearchWrapper.__init__.<locals>.wrapped_jac  s    #48A-----r)   c                       j         | gR  S rS   )r   r   s    r'   wrapped_hessz1LocalSearchWrapper.__init__.<locals>.wrapped_hess  s    $49Q.....r)   c                 "     j         | |gR  S rS   )r   )r6   pr   r#   s     r'   wrapped_hesspz2LocalSearchWrapper.__init__.<locals>.wrapped_hessp  s    %4:a2T2222r)   )r_   kwargsgetr   r   r   popr   	minimizerlistzipr   rq   r   r   rZ   minmaxLS_MAXITER_RATIOLS_MAXITER_MINLS_MAXITER_MAXcallable)r#   search_boundsr_   r   r   bounds_listnls_max_iterr   r   r   s   `  `       r'   r(   zLocalSearchWrapper.__init__  s
   (;??5$//KOOFD11	[__Wd33
%%%!3.//Xk!n--
Xk!n--
 { 	5DJAc!d&;";"&"57 7"13 3K %/DK!;&DK	" %)TZ)D)D$E$EDK!!!!! 1. . . . . .%0E"	"" 3/ / / / / /&2F#
## 53 3 3 3 3 3'4G$$$5 5r)   c                 4   t          j        |          } | j        | j        j        |fi | j        }d|v r| j        xj        |j        z  c_        d|v r| j        xj        |j        z  c_        t          j	        t          j
        |j                            ot          j
        |j                  }t          j	        |j        | j        k              o!t          j	        |j        | j        k              }|o|}|r|j        |k     r|j        |j        fS ||fS )Nnjevr   )r   r5   r   r_   r[   r   r   r   r   allr]   r6   r   r   )r#   r6   rf   x_tmpmres	is_finite	in_boundsis_valids           r'   r   zLocalSearchWrapper.local_search  s   

t~d/3QFF$+FFT>>""di/""T>>""di/""F2;tv..//IBK4I4I	F46TZ/00 "RVFdj 6" 6"	*  	18TV##e8Or)   N)	rJ   rK   rL   rM   r   r   r   r(   r   rN   r)   r'   r   r     sO         
 NN#5 #5 #5J    r)   r   seed
   )position_numrN   rQ        n@h㈵>(\@      r   Fc                    t          |t                    r-t          |j        |j        t          |j                            }|/t          |          t          |          k    st          d          t          t          |           }t          j
        |d                   }t          j
        |d                   }|dk    s|dk    rt          d          t          j        t          j        |                    srt          j        t          j        |                    sLt          j        t          j        |                    s&t          j        t          j        |                    rt          d          t          j        ||k               st          d	          t          |          t          |          k    st          d
          t          | |	g|R  }|pi }t!          ||g|R i |}t#          |
          }t%          |||          }|                    |||           ||z  }t)          ||||          }t+          ||||||          }d}d}g }t-                      }d|_        d|_        t          j        |dz
  t          j        d          z            dz
  }|st7          |          D ]}t9          |          dz   }t          j        |dz
  t          j        |          z            dz
  }||z  |z  } ||k    r|                    d           d} n| |k     r|                    ||            nv|                    ||           }!|! |                    |!           d}d|_         n>|s6|                                }!|! |                    |!           d}d|_         n|dz  }||j         |_!        |j"        |_#        ||_$        |j%        |_%        |j&        |_'        |j(        |_(        ||_)        |S )a   
    Find the global minimum of a function using Dual Annealing.

    Parameters
    ----------
    func : callable
        The objective function to be minimized. Must be in the form
        ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array
        and ``args`` is a  tuple of any additional fixed parameters needed to
        completely specify the function.
    bounds : sequence or `Bounds`
        Bounds for variables. There are two ways to specify the bounds:

        1. Instance of `Bounds` class.
        2. Sequence of ``(min, max)`` pairs for each element in `x`.

    args : tuple, optional
        Any additional fixed parameters needed to completely specify the
        objective function.
    maxiter : int, optional
        The maximum number of global search iterations. Default value is 1000.
    minimizer_kwargs : dict, optional
        Keyword arguments to be passed to the local minimizer
        (`minimize`). An important option could be ``method`` for the minimizer
        method to use.
        If no keyword arguments are provided, the local minimizer defaults to
        'L-BFGS-B' and uses the already supplied bounds. If `minimizer_kwargs`
        is specified, then the dict must contain all parameters required to
        control the local minimization. `args` is ignored in this dict, as it is
        passed automatically. `bounds` is not automatically passed on to the
        local minimizer as the method may not support them.
    initial_temp : float, optional
        The initial temperature, use higher values to facilitates a wider
        search of the energy landscape, allowing dual_annealing to escape
        local minima that it is trapped in. Default value is 5230. Range is
        (0.01, 5.e4].
    restart_temp_ratio : float, optional
        During the annealing process, temperature is decreasing, when it
        reaches ``initial_temp * restart_temp_ratio``, the reannealing process
        is triggered. Default value of the ratio is 2e-5. Range is (0, 1).
    visit : float, optional
        Parameter for visiting distribution. Default value is 2.62. Higher
        values give the visiting distribution a heavier tail, this makes
        the algorithm jump to a more distant region. The value range is (1, 3].
    accept : float, optional
        Parameter for acceptance distribution. It is used to control the
        probability of acceptance. The lower the acceptance parameter, the
        smaller the probability of acceptance. Default value is -5.0 with
        a range (-1e4, -5].
    maxfun : int, optional
        Soft limit for the number of objective function calls. If the
        algorithm is in the middle of a local search, this number will be
        exceeded, the algorithm will stop just after the local search is
        done. Default value is 1e7.
    rng : `numpy.random.Generator`, optional
        Pseudorandom number generator state. When `rng` is None, a new
        `numpy.random.Generator` is created using entropy from the
        operating system. Types other than `numpy.random.Generator` are
        passed to `numpy.random.default_rng` to instantiate a `Generator`.

        Specify `rng` for repeatable minimizations. The random numbers
        generated only affect the visiting distribution function
        and new coordinates generation.
    no_local_search : bool, optional
        If `no_local_search` is set to True, a traditional Generalized
        Simulated Annealing will be performed with no local search
        strategy applied.
    callback : callable, optional
        A callback function with signature ``callback(x, f, context)``,
        which will be called for all minima found.
        ``x`` and ``f`` are the coordinates and function value of the
        latest minimum found, and ``context`` has one of the following
        values:

        - ``0``: minimum detected in the annealing process.
        - ``1``: detection occurred in the local search process.
        - ``2``: detection done in the dual annealing process.

        If the callback implementation returns True, the algorithm will stop.
    x0 : ndarray, shape(n,), optional
        Coordinates of a single N-D starting point.

    Returns
    -------
    res : OptimizeResult
        The optimization result represented as a `OptimizeResult` object.
        Important attributes are: ``x`` the solution array, ``fun`` the value
        of the function at the solution, and ``message`` which describes the
        cause of the termination.
        See `OptimizeResult` for a description of other attributes.

    Notes
    -----
    This function implements the Dual Annealing optimization. This stochastic
    approach derived from [3]_ combines the generalization of CSA (Classical
    Simulated Annealing) and FSA (Fast Simulated Annealing) [1]_ [2]_ coupled
    to a strategy for applying a local search on accepted locations [4]_.
    An alternative implementation of this same algorithm is described in [5]_
    and benchmarks are presented in [6]_. This approach introduces an advanced
    method to refine the solution found by the generalized annealing
    process. This algorithm uses a distorted Cauchy-Lorentz visiting
    distribution, with its shape controlled by the parameter :math:`q_{v}`

    .. math::

        g_{q_{v}}(\Delta x(t)) \propto \frac{ \
        \left[T_{q_{v}}(t) \right]^{-\frac{D}{3-q_{v}}}}{ \
        \left[{1+(q_{v}-1)\frac{(\Delta x(t))^{2}} { \
        \left[T_{q_{v}}(t)\right]^{\frac{2}{3-q_{v}}}}}\right]^{ \
        \frac{1}{q_{v}-1}+\frac{D-1}{2}}}

    Where :math:`t` is the artificial time. This visiting distribution is used
    to generate a trial jump distance :math:`\Delta x(t)` of variable
    :math:`x(t)` under artificial temperature :math:`T_{q_{v}}(t)`.

    From the starting point, after calling the visiting distribution
    function, the acceptance probability is computed as follows:

    .. math::

        p_{q_{a}} = \min{\{1,\left[1-(1-q_{a}) \beta \Delta E \right]^{ \
        \frac{1}{1-q_{a}}}\}}

    Where :math:`q_{a}` is a acceptance parameter. For :math:`q_{a}<1`, zero
    acceptance probability is assigned to the cases where

    .. math::

        [1-(1-q_{a}) \beta \Delta E] < 0

    The artificial temperature :math:`T_{q_{v}}(t)` is decreased according to

    .. math::

        T_{q_{v}}(t) = T_{q_{v}}(1) \frac{2^{q_{v}-1}-1}{\left( \
        1 + t\right)^{q_{v}-1}-1}

    Where :math:`q_{v}` is the visiting parameter.

    .. versionadded:: 1.2.0

    References
    ----------
    .. [1] Tsallis C. Possible generalization of Boltzmann-Gibbs
        statistics. Journal of Statistical Physics, 52, 479-487 (1998).
    .. [2] Tsallis C, Stariolo DA. Generalized Simulated Annealing.
        Physica A, 233, 395-406 (1996).
    .. [3] Xiang Y, Sun DY, Fan W, Gong XG. Generalized Simulated
        Annealing Algorithm and Its Application to the Thomson Model.
        Physics Letters A, 233, 216-220 (1997).
    .. [4] Xiang Y, Gong XG. Efficiency of Generalized Simulated
        Annealing. Physical Review E, 62, 4473 (2000).
    .. [5] Xiang Y, Gubian S, Suomela B, Hoeng J. Generalized
        Simulated Annealing for Efficient Global Optimization: the GenSA
        Package for R. The R Journal, Volume 5/1 (2013).
    .. [6] Mullen, K. Continuous Global Optimization in R. Journal of
        Statistical Software, 60(6), 1 - 45, (2014).
        :doi:`10.18637/jss.v060.i06`

    Examples
    --------
    The following example is a 10-D problem, with many local minima.
    The function involved is called Rastrigin
    (https://en.wikipedia.org/wiki/Rastrigin_function)

    >>> import numpy as np
    >>> from scipy.optimize import dual_annealing
    >>> func = lambda x: np.sum(x*x - 10*np.cos(2*np.pi*x)) + 10*np.size(x)
    >>> lw = [-5.12] * 10
    >>> up = [5.12] * 10
    >>> ret = dual_annealing(func, bounds=list(zip(lw, up)))
    >>> ret.x
    array([-4.26437714e-09, -3.91699361e-09, -1.86149218e-09, -3.97165720e-09,
           -6.29151648e-09, -6.53145322e-09, -3.93616815e-09, -6.55623025e-09,
           -6.05775280e-09, -5.00668935e-09]) # random
    >>> ret.fun
    0.000000

    NzBounds size does not match x0r   r.   r~   r   z3Restart temperature ratio has to be in range (0, 1)z/Some bounds values are inf values or nan valuesz#Bounds are not consistent min < maxz&Bounds do not have the same dimensionsFTr   z#Maximum number of iteration reached)*
isinstancer   r	   r$   r%   rZ   r\   r   r   r   rq   anyisinfisnanr   r   r   r   rP   rd   r   rm   r   successstatusr   r   r   r   appendr   r   rW   r6   rT   r[   nitr   r   r   r   rc   )"r   r   r   r   minimizer_kwargsinitial_temprestart_temp_ratior@   acceptr   rngno_local_searchrX   r`   lur   r   r_   rv   r   rs   temperature_restartru   strategy_chainneed_to_stop	iterationrc   optimize_rest1ist2r8   rh   s"                                     r'   r
   r
     s/   t &&!! I"69fiVYHH	~c"ggV448999	c6l		BHRUOOEHRUOOER#5#;#;NOOO
rx L26"(5//#:#: LbfHUOO? ? L "rx 7 7LJKKK6%%-   @>???u::U##ABBB 'tV;d;;;L (-2*9#9 9 9'79 9 !%%GueX66L|Wb111 ');;%eUE7CCJ"6:|#4g|M MNLIG!##LLL	bfSkk)	*	*S	0B w 	 	Aa3AbfQii/0036B&+b0KG##DEEE#000""<999 $$Q44Cs####',$" $1133?NN3'''#'L+0L(ENII;  @ "'LN#)L L$)L$)L$)L"Lr)   )rN   rQ   Nr   r   r   r   r   NFNN)rM   numpyr   scipy.optimizer   r   r   scipy.specialr   scipy._lib._utilr   r   scipy.optimize._constraintsr	   __all__r   rP   rm   r   r   r
   rN   r)   r'   <module>r      s        ) ) ) ) ) ) + + + + + + + + ! ! ! ! ! ! C C C C C C C C 9 9 9 9 9 9
j j j j j j j jZP+ P+ P+ P+ P+ P+ P+ P+fW1 W1 W1 W1 W1 W1 W1 W1t( ( ( ( ( ( ( ($A A A A A A A AH F,,,267<@D9>%)	W W W -,W W Wr)   