
    ^MhQ                    *   d Z ddlZddlZddlmZmZ ddlmZm	Z	 ddl
mZmZmZmZmZ ddlmZmZmZmZ ddlmZ dgZ ej        ej                  j        Z ed	d
          	 	 	 	 	 	 ddddd            Z G d d          Z G d d          ZdS )zn
differential_evolution: The differential evolution global optimization algorithm
Added by Andrew Nelson 2014
    N)OptimizeResultminimize)_status_message_wrap_callback)check_random_state
MapWrapper_FunctionWrapperrng_integers_transition_to_rng)Boundsnew_bounds_to_oldNonlinearConstraintLinearConstraint)issparsedifferential_evolutionseed	   )position_num best1bin     {Gz?      ?   ffffff?FTlatinhypercube	immediater   integrality
vectorizedc                    t          | |fi d|d|d|d|d|d|d|d|	d	|d
|
d|d|d|d|d|d|d|d|d|5 }|                                }ddd           n# 1 swxY w Y   |S )aT  Finds the global minimum of a multivariate function.

    The differential evolution method [1]_ is stochastic in nature. It does
    not use gradient methods to find the minimum, and can search large areas
    of candidate space, but often requires larger numbers of function
    evaluations than conventional gradient-based techniques.

    The algorithm is due to Storn and Price [2]_.

    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. The number of parameters, N, is equal
        to ``len(x)``.
    bounds : sequence or `Bounds`
        Bounds for variables. There are two ways to specify the bounds:

        1. Instance of `Bounds` class.
        2. ``(min, max)`` pairs for each element in ``x``, defining the
           finite lower and upper bounds for the optimizing argument of
           `func`.

        The total number of bounds is used to determine the number of
        parameters, N. If there are parameters whose bounds are equal the total
        number of free parameters is ``N - N_equal``.

    args : tuple, optional
        Any additional fixed parameters needed to
        completely specify the objective function.
    strategy : {str, callable}, optional
        The differential evolution strategy to use. Should be one of:

        - 'best1bin'
        - 'best1exp'
        - 'rand1bin'
        - 'rand1exp'
        - 'rand2bin'
        - 'rand2exp'
        - 'randtobest1bin'
        - 'randtobest1exp'
        - 'currenttobest1bin'
        - 'currenttobest1exp'
        - 'best2exp'
        - 'best2bin'

        The default is 'best1bin'. Strategies that may be implemented are
        outlined in 'Notes'.
        Alternatively the differential evolution strategy can be customized by
        providing a callable that constructs a trial vector. The callable must
        have the form ``strategy(candidate: int, population: np.ndarray, rng=None)``,
        where ``candidate`` is an integer specifying which entry of the
        population is being evolved, ``population`` is an array of shape
        ``(S, N)`` containing all the population members (where S is the
        total population size), and ``rng`` is the random number generator
        being used within the solver.
        ``candidate`` will be in the range ``[0, S)``.
        ``strategy`` must return a trial vector with shape ``(N,)``. The
        fitness of this trial vector is compared against the fitness of
        ``population[candidate]``.

        .. versionchanged:: 1.12.0
            Customization of evolution strategy via a callable.

    maxiter : int, optional
        The maximum number of generations over which the entire population is
        evolved. The maximum number of function evaluations (with no polishing)
        is: ``(maxiter + 1) * popsize * (N - N_equal)``
    popsize : int, optional
        A multiplier for setting the total population size. The population has
        ``popsize * (N - N_equal)`` individuals. This keyword is overridden if
        an initial population is supplied via the `init` keyword. When using
        ``init='sobol'`` the population size is calculated as the next power
        of 2 after ``popsize * (N - N_equal)``.
    tol : float, optional
        Relative tolerance for convergence, the solving stops when
        ``np.std(population_energies) <= atol + tol * np.abs(np.mean(population_energies))``,
        where and `atol` and `tol` are the absolute and relative tolerance
        respectively.
    mutation : float or tuple(float, float), optional
        The mutation constant. In the literature this is also known as
        differential weight, being denoted by :math:`F`.
        If specified as a float it should be in the range [0, 2).
        If specified as a tuple ``(min, max)`` dithering is employed. Dithering
        randomly changes the mutation constant on a generation by generation
        basis. The mutation constant for that generation is taken from
        ``U[min, max)``. Dithering can help speed convergence significantly.
        Increasing the mutation constant increases the search radius, but will
        slow down convergence.
    recombination : float, optional
        The recombination constant, should be in the range [0, 1]. In the
        literature this is also known as the crossover probability, being
        denoted by CR. Increasing this value allows a larger number of mutants
        to progress into the next generation, but at the risk of population
        stability.
    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``.
    disp : bool, optional
        Prints the evaluated `func` at every iteration.
    callback : callable, optional
        A callable called after each iteration. Has the signature::

            callback(intermediate_result: OptimizeResult)

        where ``intermediate_result`` is a keyword parameter containing an
        `OptimizeResult` with attributes ``x`` and ``fun``, the best solution
        found so far and the objective function. Note that the name
        of the parameter must be ``intermediate_result`` for the callback
        to be passed an `OptimizeResult`.

        The callback also supports a signature like::

            callback(x, convergence: float=val)

        ``val`` represents the fractional value of the population convergence.
        When ``val`` is greater than ``1.0``, the function halts.

        Introspection is used to determine which of the signatures is invoked.

        Global minimization will halt if the callback raises ``StopIteration``
        or returns ``True``; any polishing is still carried out.

        .. versionchanged:: 1.12.0
            callback accepts the ``intermediate_result`` keyword.

    polish : bool, optional
        If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B`
        method is used to polish the best population member at the end, which
        can improve the minimization slightly. If a constrained problem is
        being studied then the `trust-constr` method is used instead. For large
        problems with many constraints, polishing can take a long time due to
        the Jacobian computations.

        .. versionchanged:: 1.15.0
            If `workers` is specified then the map-like callable that wraps
            `func` is supplied to `minimize` instead of it using `func`
            directly. This allows the caller to control how and where the
            invocations actually run.

    init : str or array-like, optional
        Specify which type of population initialization is performed. Should be
        one of:

        - 'latinhypercube'
        - 'sobol'
        - 'halton'
        - 'random'
        - array specifying the initial population. The array should have
          shape ``(S, N)``, where S is the total population size and N is
          the number of parameters.

        `init` is clipped to `bounds` before use.

        The default is 'latinhypercube'. Latin Hypercube sampling tries to
        maximize coverage of the available parameter space.

        'sobol' and 'halton' are superior alternatives and maximize even more
        the parameter space. 'sobol' will enforce an initial population
        size which is calculated as the next power of 2 after
        ``popsize * (N - N_equal)``. 'halton' has no requirements but is a bit
        less efficient. See `scipy.stats.qmc` for more details.

        'random' initializes the population randomly - this has the drawback
        that clustering can occur, preventing the whole of parameter space
        being covered. Use of an array to specify a population could be used,
        for example, to create a tight bunch of initial guesses in an location
        where the solution is known to exist, thereby reducing time for
        convergence.
    atol : float, optional
        Absolute tolerance for convergence, the solving stops when
        ``np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))``,
        where and `atol` and `tol` are the absolute and relative tolerance
        respectively.
    updating : {'immediate', 'deferred'}, optional
        If ``'immediate'``, the best solution vector is continuously updated
        within a single generation [4]_. This can lead to faster convergence as
        trial vectors can take advantage of continuous improvements in the best
        solution.
        With ``'deferred'``, the best solution vector is updated once per
        generation. Only ``'deferred'`` is compatible with parallelization or
        vectorization, and the `workers` and `vectorized` keywords can
        over-ride this option.

        .. versionadded:: 1.2.0

    workers : int or map-like callable, optional
        If `workers` is an int the population is subdivided into `workers`
        sections and evaluated in parallel
        (uses `multiprocessing.Pool <multiprocessing>`).
        Supply -1 to use all available CPU cores.
        Alternatively supply a map-like callable, such as
        `multiprocessing.Pool.map` for evaluating the population in parallel.
        This evaluation is carried out as ``workers(func, iterable)``.
        This option will override the `updating` keyword to
        ``updating='deferred'`` if ``workers != 1``.
        This option overrides the `vectorized` keyword if ``workers != 1``.
        Requires that `func` be pickleable.

        .. versionadded:: 1.2.0

    constraints : {NonLinearConstraint, LinearConstraint, Bounds}
        Constraints on the solver, over and above those applied by the `bounds`
        kwd. Uses the approach by Lampinen [5]_.

        .. versionadded:: 1.4.0

    x0 : None or array-like, optional
        Provides an initial guess to the minimization. Once the population has
        been initialized this vector replaces the first (best) member. This
        replacement is done even if `init` is given an initial population.
        ``x0.shape == (N,)``.

        .. versionadded:: 1.7.0

    integrality : 1-D array, optional
        For each decision variable, a boolean value indicating whether the
        decision variable is constrained to integer values. The array is
        broadcast to ``(N,)``.
        If any decision variables are constrained to be integral, they will not
        be changed during polishing.
        Only integer values lying between the lower and upper bounds are used.
        If there are no integer values lying between the bounds then a
        `ValueError` is raised.

        .. versionadded:: 1.9.0

    vectorized : bool, optional
        If ``vectorized is True``, `func` is sent an `x` array with
        ``x.shape == (N, S)``, and is expected to return an array of shape
        ``(S,)``, where `S` is the number of solution vectors to be calculated.
        If constraints are applied, each of the functions used to construct
        a `Constraint` object should accept an `x` array with
        ``x.shape == (N, S)``, and return an array of shape ``(M, S)``, where
        `M` is the number of constraint components.
        This option is an alternative to the parallelization offered by
        `workers`, and may help in optimization speed by reducing interpreter
        overhead from multiple function calls. This keyword is ignored if
        ``workers != 1``.
        This option will override the `updating` keyword to
        ``updating='deferred'``.
        See the notes section for further discussion on when to use
        ``'vectorized'``, and when to use ``'workers'``.

        .. versionadded:: 1.9.0

    Returns
    -------
    res : OptimizeResult
        The optimization result represented as a `OptimizeResult` object.
        Important attributes are: ``x`` the solution array, ``success`` a
        Boolean flag indicating if the optimizer exited successfully,
        ``message`` which describes the cause of the termination,
        ``population`` the solution vectors present in the population, and
        ``population_energies`` the value of the objective function for each
        entry in ``population``.
        See `OptimizeResult` for a description of other attributes. If `polish`
        was employed, and a lower minimum was obtained by the polishing, then
        OptimizeResult also contains the ``jac`` attribute.
        If the eventual solution does not satisfy the applied constraints
        ``success`` will be `False`.

    Notes
    -----
    Differential evolution is a stochastic population based method that is
    useful for global optimization problems. At each pass through the
    population the algorithm mutates each candidate solution by mixing with
    other candidate solutions to create a trial candidate. There are several
    strategies [3]_ for creating trial candidates, which suit some problems
    more than others. The 'best1bin' strategy is a good starting point for
    many systems. In this strategy two members of the population are randomly
    chosen. Their difference is used to mutate the best member (the 'best' in
    'best1bin'), :math:`x_0`, so far:

    .. math::

        b' = x_0 + F \cdot (x_{r_0} - x_{r_1})

    where :math:`F` is the `mutation` parameter.
    A trial vector is then constructed. Starting with a randomly chosen ith
    parameter the trial is sequentially filled (in modulo) with parameters
    from ``b'`` or the original candidate. The choice of whether to use ``b'``
    or the original candidate is made with a binomial distribution (the 'bin'
    in 'best1bin') - a random number in [0, 1) is generated. If this number is
    less than the `recombination` constant then the parameter is loaded from
    ``b'``, otherwise it is loaded from the original candidate. The final
    parameter is always loaded from ``b'``. Once the trial candidate is built
    its fitness is assessed. If the trial is better than the original candidate
    then it takes its place. If it is also better than the best overall
    candidate it also replaces that.

    The other strategies available are outlined in Qiang and
    Mitchell (2014) [3]_.


    - ``rand1`` : :math:`b' = x_{r_0} + F \cdot (x_{r_1} - x_{r_2})`
    - ``rand2`` : :math:`b' = x_{r_0} + F \cdot (x_{r_1} + x_{r_2} - x_{r_3} - x_{r_4})`
    - ``best1`` : :math:`b' = x_0 + F \cdot (x_{r_0} - x_{r_1})`
    - ``best2`` : :math:`b' = x_0 + F \cdot (x_{r_0} + x_{r_1} - x_{r_2} - x_{r_3})`
    - ``currenttobest1`` : :math:`b' = x_i + F \cdot (x_0 - x_i + x_{r_0} - x_{r_1})`
    - ``randtobest1`` : :math:`b' = x_{r_0} + F \cdot (x_0 - x_{r_0} + x_{r_1} - x_{r_2})`

    where the integers :math:`r_0, r_1, r_2, r_3, r_4` are chosen randomly
    from the interval [0, NP) with `NP` being the total population size and
    the original candidate having index `i`. The user can fully customize the
    generation of the trial candidates by supplying a callable to ``strategy``.

    To improve your chances of finding a global minimum use higher `popsize`
    values, with higher `mutation` and (dithering), but lower `recombination`
    values. This has the effect of widening the search radius, but slowing
    convergence.

    By default the best solution vector is updated continuously within a single
    iteration (``updating='immediate'``). This is a modification [4]_ of the
    original differential evolution algorithm which can lead to faster
    convergence as trial vectors can immediately benefit from improved
    solutions. To use the original Storn and Price behaviour, updating the best
    solution once per iteration, set ``updating='deferred'``.
    The ``'deferred'`` approach is compatible with both parallelization and
    vectorization (``'workers'`` and ``'vectorized'`` keywords). These may
    improve minimization speed by using computer resources more efficiently.
    The ``'workers'`` distribute calculations over multiple processors. By
    default the Python `multiprocessing` module is used, but other approaches
    are also possible, such as the Message Passing Interface (MPI) used on
    clusters [6]_ [7]_. The overhead from these approaches (creating new
    Processes, etc) may be significant, meaning that computational speed
    doesn't necessarily scale with the number of processors used.
    Parallelization is best suited to computationally expensive objective
    functions. If the objective function is less expensive, then
    ``'vectorized'`` may aid by only calling the objective function once per
    iteration, rather than multiple times for all the population members; the
    interpreter overhead is reduced.

    .. versionadded:: 0.15.0

    References
    ----------
    .. [1] Differential evolution, Wikipedia,
           http://en.wikipedia.org/wiki/Differential_evolution
    .. [2] Storn, R and Price, K, Differential Evolution - a Simple and
           Efficient Heuristic for Global Optimization over Continuous Spaces,
           Journal of Global Optimization, 1997, 11, 341 - 359.
    .. [3] Qiang, J., Mitchell, C., A Unified Differential Evolution Algorithm
            for Global Optimization, 2014, https://www.osti.gov/servlets/purl/1163659
    .. [4] Wormington, M., Panaccione, C., Matney, K. M., Bowen, D. K., -
           Characterization of structures from X-ray scattering data using
           genetic algorithms, Phil. Trans. R. Soc. Lond. A, 1999, 357,
           2827-2848
    .. [5] Lampinen, J., A constraint handling approach for the differential
           evolution algorithm. Proceedings of the 2002 Congress on
           Evolutionary Computation. CEC'02 (Cat. No. 02TH8600). Vol. 2. IEEE,
           2002.
    .. [6] https://mpi4py.readthedocs.io/en/stable/
    .. [7] https://schwimmbad.readthedocs.io/en/latest/
 

    Examples
    --------
    Let us consider the problem of minimizing the Rosenbrock function. This
    function is implemented in `rosen` in `scipy.optimize`.

    >>> import numpy as np
    >>> from scipy.optimize import rosen, differential_evolution
    >>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)]
    >>> result = differential_evolution(rosen, bounds)
    >>> result.x, result.fun
    (array([1., 1., 1., 1., 1.]), 1.9216496320061384e-19)

    Now repeat, but with parallelization.

    >>> result = differential_evolution(rosen, bounds, updating='deferred',
    ...                                 workers=2)
    >>> result.x, result.fun
    (array([1., 1., 1., 1., 1.]), 1.9216496320061384e-19)

    Let's do a constrained minimization.

    >>> from scipy.optimize import LinearConstraint, Bounds

    We add the constraint that the sum of ``x[0]`` and ``x[1]`` must be less
    than or equal to 1.9.  This is a linear constraint, which may be written
    ``A @ x <= 1.9``, where ``A = array([[1, 1]])``.  This can be encoded as
    a `LinearConstraint` instance:

    >>> lc = LinearConstraint([[1, 1]], -np.inf, 1.9)

    Specify limits using a `Bounds` object.

    >>> bounds = Bounds([0., 0.], [2., 2.])
    >>> result = differential_evolution(rosen, bounds, constraints=lc,
    ...                                 rng=1)
    >>> result.x, result.fun
    (array([0.96632622, 0.93367155]), 0.0011352416852625719)

    Next find the minimum of the Ackley function
    (https://en.wikipedia.org/wiki/Test_functions_for_optimization).

    >>> def ackley(x):
    ...     arg1 = -0.2 * np.sqrt(0.5 * (x[0] ** 2 + x[1] ** 2))
    ...     arg2 = 0.5 * (np.cos(2. * np.pi * x[0]) + np.cos(2. * np.pi * x[1]))
    ...     return -20. * np.exp(arg1) - np.exp(arg2) + 20. + np.e
    >>> bounds = [(-5, 5), (-5, 5)]
    >>> result = differential_evolution(ackley, bounds, rng=1)
    >>> result.x, result.fun
    (array([0., 0.]), 4.440892098500626e-16)

    The Ackley function is written in a vectorized manner, so the
    ``'vectorized'`` keyword can be employed. Note the reduced number of
    function evaluations.

    >>> result = differential_evolution(
    ...     ackley, bounds, vectorized=True, updating='deferred', rng=1
    ... )
    >>> result.x, result.fun
    (array([0., 0.]), 4.440892098500626e-16)

    The following custom strategy function mimics 'best1bin':

    >>> def custom_strategy_fn(candidate, population, rng=None):
    ...     parameter_count = population.shape(-1)
    ...     mutation, recombination = 0.7, 0.9
    ...     trial = np.copy(population[candidate])
    ...     fill_point = rng.choice(parameter_count)
    ...
    ...     pool = np.arange(len(population))
    ...     rng.shuffle(pool)
    ...
    ...     # two unique random numbers that aren't the same, and
    ...     # aren't equal to candidate.
    ...     idxs = []
    ...     while len(idxs) < 2 and len(pool) > 0:
    ...         idx = pool[0]
    ...         pool = pool[1:]
    ...         if idx != candidate:
    ...             idxs.append(idx)
    ...
    ...     r0, r1 = idxs[:2]
    ...
    ...     bprime = (population[0] + mutation *
    ...               (population[r0] - population[r1]))
    ...
    ...     crossovers = rng.uniform(size=parameter_count)
    ...     crossovers = crossovers < recombination
    ...     crossovers[fill_point] = True
    ...     trial = np.where(crossovers, bprime, trial)
    ...     return trial

    argsstrategymaxiterpopsizetolmutationrecombinationrngpolishcallbackdispinitatolupdatingworkersconstraintsx0r!   r"   N)DifferentialEvolutionSolversolve)funcboundsr$   r%   r&   r'   r(   r)   r*   r+   r-   r.   r,   r/   r0   r1   r2   r3   r4   r!   r"   solverrets                          e/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/optimize/_differentialevolution.pyr   r      si   ^ 
%T6 
< 
< 
< 
<.6h
<-4W
< .5W
< ;>#
< /7h	
<
 4A=
< *-
< 6<V
< /7h
< +/$
< 6:T
< AE
< /7h
< .5W
< 2=
< )+
< 2=
< 1;

