ó
Ê½÷Xc           @` s'  d  Z  d d l m Z m Z m Z d d l Z d d l m Z m Z d d l	 Z
 d d l Z d d l m Z d g Z d e f d „  ƒ  YZ d	 e f d
 „  ƒ  YZ d e f d „  ƒ  YZ d e f d „  ƒ  YZ d e f d „  ƒ  YZ d e f d „  ƒ  YZ d d d e e e e d e e e d „ Z d „  Z d „  Z e d k r#e d ƒ i d d 6Z e j d d g ƒ Z e
 j  j! e e e  e e e d e d d  d! e ƒZ" e d" ƒ e e" ƒ e d# ƒ i d d 6e# d$ 6Z e j d d g ƒ Z e e e d e d d  d! e ƒZ" e d% ƒ e e" ƒ n  d S(&   s>   
basinhopping: The basinhopping global optimization algorithm
i    (   t   divisiont   print_functiont   absolute_importN(   t   cost   sin(   t   check_random_statet   basinhoppingt   Storagec           B` s2   e  Z d  Z d „  Z d „  Z d „  Z d „  Z RS(   s9   
    Class used to store the lowest energy structure
    c         C` s   |  j  | ƒ d  S(   N(   t   _add(   t   selft   minres(    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyt   __init__   s    c         C` s%   | |  _  t j | j ƒ |  j  _ d  S(   N(   R
   t   npt   copyt   x(   R	   R
   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyR      s    	c         C` s.   | j  |  j j  k  r& |  j | ƒ t St Sd  S(   N(   t   funR
   R   t   Truet   False(   R	   R
   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyt   update   s    c         C` s   |  j  S(   N(   R
   (   R	   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyt
   get_lowest!   s    (   t   __name__t
   __module__t   __doc__R   R   R   R   (    (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyR      s
   			t   BasinHoppingRunnerc           B` s5   e  Z d  Z e d „ Z d „  Z d „  Z d „  Z RS(   s8  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 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.
    disp : bool, optional
        Display status messages.

    c         C` s]  t  j | ƒ |  _ | |  _ | |  _ | |  _ | |  _ d |  _ t j	 j
 ƒ  |  _ d |  j _ | |  j ƒ } | j s  |  j j d 7_ |  j r  t d ƒ q  n  t  j | j ƒ |  _ | j |  _ |  j rç t d |  j |  j f ƒ n  t | ƒ |  _ t | d ƒ r| j |  j _ n  t | d ƒ r8| j |  j _ n  t | d ƒ rY| j |  j _ n  d  S(   Ni    i   s1   warning: basinhopping: local minimization failures   basinhopping step %d: f %gt   nfevt   njevt   nhev(   R   R   R   t	   minimizert   step_takingt   accept_testst   dispt   nstept   scipyt   optimizet   OptimizeResultt   rest   minimization_failurest   successt   printR   t   energyR   t   storaget   hasattrR   R   R   (   R	   t   x0R   R   R   R   R
   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyR   <   s0    								c      
   C` sž  t  j |  j ƒ } |  j | ƒ } |  j | ƒ } | j } | j } | j sv |  j j d 7_ |  j	 rv t
 d ƒ qv n  t | d ƒ r |  j j | j 7_ n  t | d ƒ rÄ |  j j | j 7_ n  t | d ƒ rë |  j j | j 7_ n  t } x] |  j D]R } | d | d | d |  j d	 |  j ƒ } | d
 k r>t } Pqû | sû t } qû qû Wt |  j d ƒ r”|  j j | d | d | d |  j d	 |  j ƒn  | | f S(   sœ   Do one monte carlo iteration

        Randomly displace the coordinates, minimize, and decide whether
        or not to accept the new coordinates.
        i   s1   warning: basinhopping: local minimization failureR   R   R   t   f_newt   x_newt   f_oldt   x_olds   force acceptt   report(   R   R   R   R   R   R   R%   R#   R$   R   R&   R)   R   R   R   R   R   R'   R   R/   (   R	   t   x_after_stepR
   t   x_after_quencht   energy_after_quencht   acceptt   testt   testres(    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyt   _monte_carlo_step^   s:    				c         C` sÊ   |  j  d 7_  t } |  j ƒ  \ } } | rc | j |  _ t j | j ƒ |  _ |  j j	 | ƒ } n  |  j
 r¥ |  j | j | ƒ | r¥ t d |  j  |  j f ƒ q¥ n  | j |  _ | j |  _ | |  _ | S(   s3   Do one cycle of the basinhopping algorithm
        i   s:   found new global minimum on step %d with function value %g(   R   R   R6   R   R'   R   R   R   R(   R   R   t   print_reportR&   t   xtrialt   energy_trialR3   (   R	   t   new_global_minR3   R
   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyt	   one_cycle‘   s     		c         C` s9   |  j  j ƒ  } t d |  j |  j | | | j f ƒ d S(   s   print a status updates>   basinhopping step %d: f %g trial_f %g accepted %d  lowest_f %gN(   R(   R   R&   R   R'   R   (   R	   R9   R3   R
   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyR7   ¬   s    (   R   R   R   R   R   R6   R;   R7   (    (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyR   %   s
   "	3	t   AdaptiveStepsizec           B` sG   e  Z d  Z d d d e d „ Z d „  Z d „  Z d „  Z d „  Z RS(	   s´  
    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

    g      à?i2   gÍÌÌÌÌÌì?c         C` sL   | |  _  | |  _ | |  _ | |  _ | |  _ d |  _ d |  _ d |  _ d  S(   Ni    (   t   takestept   target_accept_ratet   intervalt   factort   verboseR   t	   nstep_tott   naccept(   R	   R=   t   accept_rateR?   R@   RA   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyR   Ë   s    							c         C` s   |  j  | ƒ S(   N(   t	   take_step(   R	   R   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyt   __call__×   s    c         C` s‘   |  j  j } t |  j ƒ |  j } | |  j k rI |  j  j |  j _ n |  j  j |  j 9_ |  j r t d | |  j |  j  j | f ƒ n  d  S(   NsO   adaptive stepsize: acceptance rate %f target %f new stepsize %g old stepsize %g(	   R=   t   stepsizet   floatRC   R   R>   R@   RA   R&   (   R	   t   old_stepsizeRD   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyt   _adjust_step_sizeÚ   s    	c         C` sN   |  j  d 7_  |  j d 7_ |  j  |  j d k rA |  j ƒ  n  |  j | ƒ S(   Ni   i    (   R   RB   R?   RJ   R=   (   R	   R   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyRE   ê   s
    c         K` s   | r |  j  d 7_  n  d S(   s7   called by basinhopping to report the result of the stepi   N(   RC   (   R	   R3   t   kwargs(    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyR/   ñ   s    (	   R   R   R   R   R   RF   RJ   RE   R/   (    (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyR<   ´   s   				t   RandomDisplacementc           B` s&   e  Z d  Z d d d „ Z d „  Z RS(   sA  
    Add a random displacement of maximum size, stepsize, to the coordinates

    update x inplace

    Parameters
    ----------
    stepsize : float, optional
        stepsize
    random_state : None or `np.random.RandomState` instance, optional
        The random number generator that generates the displacements
    g      à?c         C` s   | |  _  t | ƒ |  _ d  S(   N(   RG   R   t   random_state(   R	   RG   RM   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyR     s    	c         C` s0   | |  j  j |  j |  j t j | ƒ ƒ 7} | S(   N(   RM   t   uniformRG   R   t   shape(   R	   R   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyRF     s    ,N(   R   R   R   t   NoneR   RF   (    (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyRL   ÷   s   t   MinimizerWrapperc           B` s#   e  Z d  Z d d „ Z d „  Z RS(   s8   
    wrap a minimizer function as a minimizer class
    c         K` s   | |  _  | |  _ | |  _ d  S(   N(   R   t   funcRK   (   R	   R   RR   RK   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyR     s    		c         C` s?   |  j  d  k r" |  j | |  j  S|  j |  j  | |  j  Sd  S(   N(   RR   RP   R   RK   (   R	   R*   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyRF     s    N(   R   R   R   RP   R   RF   (    (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyRQ     s   t
   Metropolisc           B` s,   e  Z d  Z d d „ Z d „  Z d „  Z RS(   s»   
    Metropolis acceptance criterion

    Parameters
    ----------
    random_state : None or `np.random.RandomState` object
        Random number generator used for acceptance test
    c         C` s    d | |  _  t | ƒ |  _ d  S(   Ng      ð?(   t   betaR   RM   (   R	   t   TRM   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyR   &  s    c         C` s=   t  d t j | | |  j ƒ ƒ } |  j j ƒ  } | | k S(   Ng      ð?(   t   minR   t   expRT   RM   t   rand(   R	   t
   energy_newt
   energy_oldt   wRX   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyt   accept_reject*  s    $c         K` s   t  |  j | d | d ƒ ƒ S(   s9   
        f_new and f_old are mandatory in kwargs
        R+   R-   (   t   boolR\   (   R	   RK   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyRF   /  s    N(   R   R   R   RP   R   R\   RF   (    (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyRS     s   	id   g      ð?g      à?i2   c         C` sŠ  t  j | ƒ } t | ƒ } | t k r3 t ƒ  } n  t t j j |  |  } | t k	 r¬ t	 | t
 j ƒ ry t d ƒ ‚ n  t | d ƒ r£ t | d |	 d |
 ƒ} n | } n- t d | d | ƒ } t | d |	 d |
 ƒ} | t k	 rt	 | t
 j ƒ rt d ƒ ‚ n  | g } n g  } t | d | ƒ} | j | ƒ | t k rQ| d } n  t | | | | d |
 ƒ} d	 d	 f \ } } d
 g } x¤ t | ƒ D]– } | j ƒ  } t	 | t
 j ƒ rø| | j | j | j ƒ } | t k	 rõ| ròd g } Pn  n  n  | d 7} | rd	 } n | | k r*d g } Pn  q”W| j } | j j ƒ  | _ t  j | j j ƒ | _ | j j | _ | | _ | d | _  | S(   sã2  
    Find the global minimum of a function using the basin-hopping algorithm

    Parameters
    ----------
    func : callable ``f(x, *args)``
        Function to be optimized.  ``args`` can be passed as an optional item
        in the dict ``minimizer_kwargs``
    x0 : ndarray
        Initial guess.
    niter : integer, optional
        The number of basin hopping iterations
    T : float, optional
        The "temperature" parameter for the accept or reject 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
        initial step size for use in the random displacement.
    minimizer_kwargs : dict, optional
        Extra keyword arguments to be passed to the 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 or not 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 or not 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.
    seed : int or `np.random.RandomState`, optional
        If `seed` is not specified the `np.RandomState` singleton is used.
        If `seed` is an int, a new `np.random.RandomState` instance is used,
        seeded with seed.
        If `seed` is already a `np.random.RandomState instance`, then that
        `np.random.RandomState` instance is used.
        Specify `seed` for repeatable minimizations. The random numbers
        generated with this seed 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.

    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 ``OptimzeResult`` 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
    http://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 (http://www-wales.ch.cam.ac.uk/GMIN) for
    a Fortran implementation of basin-hopping.  This implementation has many
    different 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.  Ideally it should be comparable to
    the typical separation 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 value for ``stepsize``.

    Choosing ``T``: The parameter ``T`` is the temperature used in the
    metropolis criterion.  Basinhopping steps are accepted with probability
    ``1`` if ``func(xnew) < func(xold)``, or otherwise 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.

    .. 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.

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

    >>> 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)
    >>> print("global minimum: x = %.4f, f(x0) = %.4f" % (ret.x, ret.fun))
    global minimum: x = -0.1951, f(x0) = -1.0009

    Next consider a two-dimensional 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(x0) = %.4f" % (ret.x[0],
    ...                                                           ret.x[1],
    ...                                                           ret.fun))
    global minimum: x = [-0.1951, -0.1000], f(x0) = -1.0109


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

    >>> class MyTakeStep(object):
    ...    def __init__(self, stepsize=0.5):
    ...        self.stepsize = stepsize
    ...    def __call__(self, x):
    ...        s = self.stepsize
    ...        x[0] += np.random.uniform(-2.*s, 2.*s)
    ...        x[1:] += np.random.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(x0) = %.4f" % (ret.x[0],
    ...                                                           ret.x[1],
    ...                                                           ret.fun))
    global minimum: x = [-0.1951, -0.1000], f(x0) = -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.

    >>> np.random.seed(1)
    >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
    ...                    niter=10, callback=print_fun)
    at minimum 0.4159 accepted 1
    at minimum -0.9073 accepted 1
    at minimum -0.1021 accepted 1
    at minimum -0.1021 accepted 1
    at minimum 0.9102 accepted 1
    at minimum 0.9102 accepted 1
    at minimum 2.2945 accepted 0
    at minimum -0.1021 accepted 1
    at minimum -1.0109 accepted 1
    at minimum -1.0109 accepted 1


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

    Now let's implement bounds on the problem using a custom ``accept_test``:

    >>> class MyBounds(object):
    ...     def __init__(self, xmax=[1.1,1.1], xmin=[-1.1,-1.1] ):
    ...         self.xmax = np.array(xmax)
    ...         self.xmin = np.array(xmin)
    ...     def __call__(self, **kwargs):
    ...         x = kwargs["x_new"]
    ...         tmax = bool(np.all(x <= self.xmax))
    ...         tmin = bool(np.all(x >= self.xmin))
    ...         return tmax and tmin

    >>> mybounds = MyBounds()
    >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
    ...                    niter=10, accept_test=mybounds)

    s   take_step must be callableRG   R?   RA   RM   s   accept_test must be callablei   R   i    sB   requested number of basinhopping iterations completed successfullys7   callback function requested stop early byreturning Truei   s   success condition satisfied(!   R   t   arrayR   RP   t   dictRQ   R    R!   t   minimizet
   isinstancet   collectionst   Callablet	   TypeErrorR)   R<   RL   RS   t   appendR   t   rangeR;   R8   R9   R3   R#   R(   R   t   lowest_optimization_resultR   R   R   t   messaget   nit(   RR   R*   t   niterRU   RG   t   minimizer_kwargsRE   t   accept_testt   callbackR?   R   t   niter_successt   seedt   rngt   wrapped_minimizert   take_step_wrappedt   displaceR   t
   metropolist   bht   countt   iRh   R:   t   valR#   (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyR   7  sf    ÿ 					

				c         C` sH   t  d |  d d ƒ |  d d |  d |  d d |  d d } | S(   Ng      -@i    g333333Ó?i   gš™™™™™É?g’È‡Œ,ð?(   R   (   R   t   f(    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyt   _test_func2d_nogradž  s    Dc         C` só   t  d |  d d ƒ |  d d |  d t  d |  d d ƒ |  d d |  d |  d |  d d } t j d ƒ } d t d |  d d ƒ d	 |  d d |  d | d <d t d |  d d ƒ d	 |  d d |  d | d <| | f S(
   Ng      -@i    g333333Ó?gš™™™™™É?i   g…Qälÿ?i   g      -Àg       @(   R   R   t   zerosR   (   R   Ry   t   df(    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyt   _test_func2d¤  s
    j88t   __main__s)   

minimize a 2d function without gradients   L-BFGS-Bt   methodRk   Rj   iÈ   R   s/   minimum expected at  func([-0.195, -0.1]) = 0.0s   

try a harder 2d problemt   jacs;   minimum expected at ~, func([-0.19415263, -0.19415263]) = 0($   R   t
   __future__R    R   R   t   numpyR   R   R   t   scipy.optimizeR    Rb   t   scipy._lib._utilR   t   __all__t   objectR   R   R<   RL   RQ   RS   RP   R   R   Rz   R}   R   R&   RK   R^   R*   R!   R`   t   retR   (    (    (    s;   /tmp/pip-build-7oUkmx/scipy/scipy/optimize/_basinhopping.pyt   <module>   sH   	C		ÿ e		



	
