
    ^MhRt                        d Z ddlZddlZddlZddlZddlmZm	Z	 dgZ
 ej        dej        j                   ej        dej        j                  fZ ej        e          Z G d	 d
          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!dddd             ZdS )"z>
basinhopping: The basinhopping global optimization algorithm
    N)check_random_state_transition_to_rngbasinhoppingres_new)kindres_old)
parametersc                   *    e Zd ZdZd Zd Zd Zd ZdS )Storagez9
    Class used to store the lowest energy structure
    c                 0    |                      |           d S N)_addselfminress     \/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/optimize/_basinhopping.py__init__zStorage.__init__   s    		&    c                 Z    || _         t          j        |j                  | j         _        d S r   )r   npcopyxr   s     r   r   zStorage._add   s"    ))r   c                     |j         r8|j        | j        j        k     s| j        j         s|                     |           dS dS )NTF)successfunr   r   r   s     r   updatezStorage.update   sE    > 	vzDKO;;&*k&9  <IIf45r   c                     | j         S r   )r   )r   s    r   
get_lowestzStorage.get_lowest%   s
    {r   N)__name__
__module____qualname____doc__r   r   r   r    r   r   r   r      sZ           * * *      r   r   c                   ,    e Zd ZdZddZd Zd Zd ZdS )	BasinHoppingRunnera;  This class implements the core of the basinhopping algorithm.

    x0 : ndarray
        The starting coordinates.
    minimizer : callable
        The local minimizer, with signature ``result = minimizer(x)``.
        The return value is an `optimize.OptimizeResult` object.
    step_taking : callable
        This function displaces the coordinates randomly. Signature should
        be ``x_new = step_taking(x)``. Note that `x` may be modified in-place.
    accept_tests : list of callables
        Each test is passed the kwargs `f_new`, `x_new`, `f_old` and
        `x_old`. These tests will be used to judge whether or not to accept
        the step. The acceptable return values are True, False, or ``"force
        accept"``. If any of the tests return False then the step is rejected.
        If ``"force accept"``, then this will override any other tests in
        order to accept the step. This can be used, for example, to forcefully
        escape from a local minimum that ``basinhopping`` is trapped in.
    disp : bool, optional
        Display status messages.

    Fc                    t          j        |          | _        || _        || _        || _        || _        d| _        t          j	        
                                | _        d| j        _         || j                  }|j        s+| j        xj        dz  c_        | j        rt          d           t          j        |j                  | _        |j        | _        || _        | j        rt          d| j        | j        fz             t%          |          | _        t)          |d          r|j        | j        _        t)          |d          r|j        | j        _        t)          |d          r|j        | j        _        d S d S )Nr      1warning: basinhopping: local minimization failurezbasinhopping step %d: f %gnfevnjevnhev)r   r   r   	minimizerstep_takingaccept_testsdispnstepscipyoptimizeOptimizeResultresminimization_failuresr   printr   energyincumbent_minresr   storagehasattrr)   r*   r+   )r   x0r,   r-   r.   r/   r   s          r   r   zBasinHoppingRunner.__init__@   se   "&(	
 >0022)*& 46""~ 	KH**a/**y KIJJJ""j &9 	L.$*dk1JJKKK v66"" 	("KDHM66"" 	("KDHM66"" 	("KDHMMM	( 	(r   c                 p   t          j        | j                  }|                     |          }|                     |          }|j        }|j        }|j        s+| j        xj        dz  c_        | j	        rt          d           t          |d          r| j        xj        |j        z  c_        t          |d          r| j        xj        |j        z  c_        t          |d          r| j        xj        |j        z  c_        d}| j        D ]j}t!          j        |          t$          k    r ||| j                  }n |||| j        | j                  }|d	k    rd} n|t+          d          |sd}kt          | j        d          r)| j                            |||| j        | j                   ||fS )zDo one Monte Carlo iteration

        Randomly displace the coordinates, minimize, and decide whether
        or not to accept the new coordinates.
        r'   r(   r)   r*   r+   T)r   r   )f_newx_newf_oldx_oldzforce acceptNz7accept_tests must return True, False, or 'force accept'Freport)r   r   r   r-   r,   r   r   r4   r5   r/   r6   r:   r)   r*   r+   r.   inspect	signature_new_accept_test_signaturer8   r7   
ValueErrorrA   )r   x_after_stepr   x_after_quenchenergy_after_quenchaccepttesttestress           r   _monte_carlo_stepz$BasinHoppingRunner._monte_carlo_stepc   s    wtv''55 --$j~ 	KH**a/**y KIJJJ66"" 	)HMMV[(MM66"" 	)HMMV[(MM66"" 	)HMMV[(MM % 	 	D &&*DDD$vt7LMMM$%8%)[@ @ @ .((  "2 3 3 3  4#X.. 	2##F2E*8*.& $ 2 2 2 v~r   c                    | xj         dz  c_         d}|                                 \  }}|rK|j        | _        t	          j        |j                  | _        || _        | j        	                    |          }| j
        r;|                     |j        |           |rt          d| j         | j        fz             |j        | _        |j        | _        || _        |S )z3Do one cycle of the basinhopping algorithm
        r'   Fz:found new global minimum on step %d with function value %g)r0   rL   r   r7   r   r   r   r8   r9   r   r/   print_reportr6   xtrialenergy_trialrI   )r   new_global_minrI   r   s       r   	one_cyclezBasinHoppingRunner.one_cycle   s     	

a

//11 	9 *DKWVX&&DF$*D!!\0088N 9 	?fj&111 ? "%)Z$=> ? ? ? h"Jr   c                     | j                                         }t          d| j        | j        |||j        fz             dS )zprint a status updatez>basinhopping step %d: f %g trial_f %g accepted %d  lowest_f %gN)r9   r   r6   r0   r7   r   )r   rP   rI   r   s       r   rN   zBasinHoppingRunner.print_report   sR    ((**  $
DK &
 44 	5 	5 	5 	5 	5r   N)F)r   r    r!   r"   r   rL   rR   rN   r#   r   r   r%   r%   )   sa         ,!( !( !( !(F7 7 7r  85 5 5 5 5r   r%   c                   6    e Zd ZdZ	 	 ddZd Zd Zd	 Zd
 ZdS )AdaptiveStepsizea  
    Class to implement adaptive stepsize.

    This class wraps the step taking class and modifies the stepsize to
    ensure the true acceptance rate is as close as possible to the target.

    Parameters
    ----------
    takestep : callable
        The step taking routine.  Must contain modifiable attribute
        takestep.stepsize
    accept_rate : float, optional
        The target step acceptance rate
    interval : int, optional
        Interval for how often to update the stepsize
    factor : float, optional
        The step size is multiplied or divided by this factor upon each
        update.
    verbose : bool, optional
        Print information about each update

          ?2   ?Tc                 v    || _         || _        || _        || _        || _        d| _        d| _        d| _        d S )Nr   )takesteptarget_accept_rateintervalfactorverboser0   	nstep_totnaccept)r   rZ   accept_rater\   r]   r^   s         r   r   zAdaptiveStepsize.__init__   s?     "- 
r   c                 ,    |                      |          S r   )	take_stepr   r   s     r   __call__zAdaptiveStepsize.__call__   s    ~~a   r   c                 D   | j         j        }t          | j                  | j        z  }|| j        k    r| j         xj        | j        z  c_        n| j         xj        | j        z  c_        | j        r0t          d|dd| j        dd| j         j        dd|d           d S d S )Nz#adaptive stepsize: acceptance rate fz target z new stepsize gz old stepsize )	rZ   stepsizefloatr`   r0   r[   r]   r^   r6   )r   old_stepsizera   s      r   _adjust_step_sizez"AdaptiveStepsize._adjust_step_size   s    }-DL))DJ6000 M""dk1""" M""dk1""< 	O NO N N,>N N]+MN N=IMN N O O O O O	O 	Or   c                     | xj         dz  c_         | xj        dz  c_        | j         | j        z  dk    r|                                  |                     |          S )Nr'   r   )r0   r_   r\   rl   rZ   rd   s     r   rc   zAdaptiveStepsize.take_step   sY    

a

!:%**""$$$}}Qr   c                 .    |r| xj         dz  c_         dS dS )z7called by basinhopping to report the result of the stepr'   N)r`   )r   rI   kwargss      r   rA   zAdaptiveStepsize.report   s(     	LLALLLL	 	r   N)rV   rW   rX   T)	r   r    r!   r"   r   re   rl   rc   rA   r#   r   r   rU   rU      s{         , GJ
 
 
 
! ! !O O O         r   rU   c                        e Zd ZdZddZd ZdS )RandomDisplacementa7  Add a random displacement of maximum size `stepsize` to each coordinate.

    Calling this updates `x` in-place.

    Parameters
    ----------
    stepsize : float, optional
        Maximum stepsize in any dimension
    rng : {None, int, `numpy.random.Generator`}, optional
        Random number generator
    rV   Nc                 <    || _         t          |          | _        d S r   )ri   r   rng)r   ri   rs   s      r   r   zRandomDisplacement.__init__  s     %c**r   c                 ~    || j                             | j         | j        t          j        |                    z  }|S r   )rs   uniformri   r   shaperd   s     r   re   zRandomDisplacement.__call__  s:    	TXt}ndm hqkk+ + 	+r   )rV   Nr   r    r!   r"   r   re   r#   r   r   rq   rq     sA        
 
+ + + +    r   rq   c                        e Zd ZdZddZd ZdS )MinimizerWrapperz8
    wrap a minimizer function as a minimizer class
    Nc                 0    || _         || _        || _        d S r   )r,   funcro   )r   r,   r{   ro   s       r   r   zMinimizerWrapper.__init__  s    "	r   c                 h    | j          | j        |fi | j        S  | j        | j         |fi | j        S r   )r{   r,   ro   )r   r;   s     r   re   zMinimizerWrapper.__call__"  sF    9!4>"44444!4>$)R??4;???r   r   rw   r#   r   r   ry   ry     sF            
@ @ @ @ @r   ry   c                   &    e Zd ZdZddZd Zd ZdS )
Metropolisa  Metropolis acceptance criterion.

    Parameters
    ----------
    T : float
        The "temperature" parameter for the accept or reject criterion.
    rng : {None, int, `numpy.random.Generator`}, optional
        Random number generator used for acceptance test.

    Nc                 l    |dk    rd|z  nt          d          | _        t          |          | _        d S )Nr         ?inf)rj   betar   rs   )r   Trs   s      r   r   zMetropolis.__init__5  s4      !AvvC!GG5<<	%c**r   c                 ,   t          j        d          5  |j        |j        z
   | j        z  }t	          j        t          d|                    }ddd           n# 1 swxY w Y   | j                                        }||k    o|j	        p|j	         S )a	  
        Assuming the local search underlying res_new was successful:
        If new energy is lower than old, it will always be accepted.
        If new is higher than old, there is a chance it will be accepted,
        less likely for larger differences.
        ignore)invalidr   N)
r   errstater   r   mathexpminrs   ru   r   )r   r   r   prodwrands         r   accept_rejectzMetropolis.accept_reject<  s     [*** 
	' 
	' [7;./$);DQ&&A
	' 
	' 
	' 
	' 
	' 
	' 
	' 
	' 
	' 
	' 
	' 
	' 
	' 
	' 
	' x!!DyEgoDW_1DEs   ;AA!$A!c                H    t          |                     ||                    S )z9
        f_new and f_old are mandatory in kwargs
        )boolr   )r   r   r   s      r   re   zMetropolis.__call__R  s"     D&&w88999r   r   )r   r    r!   r"   r   r   re   r#   r   r   r~   r~   )  sS        	 	+ + + +F F F,: : : : :r   r~   seed   T)position_numreplace_docd   r   rV   rW   FrX   )r[   stepwise_factorc                   |dk    s|dk    rt          d          |dk    s|dk    rt          d          t          j        |          }t          |          }|t	                      }t          t          j        j        | fi |}|Ft          |          st          d          t          |d          rt          ||	|||
          }n(|}n%t          ||	          }t          ||	|||
          }g }|!t          |          st          d
          |g}t          ||          }|                    |           ||dz   }t!          |||||
          }t          |          r+ ||j        j        j        |j        j        j        d           d\  }}dg}t+          |          D ]_}|                                }t          |          r% ||j        |j        |j                  }||rdg} n|dz  }|rd}T||k    rdg} n`|j        }|j                                        |_        t          j        |j        j                  |_        |j        j        |_        ||_        |dz   |_        |j        j         |_         |S )a6  Find the global minimum of a function using the basin-hopping algorithm.

    Basin-hopping is a two-phase method that combines a global stepping
    algorithm with local minimization at each step. Designed to mimic
    the natural process of energy minimization of clusters of atoms, it works
    well for similar problems with "funnel-like, but rugged" energy landscapes
    [5]_.

    As the step-taking, step acceptance, and minimization methods are all
    customizable, this function can also be used to implement other two-phase
    methods.

    Parameters
    ----------
    func : callable ``f(x, *args)``
        Function to be optimized.  ``args`` can be passed as an optional item
        in the dict `minimizer_kwargs`
    x0 : array_like
        Initial guess.
    niter : integer, optional
        The number of basin-hopping iterations. There will be a total of
        ``niter + 1`` runs of the local minimizer.
    T : float, optional
        The "temperature" parameter for the acceptance or rejection criterion.
        Higher "temperatures" mean that larger jumps in function value will be
        accepted.  For best results `T` should be comparable to the
        separation (in function value) between local minima.
    stepsize : float, optional
        Maximum step size for use in the random displacement.
    minimizer_kwargs : dict, optional
        Extra keyword arguments to be passed to the local minimizer
        `scipy.optimize.minimize` Some important options could be:

        method : str
            The minimization method (e.g. ``"L-BFGS-B"``)
        args : tuple
            Extra arguments passed to the objective function (`func`) and
            its derivatives (Jacobian, Hessian).

    take_step : callable ``take_step(x)``, optional
        Replace the default step-taking routine with this routine. The default
        step-taking routine is a random displacement of the coordinates, but
        other step-taking algorithms may be better for some systems.
        `take_step` can optionally have the attribute ``take_step.stepsize``.
        If this attribute exists, then `basinhopping` will adjust
        ``take_step.stepsize`` in order to try to optimize the global minimum
        search.
    accept_test : callable, ``accept_test(f_new=f_new, x_new=x_new, f_old=fold, x_old=x_old)``, optional
        Define a test which will be used to judge whether to accept the
        step. This will be used in addition to the Metropolis test based on
        "temperature" `T`. The acceptable return values are True,
        False, or ``"force accept"``. If any of the tests return False
        then the step is rejected. If the latter, then this will override any
        other tests in order to accept the step. This can be used, for example,
        to forcefully escape from a local minimum that `basinhopping` is
        trapped in.
    callback : callable, ``callback(x, f, accept)``, optional
        A callback function which will be called for all minima found. ``x``
        and ``f`` are the coordinates and function value of the trial minimum,
        and ``accept`` is whether that minimum was accepted. This can
        be used, for example, to save the lowest N minima found. Also,
        `callback` can be used to specify a user defined stop criterion by
        optionally returning True to stop the `basinhopping` routine.
    interval : integer, optional
        interval for how often to update the `stepsize`
    disp : bool, optional
        Set to True to print status messages
    niter_success : integer, optional
        Stop the run if the global minimum candidate remains the same for this
        number of iterations.
    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``.

        The random numbers generated only affect the default Metropolis
        `accept_test` and the default `take_step`. If you supply your own
        `take_step` and `accept_test`, and these functions use random
        number generation, then those functions are responsible for the state
        of their random number generator.
    target_accept_rate : float, optional
        The target acceptance rate that is used to adjust the `stepsize`.
        If the current acceptance rate is greater than the target,
        then the `stepsize` is increased. Otherwise, it is decreased.
        Range is (0, 1). Default is 0.5.

        .. versionadded:: 1.8.0

    stepwise_factor : float, optional
        The `stepsize` is multiplied or divided by this stepwise factor upon
        each update. Range is (0, 1). Default is 0.9.

        .. versionadded:: 1.8.0

    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. The ``OptimizeResult`` object returned by the
        selected minimizer at the lowest minimum is also contained within this
        object and can be accessed through the ``lowest_optimization_result``
        attribute.  See `OptimizeResult` for a description of other attributes.

    See Also
    --------
    minimize :
        The local minimization function called once for each basinhopping step.
        `minimizer_kwargs` is passed to this routine.

    Notes
    -----
    Basin-hopping is a stochastic algorithm which attempts to find the global
    minimum of a smooth scalar function of one or more variables [1]_ [2]_ [3]_
    [4]_. The algorithm in its current form was described by David Wales and
    Jonathan Doye [2]_ http://www-wales.ch.cam.ac.uk/.

    The algorithm is iterative with each cycle composed of the following
    features

    1) random perturbation of the coordinates

    2) local minimization

    3) accept or reject the new coordinates based on the minimized function
       value

    The acceptance test used here is the Metropolis criterion of standard Monte
    Carlo algorithms, although there are many other possibilities [3]_.

    This global minimization method has been shown to be extremely efficient
    for a wide variety of problems in physics and chemistry. It is
    particularly useful when the function has many minima separated by large
    barriers. See the `Cambridge Cluster Database
    <https://www-wales.ch.cam.ac.uk/CCD.html>`_ for databases of molecular
    systems that have been optimized primarily using basin-hopping. This
    database includes minimization problems exceeding 300 degrees of freedom.

    See the free software program `GMIN <https://www-wales.ch.cam.ac.uk/GMIN>`_
    for a Fortran implementation of basin-hopping. This implementation has many
    variations of the procedure described above, including more
    advanced step taking algorithms and alternate acceptance criterion.

    For stochastic global optimization there is no way to determine if the true
    global minimum has actually been found. Instead, as a consistency check,
    the algorithm can be run from a number of different random starting points
    to ensure the lowest minimum found in each example has converged to the
    global minimum. For this reason, `basinhopping` will by default simply
    run for the number of iterations `niter` and return the lowest minimum
    found. It is left to the user to ensure that this is in fact the global
    minimum.

    Choosing `stepsize`:  This is a crucial parameter in `basinhopping` and
    depends on the problem being solved. The step is chosen uniformly in the
    region from x0-stepsize to x0+stepsize, in each dimension. Ideally, it
    should be comparable to the typical separation (in argument values) between
    local minima of the function being optimized. `basinhopping` will, by
    default, adjust `stepsize` to find an optimal value, but this may take
    many iterations. You will get quicker results if you set a sensible
    initial value for ``stepsize``.

    Choosing `T`: The parameter `T` is the "temperature" used in the
    Metropolis criterion. Basinhopping steps are always accepted if
    ``func(xnew) < func(xold)``. Otherwise, they are accepted with
    probability::

        exp( -(func(xnew) - func(xold)) / T )

    So, for best results, `T` should to be comparable to the typical
    difference (in function values) between local minima. (The height of
    "walls" between local minima is irrelevant.)

    If `T` is 0, the algorithm becomes Monotonic Basin-Hopping, in which all
    steps that increase energy are rejected.

    .. versionadded:: 0.12.0

    References
    ----------
    .. [1] Wales, David J. 2003, Energy Landscapes, Cambridge University Press,
        Cambridge, UK.
    .. [2] Wales, D J, and Doye J P K, Global Optimization by Basin-Hopping and
        the Lowest Energy Structures of Lennard-Jones Clusters Containing up to
        110 Atoms.  Journal of Physical Chemistry A, 1997, 101, 5111.
    .. [3] Li, Z. and Scheraga, H. A., Monte Carlo-minimization approach to the
        multiple-minima problem in protein folding, Proc. Natl. Acad. Sci. USA,
        1987, 84, 6611.
    .. [4] Wales, D. J. and Scheraga, H. A., Global optimization of clusters,
        crystals, and biomolecules, Science, 1999, 285, 1368.
    .. [5] Olson, B., Hashmi, I., Molloy, K., and Shehu1, A., Basin Hopping as
        a General and Versatile Optimization Framework for the Characterization
        of Biological Macromolecules, Advances in Artificial Intelligence,
        Volume 2012 (2012), Article ID 674832, :doi:`10.1155/2012/674832`

    Examples
    --------
    The following example is a 1-D minimization problem, with many
    local minima superimposed on a parabola.

    >>> import numpy as np
    >>> from scipy.optimize import basinhopping
    >>> func = lambda x: np.cos(14.5 * x - 0.3) + (x + 0.2) * x
    >>> x0 = [1.]

    Basinhopping, internally, uses a local minimization algorithm. We will use
    the parameter `minimizer_kwargs` to tell basinhopping which algorithm to
    use and how to set up that minimizer. This parameter will be passed to
    `scipy.optimize.minimize`.

    >>> minimizer_kwargs = {"method": "BFGS"}
    >>> ret = basinhopping(func, x0, minimizer_kwargs=minimizer_kwargs,
    ...                    niter=200)
    >>> # the global minimum is:
    >>> ret.x, ret.fun
    -0.1951, -1.0009

    Next consider a 2-D minimization problem. Also, this time, we
    will use gradient information to significantly speed up the search.

    >>> def func2d(x):
    ...     f = np.cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] +
    ...                                                            0.2) * x[0]
    ...     df = np.zeros(2)
    ...     df[0] = -14.5 * np.sin(14.5 * x[0] - 0.3) + 2. * x[0] + 0.2
    ...     df[1] = 2. * x[1] + 0.2
    ...     return f, df

    We'll also use a different local minimization algorithm. Also, we must tell
    the minimizer that our function returns both energy and gradient (Jacobian).

    >>> minimizer_kwargs = {"method":"L-BFGS-B", "jac":True}
    >>> x0 = [1.0, 1.0]
    >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
    ...                    niter=200)
    >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0],
    ...                                                           ret.x[1],
    ...                                                           ret.fun))
    global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109

    Here is an example using a custom step-taking routine. Imagine you want
    the first coordinate to take larger steps than the rest of the coordinates.
    This can be implemented like so:

    >>> class MyTakeStep:
    ...    def __init__(self, stepsize=0.5):
    ...        self.stepsize = stepsize
    ...        self.rng = np.random.default_rng()
    ...    def __call__(self, x):
    ...        s = self.stepsize
    ...        x[0] += self.rng.uniform(-2.*s, 2.*s)
    ...        x[1:] += self.rng.uniform(-s, s, x[1:].shape)
    ...        return x

    Since ``MyTakeStep.stepsize`` exists basinhopping will adjust the magnitude
    of `stepsize` to optimize the search. We'll use the same 2-D function as
    before

    >>> mytakestep = MyTakeStep()
    >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
    ...                    niter=200, take_step=mytakestep)
    >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0],
    ...                                                           ret.x[1],
    ...                                                           ret.fun))
    global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109

    Now, let's do an example using a custom callback function which prints the
    value of every minimum found

    >>> def print_fun(x, f, accepted):
    ...         print("at minimum %.4f accepted %d" % (f, int(accepted)))

    We'll run it for only 10 basinhopping steps this time.

    >>> rng = np.random.default_rng()
    >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
    ...                    niter=10, callback=print_fun, rng=rng)
    at minimum 0.4159 accepted 1
    at minimum -0.4317 accepted 1
    at minimum -1.0109 accepted 1
    at minimum -0.9073 accepted 1
    at minimum -0.4317 accepted 0
    at minimum -0.1021 accepted 1
    at minimum -0.7425 accepted 1
    at minimum -0.9073 accepted 1
    at minimum -0.4317 accepted 0
    at minimum -0.7425 accepted 1
    at minimum -0.9073 accepted 1

    The minimum at -1.0109 is actually the global minimum, found already on the
    8th iteration.

    g        r   z,target_accept_rate has to be in range (0, 1)z)stepwise_factor has to be in range (0, 1)Nztake_step must be callableri   )r\   ra   r]   r^   )ri   rs   zaccept_test must be callable)rs      )r/   T)r   r   zBrequested number of basinhopping iterations completed successfullyz7callback function requested stop early byreturning Truer'   r   zsuccess condition satisfied)!rE   r   arrayr   dictry   r1   r2   minimizecallable	TypeErrorr:   rU   rq   r~   appendr%   r9   r   r   r   rangerR   rO   rP   rI   r4   r   lowest_optimization_resultr   messagenitr   )r{   r;   niterr   ri   minimizer_kwargsrc   accept_testcallbackr\   r/   niter_successrs   r[   r   wrapped_minimizertake_step_wrappeddisplacer.   
metropolisbhcountir   rQ   valr4   s                              r   r   r   Y  s"   V	 R#5#;#;GHHH"2 5 5DEEE	"B S
!
!C 66()@$ = =+;= = 	"" 	:8999 9j)) 	* 0H.&	! ! ! !* &xSAAA,X9K4C59; ; ; L$$ 	<:;;;#} A3'''J
###		B 13D(t
5 
5 
5B
  C"$bj&7&;TBBB HE1  G5\\  H 	(29boryAAC  0 1GE
 	EE]""45GE #
 &C%'Z%:%:%<%<C"GC2455CE,0CGCK!eCG08CKJr   )r   r   rV   NNNNrW   FNN)r"   numpyr   r   rB   scipy.optimizer1   scipy._lib._utilr   r   __all__	ParameterKEYWORD_ONLY_params	SignaturerD   r   r%   rU   rq   ry   r~   r   r#   r   r   <module>r      s              C C C C C C C C
 7YW->-KLLL7YW->-KLLLN.W.'BBB        .T5 T5 T5 T5 T5 T5 T5 T5n? ? ? ? ? ? ? ?D       .@ @ @ @ @ @ @ @ -: -: -: -: -: -: -: -:` F>>>69DHGKE 25cE E E E ?>E E Er   