<  @Fllnn              " Js   A''A+.A+c                   R   e Zd ZdZdddddddZddddddd	Zd
Zddddddddej        dddddddddfddddZ	d Z
d Zd Zd Zed             Zed              Zd! Zd" Zd# Zd$ Zd% Zd& Zd' Zd( Zd) Zd* Zd+ Zd, Zd- Zd. Zd/ Zd0 Z d1 Z!d2 Z"d3 Z#d4 Z$d5 Z%d6 Z&d7 Z'd8 Z(d9 Z)dS ):r5   a/  This class implements the differential evolution solver

    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. The number of parameters, N, is equal
        to ``len(x)``.
    bounds : sequence or `Bounds`
        Bounds for variables. There are two ways to specify the bounds:

            1. Instance of `Bounds` class.
            2. ``(min, max)`` pairs for each element in ``x``, defining the
               finite lower and upper bounds for the optimizing argument of
               `func`.

        The total number of bounds is used to determine the number of
        parameters, N. If there are parameters whose bounds are equal the total
        number of free parameters is ``N - N_equal``.
    args : tuple, optional
        Any additional fixed parameters needed to
        completely specify the objective function.
    strategy : {str, callable}, optional
        The differential evolution strategy to use. Should be one of:

            - 'best1bin'
            - 'best1exp'
            - 'rand1bin'
            - 'rand1exp'
            - 'rand2bin'
            - 'rand2exp'
            - 'randtobest1bin'
            - 'randtobest1exp'
            - 'currenttobest1bin'
            - 'currenttobest1exp'
            - 'best2exp'
            - 'best2bin'

        The default is 'best1bin'. Strategies that may be
        implemented are outlined in 'Notes'.

        Alternatively the differential evolution strategy can be customized
        by providing a callable that constructs a trial vector. The callable
        must have the form
        ``strategy(candidate: int, population: np.ndarray, rng=None)``,
        where ``candidate`` is an integer specifying which entry of the
        population is being evolved, ``population`` is an array of shape
        ``(S, N)`` containing all the population members (where S is the
        total population size), and ``rng`` is the random number generator
        being used within the solver.
        ``candidate`` will be in the range ``[0, S)``.
        ``strategy`` must return a trial vector with shape ``(N,)``. The
        fitness of this trial vector is compared against the fitness of
        ``population[candidate]``.
    maxiter : int, optional
        The maximum number of generations over which the entire population is
        evolved. The maximum number of function evaluations (with no polishing)
        is: ``(maxiter + 1) * popsize * (N - N_equal)``
    popsize : int, optional
        A multiplier for setting the total population size. The population has
        ``popsize * (N - N_equal)`` individuals. This keyword is overridden if
        an initial population is supplied via the `init` keyword. When using
        ``init='sobol'`` the population size is calculated as the next power
        of 2 after ``popsize * (N - N_equal)``.
    tol : float, optional
        Relative tolerance for convergence, the solving stops when
        ``np.std(population_energies) <= atol + tol * np.abs(np.mean(population_energies))``,
        where and `atol` and `tol` are the absolute and relative tolerance
        respectively.
    mutation : float or tuple(float, float), optional
        The mutation constant. In the literature this is also known as
        differential weight, being denoted by F.
        If specified as a float it should be in the range [0, 2].
        If specified as a tuple ``(min, max)`` dithering is employed. Dithering
        randomly changes the mutation constant on a generation by generation
        basis. The mutation constant for that generation is taken from
        U[min, max). Dithering can help speed convergence significantly.
        Increasing the mutation constant increases the search radius, but will
        slow down convergence.
    recombination : float, optional
        The recombination constant, should be in the range [0, 1]. In the
        literature this is also known as the crossover probability, being
        denoted by CR. Increasing this value allows a larger number of mutants
        to progress into the next generation, but at the risk of population
        stability.

    rng : {None, int, `numpy.random.Generator`}, optional
        
        ..versionchanged:: 1.15.0
            As part of the `SPEC-007 <https://scientific-python.org/specs/spec-0007/>`_
            transition from use of `numpy.random.RandomState` to
            `numpy.random.Generator` this keyword was changed from `seed` to `rng`.
            For an interim period both keywords will continue to work (only specify
            one of them). After the interim period using the `seed` keyword will emit
            warnings. The behavior of the `seed` and `rng` keywords is outlined below.

        If `rng` is passed by keyword, types other than `numpy.random.Generator` are
        passed to `numpy.random.default_rng` to instantiate a `Generator`.
        If `rng` is already a `Generator` instance, then the provided instance is
        used.
        
        If this argument is passed by position or `seed` is passed by keyword, the
        behavior is:
        
        - 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.
        
        Specify `seed`/`rng` for repeatable minimizations.
    disp : bool, optional
        Prints the evaluated `func` at every iteration.
    callback : callable, optional
        A callable called after each iteration. Has the signature:

            ``callback(intermediate_result: OptimizeResult)``

        where ``intermediate_result`` is a keyword parameter containing an
        `OptimizeResult` with attributes ``x`` and ``fun``, the best solution
        found so far and the objective function. Note that the name
        of the parameter must be ``intermediate_result`` for the callback
        to be passed an `OptimizeResult`.

        The callback also supports a signature like:

            ``callback(x, convergence: float=val)``

        ``val`` represents the fractional value of the population convergence.
         When ``val`` is greater than ``1.0``, the function halts.

        Introspection is used to determine which of the signatures is invoked.

        Global minimization will halt if the callback raises ``StopIteration``
        or returns ``True``; any polishing is still carried out.

        .. versionchanged:: 1.12.0
            callback accepts the ``intermediate_result`` keyword.

    polish : bool, optional
        If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B`
        method is used to polish the best population member at the end, which
        can improve the minimization slightly. If a constrained problem is
        being studied then the `trust-constr` method is used instead. For large
        problems with many constraints, polishing can take a long time due to
        the Jacobian computations.
    maxfun : int, optional
        Set the maximum number of function evaluations. However, it probably
        makes more sense to set `maxiter` instead.
    init : str or array-like, optional
        Specify which type of population initialization is performed. Should be
        one of:

            - 'latinhypercube'
            - 'sobol'
            - 'halton'
            - 'random'
            - array specifying the initial population. The array should have
              shape ``(S, N)``, where S is the total population size and
              N is the number of parameters.
              `init` is clipped to `bounds` before use.

        The default is 'latinhypercube'. Latin Hypercube sampling tries to
        maximize coverage of the available parameter space.

        'sobol' and 'halton' are superior alternatives and maximize even more
        the parameter space. 'sobol' will enforce an initial population
        size which is calculated as the next power of 2 after
        ``popsize * (N - N_equal)``. 'halton' has no requirements but is a bit
        less efficient. See `scipy.stats.qmc` for more details.

        'random' initializes the population randomly - this has the drawback
        that clustering can occur, preventing the whole of parameter space
        being covered. Use of an array to specify a population could be used,
        for example, to create a tight bunch of initial guesses in an location
        where the solution is known to exist, thereby reducing time for
        convergence.
    atol : float, optional
        Absolute tolerance for convergence, the solving stops when
        ``np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))``,
        where and `atol` and `tol` are the absolute and relative tolerance
        respectively.
    updating : {'immediate', 'deferred'}, optional
        If ``'immediate'``, the best solution vector is continuously updated
        within a single generation [4]_. This can lead to faster convergence as
        trial vectors can take advantage of continuous improvements in the best
        solution.
        With ``'deferred'``, the best solution vector is updated once per
        generation. Only ``'deferred'`` is compatible with parallelization or
        vectorization, and the `workers` and `vectorized` keywords can
        over-ride this option.
    workers : int or map-like callable, optional
        If `workers` is an int the population is subdivided into `workers`
        sections and evaluated in parallel
        (uses `multiprocessing.Pool <multiprocessing>`).
        Supply `-1` to use all cores available to the Process.
        Alternatively supply a map-like callable, such as
        `multiprocessing.Pool.map` for evaluating the population in parallel.
        This evaluation is carried out as ``workers(func, iterable)``.
        This option will override the `updating` keyword to
        `updating='deferred'` if `workers != 1`.
        Requires that `func` be pickleable.
    constraints : {NonLinearConstraint, LinearConstraint, Bounds}
        Constraints on the solver, over and above those applied by the `bounds`
        kwd. Uses the approach by Lampinen.
    x0 : None or array-like, optional
        Provides an initial guess to the minimization. Once the population has
        been initialized this vector replaces the first (best) member. This
        replacement is done even if `init` is given an initial population.
        ``x0.shape == (N,)``.
    integrality : 1-D array, optional
        For each decision variable, a boolean value indicating whether the
        decision variable is constrained to integer values. The array is
        broadcast to ``(N,)``.
        If any decision variables are constrained to be integral, they will not
        be changed during polishing.
        Only integer values lying between the lower and upper bounds are used.
        If there are no integer values lying between the bounds then a
        `ValueError` is raised.
    vectorized : bool, optional
        If ``vectorized is True``, `func` is sent an `x` array with
        ``x.shape == (N, S)``, and is expected to return an array of shape
        ``(S,)``, where `S` is the number of solution vectors to be calculated.
        If constraints are applied, each of the functions used to construct
        a `Constraint` object should accept an `x` array with
        ``x.shape == (N, S)``, and return an array of shape ``(M, S)``, where
        `M` is the number of constraint components.
        This option is an alternative to the parallelization offered by
        `workers`, and may help in optimization speed. This keyword is
        ignored if ``workers != 1``.
        This option will override the `updating` keyword to
        ``updating='deferred'``.
    _best1_randtobest1_currenttobest1_best2_rand2_rand1)r   randtobest1bincurrenttobest1binbest2binrand2binrand1bin)best1exprand1exprandtobest1expcurrenttobest1expbest2exprand2expzThe population initialization method must be one of 'latinhypercube' or 'random', or an array of shape (S, N) where N is the number of parameters and S>5r   r   r   r   r   r   r   NFTr   r   r   r   r    c          	         t          |          rnc|| j        v r!t          | | j        |                   | _        n9|| j        v r!t          | | j        |                   | _        nt          d          || _        t          |d          | _        || _	        |dv r|| _
        || _        |dk    r)|dk    r#t          j        dt          d           d	| _
        |r%|dk    rt          j        d
d           dx| _        }|r)|dk    r#t          j        dt          d           d	| _
        |rd }|}t          |          | _        ||c| _        | _        || _        t)          j        t)          j        |                    rTt)          j        t)          j        |          dk              s*t)          j        t)          j        |          dk               rt          d          d | _        t5          |d          rAt7          |          dk    r.|d         |d         g| _        | j                                         |	| _        t=          ||          | _        || _         tC          |tD                    rQt)          j        tG          |j$        |j%        t7          |j$                            tL                    j'        | _(        n t)          j        |d          j'        | _(        t)          j)        | j(        d          dk    s+t)          j        t)          j        | j(                            st          d          |d}|| _*        |t(          j+        }|| _,        d| j(        d         | j(        d         z   z  | _-        t)          j.        | j(        d         | j(        d         z
            | _/        t)          j0        d          5  d| j/        z  | _1        d| j1        t)          j        | j1                   <   d d d            n# 1 swxY w Y   t)          j)        | j(        d          | _2        tg          |
          | _4        t)          j        |          r&t)          j5        || j2                  }t)          j6        |tn                    }t)          j8        | j(                  \  }}t)          j9        |          }t)          j:        |          }||         ||         k                                    st          d          t)          j;        ||         dz
  t(          j+                  }t)          j;        ||         dz   t(          j+                   }|| _<        || j(        d| j<        f<   || j(        d| j<        f<   nd| _<        | j(        d         | j(        d         k    }t)          j=        |          }t}          d|t}          d| j2        |z
            z            | _?        | j?        | j2        f| _@        d| _A        tC          |t                    r|dk    r| C                                 n|dk    rlt          dt)          j9        t)          jE        | j?                            z            }|| _?        | j?        | j2        f| _@        | F                    d           na|dk    r| F                    d           nD|dk    r| G                                 n)t          | jH                  | I                    |           |_| J                    t)          j6        |                    }|dk    |d k     z                                  rt          d!          || jK        d<   || _L        g | _M        t5          |d"          r3|D ]/} | jM        N                    t          | | jP                             0nt          || jP                  g| _M        t)          jQ        d# | jM        D                       | _R        t)          jS        | j?        df          | _T        t)          jU        | j?        tn                    | _V        t)          jW        | j?                  | _X        || _Y        d S )$Nz'Please select a valid mutation strategyr   )r   deferredr   r   zhdifferential_evolution: the 'workers' keyword has overridden updating='immediate' to updating='deferred'   
stacklevelrO   zPdifferential_evolution: the 'workers' keyword overrides the 'vectorized' keywordFzkdifferential_evolution: the 'vectorized' keyword has overridden updating='immediate' to updating='deferred'c                 F    t          j         | |j                            S N)np
atleast_1dT)r7   xs     r;   maplike_for_vectorized_funczIDifferentialEvolutionSolver.__init__.<locals>.maplike_for_vectorized_func+  s     }TT!#YY///    r   zThe mutation constant must be a float in U[0, 2), or specified as a tuple(min, max) where min < max and min, max are in U[0, 2).__iter__dtypefloatz^bounds should be a sequence containing finite real valued (min, max) pairs for each value in xr   r   ignore)dividezlOne of the integrality constraints does not have any possible integer values between the lower/upper bounds.   r   sobol)
qmc_enginehaltonrandom      ?        z3Some entries in x0 lay outside the specified bounds__len__c                     g | ]	}|j         
S r   )
num_constr).0cs     r;   
<listcomp>z8DifferentialEvolutionSolver.__init__.<locals>.<listcomp>  s    ===aQ\===rZ   )Zcallable	_binomialgetattrmutation_func_exponential
ValueErrorr%   r   r-   r,   	_updatingr"   warningswarnUserWarningr   _mapwrapperr(   r0   scalerU   allisfiniteanyarrayditherhasattrlensortcross_over_probabilityr	   r7   r$   
isinstancer   r   lbubr^   rW   limitssizer&   infmaxfun(_DifferentialEvolutionSolver__scale_arg1fabs(_DifferentialEvolutionSolver__scale_arg2errstate._DifferentialEvolutionSolver__recip_scale_arg2parameter_countr   random_number_generatorbroadcast_toasarrayboolcopyceilfloor	nextafterr!   count_nonzeromaxnum_population_memberspopulation_shape_nfevstrinit_population_lhsintlog2init_population_qmcinit_population_random,_DifferentialEvolutionSolver__init_error_msginit_population_array_unscale_parameters
populationr3   _wrapped_constraintsappend_ConstraintWrapperrX   sumtotal_constraintszerosconstraint_violationonesfeasiblearange_random_population_indexr.   )!selfr7   r8   r$   r%   r&   r'   r(   r)   r*   r+   r   r-   r.   r,   r/   r0   r1   r2   r3   r4   r!   r"   rY   r   r   nlbnubebeb_countn_s	x0_scaledrl   s!                                    r;   __init__z$DifferentialEvolutionSolver.__init__  s    H 	H''!(t~h/G!H!HD***!(t/@/J!K!KDFGGG &x1IJJ 000%DN$ a<<H33M 12=!M M M M (DN 	1'Q,,M @LMO O O O+00DOj 	((k11M ()4D D D D (DN  	20 0 0
 2G%g.. "4$) 
r{8,,-- 	Nrx))Q.//	Nrx))A-..	N  M N N N 8Z(( 	S]]Q->->#A;4DKK&3# %T400		
 ff%% 	<(#4VY5;Y58^^$E $E */0 0 0 12 KK
 (6999;DKGDK##q((r{4;//00 ) % & & & ?G>VF  4;q>DKN#BCGDKNT[^$CDD[))) 	O 	O '($*;&;D#MND#R[1H%I%I$IJ	O 	O 	O 	O 	O 	O 	O 	O 	O 	O 	O 	O 	O 	O 	O  "wt{A66'9#'>'>$ 6+ 	%/$ K *[$77K WT[))FBB"B{Or+6;;== = ! "< = = = ,r+4bf==C,r+4rvg>>C*D/2DK4++,/2DK4++,,$D [^t{1~-#B'' '*c!T1H<==='
 '
# "&!<!%!5!7 
dC   	-'''((****!rwrwt/J'K'KLLLMM.1+)-)D)-)=)?%((G(<<<<!!((H(====!!++---- !6777&&t,,,> 00B@@ISY_5::<<  I   "+DOA '$&!;	** 
	 !  )00&q$&11    #;77)D% "$==4#<==="
 "
 %'Hd.I1-M$N$N! ;TBB )+	$2M(N(N%			s   2PP	P	c                    | j         }d| j        z  }||                    | j                  z  t	          j        dd| j        d          ddt          j        f         z   }t	          j        |          | _        t          | j
                  D ]?}|                    t          | j                            }|||f         | j        dd|f<   @t	          j        | j        t          j                  | _        d| _        dS )z
        Initializes the population with Latin Hypercube Sampling.
        Latin Hypercube Sampling ensures that each parameter is uniformly
        sampled over its range.
        rf   r   rg   F)endpointNr   )r   r   uniformr   rU   linspacenewaxis
zeros_liker   ranger   permutationfullr   population_energiesr   )r   r+   segsizesamplesjorders         r;   r   z/DifferentialEvolutionSolver.init_population_lhs  s    * 33 S[[d.C[DDD [R)D*/1 1 112BJ@@ -00 t+,, 	6 	6AOOE$*E$F$FGGE$+E1H$5DOAAAqD!! $&74+F+-6$3 $3  


rZ   c                    ddl m} | j        }|dk    r|                    | j        |          }nZ|dk    r|                    | j        |          }n7|dk    r|                    | j        |          }nt          | j                  |	                    | j
                  | _        t          j        | j
        t          j                  | _        d| _        dS )	aR  Initializes the population with a QMC method.

        QMC methods ensures that each parameter is uniformly
        sampled over its range.

        Parameters
        ----------
        qmc_engine : str
            The QMC method to use for initialization. Can be one of
            ``latinhypercube``, ``sobol`` or ``halton``.

        r   )qmcr   )dr   rb   rd   )nN)scipy.statsr   r   LatinHypercuber   SobolHaltonrs   r   re   r   r   rU   r   r   r   r   )r   rc   r   r+   samplers        r;   r   z/DifferentialEvolutionSolver.init_population_qmc  s     	$#####* )))((4+?c(JJGG7""ii$"6SiAAGG8##jj4#7cjBBGGT2333!..4+F.GG $&74+F+-6$3 $3  


rZ   c                     | j         }|                    | j                  | _        t	          j        | j        t          j                  | _        d| _	        dS )z
        Initializes the population at random. This type of initialization
        can possess clustering, Latin Hypercube sampling is generally better.
        r   r   N)
r   r   r   r   rU   r   r   r   r   r   )r   r+   s     r;   r   z2DifferentialEvolutionSolver.init_population_random'  sQ    
 *++4+@+AA $&74+F+-6$3 $3  


rZ   c                    t          j        |t           j                  }t          j        |d          dk     s.|j        d         | j        k    st          |j                  dk    rt          d          t          j        | 	                    |          dd          | _
        t          j        | j
        d          | _        | j        | j        f| _        t          j        | j        t           j                  | _        d| _        dS )ah  
        Initializes the population with a user specified population.

        Parameters
        ----------
        init : np.ndarray
            Array specifying subset of the initial population. The array should
            have shape (S, N), where N is the number of parameters.
            The population is clipped to the lower and upper bounds.
        r\   r   ra   r   rP   zEThe population supplied needs to have shape (S, len(x)), where S > 4.N)rU   r   float64r   shaper   r   rs   clipr   r   r   r   r   r   r   r   )r   r/   popns      r;   r   z1DifferentialEvolutionSolver.init_population_array6  s     z$bj111GD!q  
1!555DJ1$$ : ; ; ; '$":":4"@"@!QGG&(gdoq&A&A#!%!<!%!5!7 $&74+F+-6$3 $3  


rZ   c                 B    |                      | j        d                   S )z3
        The best solution from the solver
        r   )_scale_parametersr   r   s    r;   rX   zDifferentialEvolutionSolver.xY  s    
 %%doa&8999rZ   c                 
   t          j        t          j        | j                            rt           j        S t          j        | j                  t          j        t          j        | j                            t          z   z  S )zb
        The standard deviation of the population energies divided by their
        mean.
        )	rU   r|   isinfr   r   stdabsmean_MACHEPSr   s    r;   convergencez'DifferentialEvolutionSolver.convergence`  se     6"(434455 	6Mt/00 899::XEG 	HrZ   c                    t          j        t          j        | j                            rdS t          j        | j                  | j        | j        t          j        t          j        | j                            z  z   k    S )z:
        Return True if the solver has converged.
        F)	rU   r|   r   r   r   r0   r(   r   r   r   s    r;   	convergedz%DifferentialEvolutionSolver.convergedk  sp     6"(434455 	5t/00	26"'$*B"C"CDDDEE 	FrZ   c                     d\  }}t           d         }t          j        t          j         j                            rm                      j                  \   _         _         	                     j         j                            j         j        <    
                                 t          d j        dz             D ]}	 t                      nC# t          $ r6 d} j         j        k    rt           d         }n j         j        k    rd}Y  nw xY w j        r t%          d| d j        d	                      j        ro j         j        t,          z   z  }                     |d
          }||_        	 t1                               |                    }n# t          $ r d}Y nw xY w|rd}|s                                 r nt           d         }d}                     |||           j        rt          j         j                  st          j         j                  r2 j         j        }}j        |         |d	|f<   j        |         |d|f<   d} j        rPd}                      j                  }	t          j        |	dk              rtC          j"        dtF          d            j        rt%          d| d           tI           fdt          j%        j                  | j        j&         j'                  }
 xj        |
j(        z  c_         j        _(        |
j)        j)        k     r|
j*        rt          j        |
j         j        d         k              r}t          j         j        d	         |
j        k              rU|
j)        _)        |
j        _        |
j+        _+        |
j)         j        d	<    ,                    |
j                   j        d	<    j        rufd j        D             _-        t          j.        t          j/        j-                            _0        j0        _1        j1        d	k    rd_*        dj1         _2        S )a  
        Runs the DifferentialEvolutionSolver.

        Returns
        -------
        res : OptimizeResult
            The optimization result represented as a `OptimizeResult` object.
            Important attributes are: ``x`` the solution array, ``success`` a
            Boolean flag indicating if the optimizer exited successfully,
            ``message`` which describes the cause of the termination,
            ``population`` the solution vectors present in the population, and
            ``population_energies`` the value of the objective function for
            each entry in ``population``.
            See `OptimizeResult` for a description of other attributes. If
            `polish` was employed, and a lower minimum was obtained by the
            polishing, then OptimizeResult also contains the ``jac`` attribute.
            If the eventual solution does not satisfy the applied constraints
            ``success`` will be `False`.
        )r   Fsuccessr   Tmaxfevz8Maximum number of function evaluations has been reached.zdifferential_evolution step z: f(x)= r   zin progress)nitmessagez&callback function requested stop earlyr&   )r   r   warning_flagzL-BFGS-Bztrust-constrrg   zdifferential evolution didn't find a solution satisfying the constraints, attempting to polish from the least infeasible solutionrP   rQ   zPolishing solution with ''c                     t                              j        t          j        |                               d         S )Nr   )listrx   r7   rU   
atleast_2d)rX   r   s    r;   <lambda>z3DifferentialEvolutionSolver.solve.<locals>.<lambda>  s5     $T%5%5diqAQAQ%R%R S STU V rZ   )methodr8   r3   c                 D    g | ]}|                     j                  S r   	violationrX   )rk   rl   	DE_results     r;   rm   z5DifferentialEvolutionSolver.solve.<locals>.<listcomp>  s=      @  @  @ ! !"IK 8 8  @  @  @rZ   Fz7The solution does not satisfy the constraints, MAXCV = )3r   rU   rz   r   r   #_calculate_population_feasibilitiesr   r   r   _calculate_population_energies_promote_lowest_energyr   r&   nextStopIterationr   r   r.   printr-   r(   r   r   _resultr   r   r,   r!   r|   r   rX   r   _constraint_violation_fnru   rv   rw   r   r   rW   r3   nfevfunr   jacr   constrr   concatenateconstr_violationmaxcvr   )r   r   r   status_messagerl   resr   r!   polish_methodr  resultr   s   `          @r;   r6   z!DifferentialEvolutionSolver.solvev  s
   ( %\(3 6"(434455 		*88II 5DM44
 33ODM24 4 $T]3 ''))) DL1,-- $	  $	 C	T



    #:++%4X%>NNZ4;..';N y  8S 8 82158 8    } 
NH 08 ;<llsMlBB"#(#'c(:(:#;#;LL$ ( ( (#'LLL(   N%MN  t~~//  -Y7NLLL^, ! 
 
	 ; -	Hrvd&677 -	Hvd&'' B '+k43C)2[)Aq+~&)2[)Aq+~&&M( 	= .#'#@#@#M#M 6*R/00 =M #8 #.!	= = = =
 y DB-BBBCCC W W W W gik22%2%)[]*.*:< < <F JJ&+%JJ!ZIN
 
Y]**N +F68t{1~566 + F4;q>VX566 + !'
	$h	 &
	.4j(+%)%=%=fh%G%G"$ 
	P @  @  @  @%)%> @  @  @I)+y/00*2 *2I&'8IO""$)	!&O=F_&O &O	! s$   	C<DD "F##F21F2c                    |                     dd           }|                     dd           }|                     dd          }t          | j        | j        d         | j        |||du|                     | j                  | j                  | j        rffd| j        D             _        t          j
        t          j        j                            _        j        _        j        dk    rd_        S )	Nr   r   r   Fr   T)rX   r   r   r   r   r   r   r   c                 D    g | ]}|                     j                  S r   r   )rk   rl   r  s     r;   rm   z7DifferentialEvolutionSolver._result.<locals>.<listcomp>  s=     A A A!" [[22 A A ArZ   )getr   rX   r   r   r   r   r   r   rU   r   r   r  r  r   )r   kwdsr   r   r   r  s        @r;   r   z#DifferentialEvolutionSolver._result  s   hhud##((9d++xx66f(+!---do>> $ 8	
 	
 	
 $ 	'A A A A&*&?A A AFM&(fR^FM-J-J&K&KF#!2FL|a!&rZ   c                 n   t          j        |d          }t          || j        | j        z
            }t          j        |t           j                  }|                     |          }	 t          | 	                    | j
        |d|                             }t          j        |          }n)# t          t          f$ r}t          d          |d}~ww xY w|j        |k    r%| j        rt          d          t          d          ||d|<   | j        r| xj        dz  c_        n| xj        |z  c_        |S )aw  
        Calculate the energies of a population.

        Parameters
        ----------
        population : ndarray
            An array of parameter vectors normalised to [0, 1] using lower
            and upper limits. Has shape ``(np.size(population, 0), N)``.

        Returns
        -------
        energies : ndarray
            An array of energies corresponding to each population member. If
            maxfun will be exceeded during this call, then the number of
            function evaluations will be reduced and energies will be
            right-padded with np.inf. Has shape ``(np.size(population, 0),)``
        r   zzThe map-like callable must be of the form f(func, iterable), returning a sequence of numbers the same length as 'iterable'NzcThe vectorized function must return an array of shape (S,) when given an array of shape (len(x), S)z)func(x, *args) must return a scalar valuer   )rU   r   minr   r   r   r   r   r   rx   r7   squeeze	TypeErrorrs   RuntimeErrorr"   )r   r   num_membersSenergiesparameters_popcalc_energieses           r;   r   z:DifferentialEvolutionSolver._calculate_population_energies  s[   $ gj!,, T[4:5667;////
;;	   N1Q3,?@@ M J}55MM:& 	 	 	 P  	 "" <" $; < < < JKKK%1? 	JJ!OJJJJJ!OJJs   (AB- -C>CCc                    t          j        | j                  }|| j                 }|j        r(t          j        | j        |                   }||         }n-t          j        t          j        | j        d                    }| j        |dg         | j        d|g<   | j	        |dgd d f         | j	        d|gd d f<   | j        |dg         | j        d|g<   | j        |dgd d f         | j        d|gd d f<   d S )Nr   axisr   )
rU   r   r   r   r   argminr   r   r   r   )r   idxfeasible_solutionsidx_tls        r;   r   z2DifferentialEvolutionSolver._promote_lowest_energyU  s    i344 /" 	EId67IJKKE"5)AA 	"&!:CCCDDA+/+CQF+K !Q(%)_aVQQQY%?A	" $q!f 5q!f!1a&!!!), 	!1a&!!!),,,rZ   c                    t          j        |          | j        z  }t          j        || j        f          }d}| j        D ]}|                    |j                  j        }|j        d         |j	        k    s|dk    r |j        d         |k    rt          d          t          j        |||j	        f          }||dd|||j	        z   f<   ||j	        z  }|S )a\  
        Calculates total constraint violation for all the constraints, for a
        set of solutions.

        Parameters
        ----------
        x : ndarray
            Solution vector(s). Has shape (S, N), or (N,), where S is the
            number of solutions to investigate and N is the number of
            parameters.

        Returns
        -------
        cv : ndarray
            Total violation of constraints. Has shape ``(S, M)``, where M is
            the total number of constraint components (which is not necessarily
            equal to len(self._wrapped_constraints)).
        r   r   M  An array returned from a Constraint has the wrong shape. If `vectorized is False` the Constraint should return an array of shape (M,). If `vectorized is True` then the Constraint must return an array of shape (M, S), where S is the number of solution vectors and M is the number of constraint components in a given Constraint object.N)rU   r   r   r   r   r   r   rW   r   rj   r  reshape)r   rX   r  _outoffsetconrl   s          r;   r   z4DifferentialEvolutionSolver._constraint_violation_fni  s    * GAJJ$..xD2344, 	% 	%C ac""$A wr{cn,,Q171:??" $9 : : : 
1q#.122A67DF6CN2223cn$FFrZ   c                     t          j        |d          } j        s0t          j        |t                    t          j        |df          fS                      |          } j        r(t          j         	                    |                    }n,t          j         fd|D                       }|dddf         }t          j
        |d          dk     }||fS )a  
        Calculate the feasibilities of a population.

        Parameters
        ----------
        population : ndarray
            An array of parameter vectors normalised to [0, 1] using lower
            and upper limits. Has shape ``(np.size(population, 0), N)``.

        Returns
        -------
        feasible, constraint_violation : ndarray, ndarray
            Boolean array of feasibility for each population member, and an
            array of the constraint violation for each population member.
            constraint_violation has shape ``(np.size(population, 0), M)``,
            where M is the number of constraints.
        r   r   c                 :    g | ]}                     |          S r   )r   )rk   rX   r   s     r;   rm   zSDifferentialEvolutionSolver._calculate_population_feasibilities.<locals>.<listcomp>  s=     -F -F -F12 .2-J-J1-M-M -F -F -FrZ   Nr  )rU   r   r   r   r   r   r   r"   r}   r   r   )r   r   r  r  r   r   s   `     r;   r   z?DifferentialEvolutionSolver._calculate_population_feasibilities  s   $ gj!,,( 	J7;--rxa8H/I/III //
;;? 	>#%8--n==$ $  
 $&8 -F -F -F -F6D-F -F -F $G $G  $81#= V0q999A=>---rZ   c                     | S rT   r   r   s    r;   r[   z$DifferentialEvolutionSolver.__iter__      rZ   c                     | S rT   r   r   s    r;   	__enter__z%DifferentialEvolutionSolver.__enter__  r(  rZ   c                       | j         j        | S rT   )rx   __exit__)r   r$   s     r;   r,  z$DifferentialEvolutionSolver.__exit__  s    (t($//rZ   c                 ^    |r|r||k    S |r|sdS |s||k                                     rdS dS )a  
        Trial is accepted if:
        * it satisfies all constraints and provides a lower or equal objective
          function value, while both the compared solutions are feasible
        - or -
        * it is feasible while the original solution is infeasible,
        - or -
        * it is infeasible, but provides a lower or equal constraint violation
          for all constraint functions.

        This test corresponds to section III of Lampinen [1]_.

        Parameters
        ----------
        energy_trial : float
            Energy of the trial solution
        feasible_trial : float
            Feasibility of trial solution
        cv_trial : array-like
            Excess constraint violation for the trial solution
        energy_orig : float
            Energy of the original solution
        feasible_orig : float
            Feasibility of original solution
        cv_orig : array-like
            Excess constraint violation for the original solution

        Returns
        -------
        accepted : bool

        TF)rz   )r   energy_trialfeasible_trialcv_trialenergy_origfeasible_origcv_origs          r;   _accept_trialz)DifferentialEvolutionSolver._accept_trial  s_    D  	^ 	;.. 	M 	4 	X%8$=$=$?$? 	 4urZ   c           
      	    t          j        t          j         j                            rm                      j                  \   _         _                              j         j                            j         j        <    	                                  j
        6 j                             j
        d          j
        d                    _         j        dk    rt           j                  D ]} j         j        k    rt&                               |          }                     |                                |          } j        rc                     |          }d}t           j        }t          j        |          dk    s'd}                     |          } xj        dz  c_        n<d}t          j        dg          }                     |          } xj        dz  c_                             ||| j        |          j        |          j        |                   r| j        |<   t          j        |           j        |<   | j        |<   | j        |<                        ||| j        d          j        d          j        d                   r 	                                 Őn j        dk    r j         j        k    rt&                               t          j          j                            }                     |                                |          \  }}t          j!         j        t           j                  }                     ||                   ||<    fd	tE          ||| j         j         j                  D             }	t          j#        |	          }	t          j$        |	ddt           j%        f         | j                   _        t          j$        |	| j                   _        t          j$        |	| j                   _        t          j$        |	ddt           j%        f         | j                   _         	                                  j&         j        d         fS )
z
        Evolve the population by a single generation

        Returns
        -------
        x : ndarray
            The best solution from the solver.
        fun : float
            Value of objective function obtained from the best solution.
        Nr   r   r   FTrg   rO   c                 $    g | ]} j         | S r   )r4  )rk   valr   s     r;   rm   z8DifferentialEvolutionSolver.__next__.<locals>.<listcomp>m  s6     B B B%4%s+ B B BrZ   )'rU   rz   r   r   r   r   r   r   r   r   r~   r   r   ry   rt   r   r   r   r   r   _mutate_ensure_constraintr   r   r   r   r   r7   r   r4  r  _mutate_manyr   r   zipr}   wherer   rX   )
r   	candidatetrial
parameterscvr   energy	trial_poptrial_energieslocs
   `         r;   __next__z$DifferentialEvolutionSolver.__next__  s    6"(434455 
	*88II 5DM44 33ODM24 4 $T]3 '')));"5==dk!n>Bk!nN NDJ >[(("4#>?? -6 -6	:++'' Y// ''... "33E::
 , $66zBBB$HVF6"::>>#'!%:!6!6

a

#Ht,,B!YYz22FJJ!OJJ %%fh&*&>y&I&*mI&>&*&?	&JL L 6 27DOI.:<*V:L:LD,Y7/7DM),;=D-i8 ))&(B*.*B1*E*.-*:*.*CA*FH H 6 33555[-6^ ^z))zT[((## ))	$566 I
 ##I...  CCINNLHbWT%@"&IIN (,'J'J(#(% (%N8$B B B B~xT5M}d&?A AB B BC (3--C hs111bj='9'0'+8 8DO (*x0>040H(J (JD$ HS%-%)]4 4DM )+QQQ
]1C13151J)L )LD% '')))vt/222rZ   c                     | j         |dz
  | j        z  z   }t          j        | j                  r<t          j        | j        |j                  }t          j        ||                   ||<   |S )z2Scale from a number between 0 and 1 to parameters.r   )r   r   rU   r   r!   r   r   round)r   r>  scaledis       r;   r   z-DifferentialEvolutionSolver._scale_parameters  se     "eckT5F%FFD,-- 	, 0&,??A++F1IrZ   c                 ,    || j         z
  | j        z  dz   S )z2Scale from parameters to a number between 0 and 1.r   )r   r   )r   r?  s     r;   r   z/DifferentialEvolutionSolver._unscale_parameters  s    T..$2IICOOrZ   c                     t          j        |dk    |dk               }t          j        |          x}r | j                            |          ||<   dS dS )z0Make sure the parameters lie between the limits.r   r   r   N)rU   
bitwise_orr   r   r   )r   r>  maskoobs       r;   r9  z.DifferentialEvolutionSolver._ensure_constraint  sa    }UQY	22"4(((3 	I6>>C>HHE$KKK	I 	IrZ   c                      j         d}                      j                  t          t	          j        |                    s9                     |          }|j         j        fk    rt          |          nW|j        d         }t	          j	         fd|D             t                    }|j        | j        fk    rt          |                               |          S )Nzqstrategy must have signature f(candidate: int, population: np.ndarray, rng=None) returning an array of shape (N,)r+   r   c                 @    g | ]}                     |           S )rP  )r%   )rk   rl   _populationr+   r   s     r;   rm   z>DifferentialEvolutionSolver._mutate_custom.<locals>.<listcomp>  s+    KKKAq+377KKKrZ   r\   )r   r   r   r   rU   r   r%   r   r  r}   r^   r   )r   r=  msgr>  r  rR  r+   s   `    @@r;   _mutate_customz*DifferentialEvolutionSolver._mutate_custom  s   *# 	
 ,,T_==28I&&'' 	(MM)[cMBBE{t3555"3''' 6 "AHKKKKKKKKK  E {q$"6777"3'''''...rZ   c                 r     j         }t          |          }t           j                  r                     |          S t          j         j        |                   }t          j         fd|D                       } j        dv r 	                    ||          }n 	                    |          }t          | j        |          }|                    | j        f          }| j        k     } j         j        v r9t          j        |          }	d||	||	         f<   t          j        |||          }|S  j         j        v rnd|d<   t%          |          D ]W}
d}	||
         }|	 j        k     r@||
|	f         r6||
|f         ||
|f<   |dz    j        z  }|	dz  }	|	 j        k     r
||
|	f         6X|S dS )	z2Create trial vectors based on a mutation strategy.c                 <    g | ]}                     |d           S )ra   )_select_samples)rk   rl   r   s     r;   rm   z<DifferentialEvolutionSolver._mutate_many.<locals>.<listcomp>  s)    KKK1D00A66KKKrZ   rK   rD   r   T).r   r   r   N)r   r   rn   r%   rT  rU   r   r   r}   rq   r
   r   r   r   ro   r   r<  rr   r   )r   
candidatesr+   r  r>  r   bprime
fill_point
crossoversrI  r   	init_fills   `           r;   r:  z(DifferentialEvolutionSolver._mutate_many  s   *
OODM"" 	3&&z222
344(KKKK
KKKLL=FFF''
G<<FF''00F!#t';!DDD
[[q$*>&?[@@
$"==
=DN**
 	!A+/Jq*Q-'(HZ77EL]d///!%Jv1XX  &qM	4///Jq!t4D/*0I*>E!Y,'!*Q$2F FIFA 4///Jq!t4D/
 L 0/rZ   c                    | j         }t          | j                  r|                     |          S t	          || j                  }|                     |d          }t          j        | j	        |                   }| j        dv r| 
                    ||          }n| 
                    |          }|                    | j                  }|| j        k     }| j        | j        v rd||<   t          j        |||          }|S | j        | j        v rLd}d|d<   || j        k     r8||         r0||         ||<   |dz   | j        z  }|dz  }|| j        k     r||         0|S dS )z3Create a trial vector based on a mutation strategy.ra   rX  r   Tr   r   N)r   rn   r%   rT  r
   r   rW  rU   r   r   rq   r   r   ro   r<  rr   )	r   r=  r+   r[  r   r>  rZ  r\  rI  s	            r;   r8  z#DifferentialEvolutionSolver._mutate  s   *DM"" 	2&&y111!#t';<<
&&y!44	233=FFF''	7;;FF''00F[[d&:[;;
$"==
=DN**
 &*Jz"HZ77EL]d///A JqMd***z!}*$*:$6j!(1n0DD
Q d***z!}*
 L 0/rZ   c                     |dddf         j         \  }}| j        d         | j        | j        |         | j        |         z
  z  z   S )zbest1bin, best1exp.NrP   r   rW   r   ry   )r   r   r0r1s       r;   r=   z"DifferentialEvolutionSolver._best1  sP    
 bqb!#B"TZ$tr'::&< < 	=rZ   c                     |dddf         j         \  }}}| j        |         | j        | j        |         | j        |         z
  z  z   S )zrand1bin, rand1exp.N   r`  )r   r   ra  rb  r2s        r;   rB   z"DifferentialEvolutionSolver._rand1  sP    S"1"W%'
B#dj$tr'::'< < 	=rZ   c                     |dddf         j         \  }}}t          j        | j        |                   }|| j        | j        d         |z
  z  z  }|| j        | j        |         | j        |         z
  z  z  }|S )zrandtobest1bin, randtobest1exp.Nrd  r   )rW   rU   r   r   ry   )r   r   ra  rb  re  rZ  s         r;   r>   z(DifferentialEvolutionSolver._randtobest1  s    S"1"W%'
B,--$* 2V ;<<$* 3 $ 3!4 5 	5rZ   c                     |dddf         j         \  }}| j        |         | j        | j        d         | j        |         z
  | j        |         z   | j        |         z
  z  z   }|S )z$currenttobest1bin, currenttobest1exp.NrP   r   r`  )r   r=  r   ra  rb  rZ  s         r;   r?   z+DifferentialEvolutionSolver._currenttobest1  sp    bqb!#B/),tz?1%	(BB?2&')-)<=0> > rZ   c                     |dddf         j         \  }}}}| j        d         | j        | j        |         | j        |         z   | j        |         z
  | j        |         z
  z  z   }|S )zbest2bin, best2exp.N   r   r`  )r   r   ra  rb  re  r3rZ  s          r;   r@   z"DifferentialEvolutionSolver._best2  st     bqb)+BB/!$tz?2&)<<?2&')-)<=(> > rZ   c                     |dddf         j         \  }}}}}| j        |         | j        | j        |         | j        |         z   | j        |         z
  | j        |         z
  z  z   }|S )zrand2bin, rand2exp.Nra   r`  )r   r   ra  rb  re  rj  r4rZ  s           r;   rA   z"DifferentialEvolutionSolver._rand2'  sw    $S"1"W-/BB/"%
?2&)<<?2&')-)<=)> > rZ   c                     | j                             | j                   | j        d|dz            }|||k             d|         S )z
        obtain random integers from range(self.num_population_members),
        without replacement. You can't have the original candidate either.
        Nr   )r   shuffler   )r   r=  number_samplesidxss       r;   rW  z+DifferentialEvolutionSolver._select_samples0  sO    
 	$,,T-JKKK,-@nq.@-@ADI%&77rZ   )*__name__
__module____qualname____doc__ro   rr   r   rU   r   r   r   r   r   r   propertyrX   r   r   r6   r   r   r   r   r   r[   r*  r,  r4  rE  r   r   r9  rT  r:  r8  r=   rB   r>   r?   r@   rA   rW  r   rZ   r;   r5   r5     s       k k\ &#1&7%%%' 'I !) (&4): ( (* *LM +-$dBHCTE$&Qt`
 EI!` ` ` ` `D$ $ $L" " "H  ! ! !F : : X: H H XH	F 	F 	FM M M^  25 5 5n. . .(9 9 9v+. +. +.Z    0 0 0+ + +Z{3 {3 {3z  P P PI I I/ / /.' ' 'R$ $ $L= = == = =        8 8 8 8 8rZ   r5   c                   $    e Zd ZdZd Zd Zd ZdS )r   a  Object to wrap/evaluate user defined constraints.

    Very similar in practice to `PreparedConstraint`, except that no evaluation
    of jac/hess is performed (explicit or implicit).

    If created successfully, it will contain the attributes listed below.

    Parameters
    ----------
    constraint : {`NonlinearConstraint`, `LinearConstraint`, `Bounds`}
        Constraint to check and prepare.
    x0 : array_like
        Initial vector of independent variables, shape (N,)

    Attributes
    ----------
    fun : callable
        Function defining the constraint wrapped by one of the convenience
        classes.
    bounds : 2-tuple
        Contains lower and upper bounds for the constraints --- lb and ub.
        These are converted to ndarray and have a size equal to the number of
        the constraints.

    Notes
    -----
    _ConstraintWrapper.fun and _ConstraintWrapper.violation can get sent
    arrays of shape (N, S) or (N,), where S is the number of vectors of shape
    (N,) to consider constraints for.
    c                 d   | _         t          t                    rfd}nCt          t                    rfd}n(t          t                    rd }nt          d          || _        t          j        j	        t                    }t          j        j        t                    }t          j        |          } ||          }|j        x| _        }|j        | _        |j        dk    rt          j        ||          }|j        dk    rt          j        ||          }||f| _        d S )Nc                 z    t          j        |           } t          j                            |                     S rT   )rU   r   rV   r   )rX   
constraints    r;   r   z(_ConstraintWrapper.__init__.<locals>.fun]  s,    JqMM}Z^^A%6%6777rZ   c                    t          j                  rj        }nt          j        j                  }|                    |           }| j        dk    r)|j        dk    rt          j        |          d d df         }|S )Nr   rP   r   )r   ArU   r   dotndimr   )rX   r{  r  ry  s      r;   r   z(_ConstraintWrapper.__init__.<locals>.funa  sv    JL)) 4"AAjl33AeeAhh 6Q;;38q== *S//!!!Q$/C
rZ   c                 *    t          j        |           S rT   )rU   r   )rX   s    r;   r   z(_ConstraintWrapper.__init__.<locals>.funt  s    z!}}$rZ   z*`constraint` of an unknown type is passed.r\   r   )ry  r   r   r   r   rs   r   rU   r   r   r^   r   r   rj   r   r}  resizer8   )r   ry  r4   r   r   r   f0ms    `      r;   r   z_ConstraintWrapper.__init__Y  sX   $j"566 	K8 8 8 8 8 8 
$455 	K     $ 
F++ 	K% % % % IJJJZ
U333Z
U333Z^^ SWW g%!!w7a<<2q!!B7a<<2q!!B2hrZ   c                 P    t          j        |                     |                    S rT   )rU   rV   r   )r   rX   s     r;   __call__z_ConstraintWrapper.__call__  s    }TXXa[[)))rZ   c                 P   |                      t          j        |                    }	 t          j        | j        d         |j        z
  d          }t          j        |j        | j        d         z
  d          }n"# t          $ r}t          d          |d}~ww xY w||z   j        }|S )a  How much the constraint is exceeded by.

        Parameters
        ----------
        x : array-like
            Vector of independent variables, (N, S), where N is number of
            parameters and S is the number of solutions to be investigated.

        Returns
        -------
        excess : array-like
            How much the constraint is exceeded by, for each of the
            constraints specified by `_ConstraintWrapper.fun`.
            Has shape (M, S) where M is the number of constraint components.
        r   r   r   N)r   rU   r   maximumr8   rW   rs   r  )r   rX   ev	excess_lb	excess_ubr  vs          r;   r   z_ConstraintWrapper.violation  s    " XXbjmm$$	=
4;q>BD#8!<<I
24$+a.#8!<<II 		= 		= 		=  5 6 6 <==		= "%s   AA: :
BBBN)rq  rr  rs  rt  r   r  r   r   rZ   r;   r   r   :  sL         <1 1 1f* * *" " " " "rZ   r   )r   r   r   r   r   r   r   NNFTr   r   r   r   r   N)rt  ru   numpyrU   scipy.optimizer   r   scipy.optimize._optimizer   r   scipy._lib._utilr   r   r	   r
   r   scipy.optimize._constraintsr   r   r   r   scipy.sparser   __all__finfor   epsr   r   r5   r   r   rZ   r;   <module>r     s         3 3 3 3 3 3 3 3 D D D D D D D D@ @ @ @ @ @ @ @ @ @ @ @ @ @P P P P P P P P P P P P ! ! ! ! ! !#
$ 28BJ# F+++;E9=EI=ACN9=_ (,_ _ _ _ ,+_D}8 }8 }8 }8 }8 }8 }8 }8@*w w w w w w w w w wrZ   