
    (phQ                    &   S r SSKrSSKrSSKJrJr  SSKJrJ	r	  SSK
JrJrJrJrJr  SSKJrJrJrJr  SSKJr  S/r\R0                  " \R2                  5      R4                  r\" S	S
S9      SSSS.S jj5       r " S S5      r " S S5      rg)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_numFintegrality
vectorizedc                    [        X40 SU_SU_SU_SU_SU_SU_SU_SU	_S	U_S
U
_SU_SU_SU_SU_SU_SU_SU_SU_SU_6 nUR                  5       nSSS5        U$ ! , (       d  f       W$ = f)aN  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$   r%   r&   r'   r(   r)   r   r   solverrets                          X/var/www/html/venv/lib/python3.13/site-packages/scipy/optimize/_differentialevolution.pyr   r      s    ^ 
%T 
< 
<.6
<-4
< .5
< ;>
< /7	
<
 4A
< *-
< 6<
< /7
< +/
< 6:
< AE
< /7
< .5
< 2=
< )+
< 2=
< 1;
< @Flln
<" J#
< 
<" Js   A
A.c                   Z   \ rS rSrSrSSSSSSS	.rSSSSSSS
.rSrSSSSSSSS\R                  SSSSSSSSS4SSS.S jjr
S rS rS rS r\S  5       r\S! 5       rS" rS# rS$ rS% rS& rS' rS( rS) rS* rS+ rS, rS- rS. rS/ rS0 r S1 r!S2 r"S3 r#S4 r$S5 r%S6 r&S7 r'S8 r(S9 r)S: r*S;r+g)<r*   i  a3,  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)best1bin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>5 r8        {Gz?      ?   ffffff?NFTlatinhypercuber   	immediaterJ   r   c          	         [        U5      (       a  OeX@R                  ;   a  [        X R                  U   5      U l        O8X@R                  ;   a  [        X R                  U   5      U l        O[        S5      eX@l        [        US5      U l        Xl	        US;   a  UU l
        UU l        US:w  a'  US:X  a!  [        R                  " S[        SS9  S	U l
        U(       a$  US:w  a  [        R                  " S
SS9  S=U l        nU(       a'  US:X  a!  [        R                  " S[        SS9  S	U l
        U(       a  S nUn[        U5      U l        UUsU l        U l        Xl        [(        R*                  " [(        R,                  " U5      5      (       ad  [(        R.                  " [(        R0                  " U5      S:  5      (       d2  [(        R.                  " [(        R0                  " U5      S:  5      (       a  [        S5      eS U l        [5        US5      (       a8  [7        U5      S:  a)  US   US   /U l        U R2                  R9                  5         Xl        [=        X5      U l        X0l         [C        U[D        5      (       a[  [(        R0                  " [G        URH                  URJ                  [7        URH                  5      5      [L        S9RN                  U l(        O$[(        R0                  " USS9RN                  U l(        [(        RR                  " U RP                  S5      S:w  d9  [(        R*                  " [(        R,                  " U RP                  5      5      (       d  [        S5      eUc  SnXPl*        Uc  [(        RV                  nXl,        SU RP                  S   U RP                  S   -   -  U l-        [(        R\                  " U RP                  S   U RP                  S   -
  5      U l/        [(        R`                  " SS9   SU R^                  -  U l1        SU Rb                  [(        R,                  " U Rb                  5      ) '   S S S 5        [(        RR                  " U RP                  S5      U l2        [g        U
5      U l4        [(        R.                  " U5      (       GaI  [(        Rj                  " UU Rd                  5      n[(        Rl                  " U[n        5      n[(        Rp                  " U RP                  5      u  nn[(        Rr                  " U5      n[(        Rt                  " U5      nUU   UU   :*  R+                  5       (       d  [        S5      e[(        Rv                  " UU   S-
  [(        RV                  5      n[(        Rv                  " UU   S-   [(        RV                  * 5      nUU l<        UU RP                  SU Rx                  4'   UU RP                  SU Rx                  4'   OSU l<        U RP                  S   U RP                  S   :H  n[(        Rz                  " U5      n[}        SU[}        SU Rd                  U-
  5      -  5      U l?        U R~                  U Rd                  4U l@        SU lA        [C        U[        5      (       a  US:X  a  U R                  5         OUS:X  at  [        S[(        Rr                  " [(        R                  " U R~                  5      5      -  5      nUU l?        U R~                  U Rd                  4U l@        U R                  SS9  OSUS:X  a  U R                  SS9  O=US:X  a  U R                  5         O&[        U R                  5      eU R                  U5        Ub]  U R                  [(        Rl                  " U5      5      nUS:  US :  -  R/                  5       (       a  [        S!5      eUU R                  S'   UU lL        / U lM        [5        US"5      (       a9  U H2  n U R                  R                  [        U U R                  5      5        M4     O[        UU R                  5      /U lM        [(        R                  " U R                   V s/ s H  n U R                  PM     sn 5      U lS        [(        R                  " U R~                  S45      U lU        [(        R                  " U R~                  [n        5      U lW        [(        R                  " U R~                  5      U lY        XlZ        g ! , (       d  f       GN= fs  sn f )#Nz'Please select a valid mutation strategyr   )rM   deferredrJ   rM   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                 N    [         R                  " U " UR                  5      5      $ N)np
atleast_1dT)r,   xs     r0   maplike_for_vectorized_funcIDifferentialEvolutionSolver.__init__.<locals>.maplike_for_vectorized_func+  s     }}T!##Y//    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 xrE   rI   ignore)dividezlOne of the integrality constraints does not have any possible integer values between the lower/upper bounds.   rL   sobol)
qmc_enginehaltonrandom      ?        z3Some entries in x0 lay outside the specified bounds__len__)[callable	_binomialgetattrmutation_func_exponential
ValueErrorr   r   r"   r!   	_updatingr   warningswarnUserWarningr   _mapwrapperr   r%   scalerU   allisfiniteanyarrayditherhasattrlensortcross_over_probabilityr	   r,   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
populationr(   _wrapped_constraintsappend_ConstraintWrapperrX   sum
num_constrtotal_constraintszerosconstraint_violationonesfeasiblearange_random_population_indexr#   )!selfr,   r-   r   r   r   r   r   r   r   r    r   r"   r#   r!   r$   r%   r&   r'   r(   r)   r   r   rY   r   r   nlbnubebeb_countn_s	x0_scaledcs!                                    r0   __init__$DifferentialEvolutionSolver.__init__  sd    H'!(~~h/G!HD***!(/@/@/J!KDFGG &x1IJ 00%DN$ a<H3MM 12=!M (DN'Q,MM @LMO+00DOj(k1MM ()4D (DN 0
 2G%g. "4$) 
r{{8,--rxx)Q.//rxx)A-.. M N N 8Z((S]Q->#A;4DKKK&3# %T0		
 ff%%((#4VYY5;YY58^$E */0 12 K
 ((69;;DKGGDKK#q(r{{4;;/00 % & & ?G>VVF  4;;q>DKKN#BCGGDKKNT[[^$CD[[) '($*;*;&;D#MND##R[[1H1H%I$IJ *  "wwt{{A6'9#'>$ 66+//$$K **[$7K WWT[[)FBB"B{Or+6;;== ! "< = = ,,r+4bff=C,,r+4rvvg>C*D/2DKK4+++,/2DKK4+++,$D [[^t{{1~-##B' '*c!T11H<=='
# "&!<!<!%!5!5!7 
dC  ''((*!rwwrwwt/J/J'KLLM.1+)-)D)D)-)=)=)?%((G(<!((H(=!++- !6!677&&t,> 00B@ISY_5::<< I  "+DOOA '$&!;	** !))00&q$&&1 ! #;7)D% "$#'#<#<=#<aQ\\#<="
 %'HHd.I.I1-M$N! ; ;TB )+		$2M2M(N%	a *)P >s   =Ac8d
8
dc                 8   U R                   nSU R                  -  nX!R                  U R                  S9-  [        R
                  " SSU R                  SS9SS2[        R                  4   -   n[        R                  " U5      U l        [        U R                  5       H>  nUR                  [        U R                  5      5      nX5U4   U R                  SS2U4'   M@     [        R                  " U R                  [        R                  5      U l        SU l        g)z
Initializes the population with Latin Hypercube Sampling.
Latin Hypercube Sampling ensures that each parameter is uniformly
sampled over its range.
rg   r   rh   F)endpointNr   )r   r   uniformr   rU   linspacenewaxis
zeros_liker   ranger   permutationfullr   population_energiesr   )r   r    segsizesamplesjorders         r0   r   /DifferentialEvolutionSolver.init_population_lhs  s     ** 333 [[d.C.C[DD [[R)D)D*/112BJJ@@ --0 t++,AOOE$*E*E$FGE$+1H$5DOOAqD! -
 $&774+F+F+-66$3  
r[   c                    SSK Jn  U R                  nUS:X  a  UR                  U R                  US9nOWUS:X  a  UR                  U R                  US9nO6US:X  a  UR                  U R                  US9nO[        U R                  5      eUR                  U R                  S9U l        [        R                  " U R                  [        R                  5      U l        SU l        g)	a  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   )qmcrL   )dr   rc   re   )nN)scipy.statsr   r   LatinHypercuber   SobolHaltonro   r   rf   r   r   rU   r   r   r   r   )r   rd   r   r    samplers        r0   r   /DifferentialEvolutionSolver.init_population_qmc  s     	$** ))((4+?+?c(JG7"ii$"6"6SiAG8#jj4#7#7cjBGT2233!..4+F+F.G $&774+F+F+-66$3  
r[   c                     U R                   nUR                  U R                  S9U l        [        R
                  " U R                  [        R                  5      U l        SU l	        g)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     r0   r   2DifferentialEvolutionSolver.init_population_random'  sR    
 **++4+@+@+A $&774+F+F+-66$3  
r[   c                 V   [         R                  " U[         R                  S9n[         R                  " US5      S:  d6  UR                  S   U R
                  :w  d  [        UR                  5      S:w  a  [        S5      e[         R                  " U R                  U5      SS5      U l
        [         R                  " U R                  S5      U l        U R                  U R
                  4U l        [         R                  " U R                  [         R                  5      U l        SU l        g)a(  
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   rb   rJ   rP   zEThe population supplied needs to have shape (S, len(x)), where S > 4.N)rU   r   float64r   shaper   r|   ro   clipr   r   r   r   r   r   r   r   )r   r$   popns      r0   r   1DifferentialEvolutionSolver.init_population_array6  s     zz$bjj1GGD!q 

1!5!55DJJ1$ : ; ; ''$":":4"@!QG&(ggdooq&A#!%!<!<!%!5!5!7 $&774+F+F+-66$3  
r[   c                 >    U R                  U R                  S   5      $ )z#
The best solution from the solver
r   )_scale_parametersr   r   s    r0   rX   DifferentialEvolutionSolver.xY  s    
 %%dooa&899r[   c                 L   [         R                  " [         R                  " U R                  5      5      (       a  [         R                  $ [         R
                  " U R                  5      [         R                  " [         R                  " U R                  5      5      [        -   -  $ )zJ
The standard deviation of the population energies divided by their
mean.
)	rU   rx   isinfr   r   stdabsmean_MACHEPSr   s    r0   convergence'DifferentialEvolutionSolver.convergence`  si     66"((43345566Mt//0 8 89:XEG 	Hr[   c                 T   [         R                  " [         R                  " U R                  5      5      (       a  g[         R                  " U R                  5      U R
                  U R                  [         R                  " [         R                  " U R                  5      5      -  -   :*  $ )z*
Return True if the solver has converged.
F)	rU   rx   r   r   r   r%   r   r   r   r   s    r0   	converged%DifferentialEvolutionSolver.convergedk  st     66"((433455t//0		266"''$*B*B"CDDEE 	Fr[   c                 0  ^  Su  p[         S   n[        R                  " [        R                  " T R                  5      5      (       aw  T R                  T R                  5      u  T l        T l        T R                  T R                  T R                     5      T R                  T R                  '   T R                  5         [        ST R                  S-   5       H  n [        T 5        T R"                  (       a  [%        SU ST R                  S	    35        T R&                  (       aZ  T R(                  T R*                  [,        -   -  nT R/                  US
S9nXEl         [1        T R'                  U5      5      nU(       a  SnU(       d  T R3                  5       (       d  M    O   [         S   nSnT R/                  XUS9nT R4                  (       Ga  [        R                  " T R6                  5      (       Gdr  [        R8                  " T R6                  5      (       a?  T R:                  T R6                  pUR<                  U   US	U4'   UR<                  U   USU4'   Sn	T R>                  (       aU  Sn	T RA                  UR<                  5      n
[        R8                  " U
S:  5      (       a  [B        RD                  " S[F        SS9  T R"                  (       a  [%        SU	 S35        [I        U 4S j[        RJ                  " UR<                  5      U	T R:                  RL                  T RN                  S9nT =R                  URP                  -  sl        T R                  Ul(        URR                  URR                  :  a  URT                  (       a  [        R                  " UR<                  T R:                  S   :*  5      (       a  [        R                  " T R:                  S	   UR<                  :*  5      (       at  URR                  Ul)        UR<                  Ul        URV                  Ul+        URR                  T R                  S	'   T RY                  UR<                  5      T R                  S	'   T R>                  (       a  T R>                   Vs/ s H  nUR[                  UR<                  5      PM      snUl.        [        R^                  " [        R`                  " UR\                  5      5      Ul1        URb                  Ul2        URd                  S	:  a  SUl*        SURd                   3Ul3        U$ ! [         aH    SnT R                  T R                   :  a
  [         S   nOT R                  T R                   :X  a  Sn   GM  f = f! [         a    Sn GNf = fs  snf )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successrJ   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-constrrh   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R                  TR                  [        R                  " U 5      5      5      S   $ )Nr   )listrt   r,   rU   
atleast_2d)rX   r   s    r0   <lambda>3DifferentialEvolutionSolver.solve.<locals>.<lambda>  s+     $T%5%5diiqAQ%R STU Vr[   )methodr-   r(   Fz7The solution does not satisfy the constraints, MAXCV = )4r   rU   rv   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   rx   r   rX   r   _constraint_violation_fnrq   rr   rs   r   r   rW   r(   nfevfunr   jacr   	violationconstrr   concatenateconstr_violationmaxcvr   )r   r   r   status_messager   res	DE_resultr   r   polish_methodr  results   `           r0   r+   !DifferentialEvolutionSolver.solvev  s~   ( %(3 66"((43345588I 5DM44
 33OODMM24 $$T]]3 '') DLL1,-C	T
 yy4SE :221568  }}HH 0 08 ;<llsMlB"#(#'c(:#;L  %MN t~~//A .F -Y7NLLL, ! 
	 ;;;rvvd&6&677vvd&&'' '+kk43C3C)2[)Aq+~&)2[)Aq+~&&M(( .#'#@#@#M 66*R/00MM #8 #.!	=
 yy1-BC W ggikk2%2%)[[]]*.*:*:<F JJ&++%J!ZZIN
 

Y]]*NNFF688t{{1~566FF4;;q>VXX566 &

	$hh	 &

	.4jj((+%)%=%=fhh%G"$$%)%>%> @%> !"IKK 8%> @I)+y//0*2I&'88IO"$)	!&==F__<M&O	! C ! #::+%4X%>NZZ4;;.';N( % (#'L(D @s+   T+V %V+AU=<U= VVc                    UR                  SS 5      nUR                  SS 5      nUR                  SS5      n[        U R                  U R                  S   U R                  UUUSLU R                  U R                  5      U R                  S9nU R                  (       a  U R                   Vs/ s H  nUR                  UR                  5      PM      snUl	        [        R                  " [        R                  " UR                  5      5      Ul        UR                  Ul        UR                  S:  a  SUl        U$ s  snf )Nr   r   r   Fr   T)rX   r   r   r   r   r   r   r   )getr   rX   r   r   r   r   r   r  r  rU   r   r  r  r  r   )r   kwdsr   r   r   r  r   s          r0   r   #DifferentialEvolutionSolver._result  s	   hhud#((9d+xx6ff((+!---doo> $ 8 8	
 $$&*&?&?A&? [[2&?AFM&(ffR^^FMM-J&KF#!22FL||a!&As   ,%D<c                    [         R                  " US5      n[        X R                  U R                  -
  5      n[         R
                  " U[         R                  5      nU R                  U5      n [        U R                  U R                  USU 5      5      n[         R                  " U5      nUR                  U:w  a'  U R                  (       a  [        S5      e[        S5      eXdSU& U R                  (       a  U =R                  S-  sl        U$ U =R                  U-  sl        U$ ! [        [        4 a  n[        S5      UeSnAff = f)a  
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 valuerJ   )rU   r   minr   r   r   r   r   r   rt   r,   squeeze	TypeErrorro   RuntimeErrorr   )r   r   num_membersSenergiesparameters_popcalc_energieses           r0   r   :DifferentialEvolutionSolver._calculate_population_energies  s+   $ ggj!, [[4::5677;///
;	   N1Q,?@M JJ}5M "" $; < < JKK%1??JJ!OJ  JJ!OJ- :& 	 P 	s   1>D) )E
9EE
c                 X   [         R                  " U R                  5      nXR                     nUR                  (       a(  [         R
                  " U R                  U   5      nX#   nO3[         R
                  " [         R                  " U R                  SS95      nU R                  US/   U R                  SU/'   U R                  US/S S 24   U R                  SU/S S 24'   U R                  US/   U R                  SU/'   U R                  US/S S 24   U R                  SU/S S 24'   g )NrJ   axisr   )
rU   r   r   r   r   argminr   r   r   r   )r   idxfeasible_solutionsidx_tls        r0   r   2DifferentialEvolutionSolver._promote_lowest_energyU  s    ii334 /""IId667IJKE")A 		"&&!:!:CDA+/+C+CQF+K  !Q(%)__aVQY%?A	" $q!f 5q!f!!1a&!), 	!!1a&!),r[   c                    [         R                  " U5      U R                  -  n[         R                  " X R                  45      nSnU R
                   H  nUR                  UR                  5      R                  nUR                  S   UR                  :w  d  US:  a  UR                  S   U:w  a  [        S5      e[         R                  " XbUR                  45      nXcSS2XDUR                  -   24'   XER                  -  nM     U$ )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   rJ   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   r   r  reshape)r   rX   r  _outoffsetconr   s          r0   r   4DifferentialEvolutionSolver._constraint_violation_fni  s    * GGAJ$...xx2234,,C acc"$$A wwr{cnn,Q1771:?" $9 : : 

1#..12A67FCNN2223nn$F? -B r[   c                    [         R                  " US5      nU R                  (       d3  [         R                  " U[        5      [         R
                  " US45      4$ U R                  U5      nU R                  (       a&  [         R                  " U R                  U5      5      nO?[         R                  " U Vs/ s H  nU R                  U5      PM     sn5      nUSS2S4   n[         R                  " USS9S:  ) nXd4$ s  snf )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   rJ   Nr  )rU   r   r   r   r   r   r   r   ry   r   r   )r   r   r  r  r   rX   r   s          r0   r   ?DifferentialEvolutionSolver._calculate_population_feasibilities  s    $ ggj!,((77;-rxxa8H/III //
;??#%88--n=$ 
 $&886D-F6D .2-J-J1-M6D-F $G  $81#= VV0q9A=>---Fs   8C?c                     U $ rT   rD   r   s    r0   r\   $DifferentialEvolutionSolver.__iter__      r[   c                     U $ rT   rD   r   s    r0   	__enter__%DifferentialEvolutionSolver.__enter__  r2  r[   c                 4    U R                   R                  " U6 $ rT   )rt   __exit__)r   r   s     r0   r7  $DifferentialEvolutionSolver.__exit__  s    (($//r[   c                     U(       a  U(       a  X:*  $ U(       a  U(       d  gU(       d  X6:*  R                  5       (       a  gg)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)rv   )r   energy_trialfeasible_trialcv_trialenergy_origfeasible_origcv_origs          r0   _accept_trial)DifferentialEvolutionSolver._accept_trial  s7    D ^..MX%8$=$=$?$? r[   c           
      h
   [         R                  " [         R                  " U R                  5      5      (       aw  U R	                  U R
                  5      u  U l        U l        U R                  U R
                  U R                     5      U R                  U R                  '   U R                  5         U R                  b;  U R                  R                  U R                  S   U R                  S   5      U l        U R                  S:X  Ga  [        U R                   5       GH  nU R"                  U R$                  :  a  [&        eU R)                  U5      nU R+                  U5        U R-                  U5      nU R.                  (       af  U R1                  U5      nSn[         R2                  n[         R4                  " U5      S:  d(  SnU R7                  U5      nU =R"                  S-  sl        O?Sn[         R8                  " S/5      nU R7                  U5      nU =R"                  S-  sl        U R;                  XeUU R                  U   U R                  U   U R                  U   5      (       d  GMQ  X R
                  U'   [         R<                  " U5      U R                  U'   XPR                  U'   X@R                  U'   U R;                  XeUU R                  S   U R                  S   U R                  S   5      (       d  GM  U R                  5         GM     GOU R                  S:X  Ga  U R"                  U R$                  :  a  [&        eU R?                  [         R@                  " U R                   5      5      nU R+                  U5        U R	                  U5      u  pT[         RB                  " U R                   [         R2                  5      nU R                  Xu   5      X'   [E        XX@R                  U R                  U R                  5       V	s/ s H  oR:                  " U	6 PM     n
n	[         RF                  " U
5      n
[         RH                  " U
SS2[         RJ                  4   UU R
                  5      U l        [         RH                  " U
UU R                  5      U l        [         RH                  " U
UU R                  5      U l        [         RH                  " U
SS2[         RJ                  4   UU R                  5      U l        U R                  5         U RL                  U R                  S   4$ s  sn	f )	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   rJ   rM   FTrh   rO   )'rU   rv   r   r   r   r   r   r   r   r   rz   r   r   ru   rp   r   r   r   r   r   _mutate_ensure_constraintr   r   r   r   r   r,   r   r@  r  _mutate_manyr   r   zipry   wherer   rX   )r   	candidatetrial
parameterscvr   energy	trial_poptrial_energiesvallocs              r0   __next__$DifferentialEvolutionSolver.__next__  sP    66"((43345588I 5DM44 33OODMM24 $$T]]3 '');;"55==dkk!n>Bkk!nNDJ >>[("4#>#>?	::+'' Y/ ''. "33E:
 ,,66zBB$HVVF66":>#'!%:!6

a
#Ht,B!YYz2FJJ!OJ %%f&*&>&>y&I&*mmI&>&*&?&?	&JL L 27OOI.:<**V:LD,,Y7/7MM),;=--i8 ))&B*.*B*B1*E*.--*:*.*C*CA*FH H 335[ @^ ^^z)zzT[[(## ))		$556I
 ##I.  CCINLHWWT%@%@"&&IN (,'J'J#(%N$
 ~5M5M}}d&?&?ABA 14%%s+A  B ((3-C hhs1bjj='9'0'+8DO (*xx0>040H0H(JD$ HHS%-%)]]4DM )+Q

]1C13151J1J)LD% '')vvt//222+Bs   T/c                    U R                   US-
  U R                  -  -   n[        R                  " U R                  5      (       aE  [        R
                  " U R                  UR                  5      n[        R                  " X#   5      X#'   U$ )z2Scale from a number between 0 and 1 to parameters.rI   )r   r   rU   r   r   r   r   round)r   rI  scaledis       r0   r   -DifferentialEvolutionSolver._scale_parameters  sk     ""eckT5F5F%FFD,,-- 0 0&,,?A+FIr[   c                 >    XR                   -
  U R                  -  S-   $ )z2Scale from parameters to a number between 0 and 1.rI   )r   r   )r   rJ  s     r0   r   /DifferentialEvolutionSolver._unscale_parameters  s!    ...$2I2IICOOr[   c                     [         R                  " US:  US:  5      n[         R                  " U5      =n(       a  U R                  R	                  US9X'   gg)z0Make sure the parameters lie between the limits.rJ   r   r   N)rU   
bitwise_orr   r   r   )r   rI  maskoobs       r0   rD  .DifferentialEvolutionSolver._ensure_constraint  sP    }}UQY	2""4((3(66>>C>HEK )r[   c                    U R                   nSnU R                  U R                  5      n[        [        R
                  " U5      5      (       d7  U R                  XUS9nUR
                  U R                  4:w  a  [        U5      eOlUR
                  S   n[        R                  " U Vs/ s H  opR                  XtUS9PM     sn[        S9nUR
                  X`R                  4:w  a  [        U5      eU R                  U5      $ s  snf )Nzqstrategy must have signature f(candidate: int, population: np.ndarray, rng=None) returning an array of shape (N,))r    r   r]   )r   r   r   r|   rU   r   r   r   r  ry   r_   r   )r   rH  r    msg_populationrI  r  r   s           r0   _mutate_custom*DifferentialEvolutionSolver._mutate_custom  s    **# 	
 ,,T__=288I&''MM)cMBE{{t3355"3'' 6 "AHHAJKAq37KE {{q"6"677"3''''.. Ls   (Dc           	         U R                   n[        U5      n[        U R                  5      (       a  U R	                  U5      $ [
        R                  " U R                  U   5      n[
        R                  " U Vs/ s H  oPR                  US5      PM     sn5      nU R                  S;   a  U R                  X5      nOU R                  U5      n[        X R                  US9nUR                  X0R                  4S9n	XR                  :  n	U R                  U R                  ;   a7  [
        R                   " U5      n
SXX   4'   [
        R"                  " XU5      nU$ U R                  U R$                  ;   a|  SU	S'   ['        U5       Hf  nSn
X   nXR                  :  d  M  XU
4   (       d  M'  X{U4   XKU4'   US-   U R                  -  nU
S-  n
XR                  :  d  MY  XU
4   (       a  M?  Mh     U$ gs  snf )	z2Create trial vectors based on a mutation strategy.rb   rA   r:   r   T).r   r   rJ   N)r   r|   rj   r   rb  rU   r   r   ry   _select_samplesrm   r
   r   r   r~   rk   r   rG  rn   r   )r   
candidatesr    r  rI  r   r   bprime
fill_point
crossoversrV  r   	init_fills                r0   rE  (DifferentialEvolutionSolver._mutate_many  s   **
ODMM""&&z22
34((
K
100A6
KL==FF''
<F''0F!#';';!D
[[q*>*>&?[@
"="==
==DNN*
 		!A+/J*-'(HHZ7EL]]d///!%Jv1X&M	///J!t4D4D*0I*>EY,'!*Q$2F2F FIFA ///J!t4D4D  L 0) Ls   :G3c                    U R                   n[        U R                  5      (       a  U R                  U5      $ [	        X R
                  5      nU R                  US5      n[        R                  " U R                  U   5      nU R                  S;   a  U R                  X5      nOU R                  U5      nUR                  U R
                  S9nXpR                  :  nU R                  U R                  ;   a  SXs'   [        R                  " XvU5      nU$ U R                  U R                  ;   aX  SnSUS'   XR
                  :  a@  Xx   (       a7  Xc   XS'   US-   U R
                  -  nUS-  nXR
                  :  a  Xx   (       a  M7  U$ g)z3Create a trial vector based on a mutation strategy.rb   re  r   Tr   rJ   N)r   rj   r   rb  r
   r   rf  rU   r   r   rm   r   r~   rk   rG  rn   )	r   rH  r    ri  r   rI  rh  rj  rV  s	            r0   rC  #DifferentialEvolutionSolver._mutate  s^   **DMM""&&y11!#';';<
&&y!4	23==FF''	;F''0F[[d&:&:[;
"="==
==DNN*
 &*J"HHZ7EL]]d///A JqM***z}$*$6!(1n0D0DD
Q ***z}}
 L 0r[   c                     USSS24   R                   u  p#U R                  S   U R                  U R                  U   U R                  U   -
  -  -   $ )zbest1bin, best1exp.NrP   r   rW   r   ru   )r   r   r0r1s       r0   r2   "DifferentialEvolutionSolver._best1  sY    
 bqb!##"TZZ$tr'::&< < 	=r[   c                     USSS24   R                   u  p#nU R                  U   U R                  U R                  U   U R                  U   -
  -  -   $ )zrand1bin, rand1exp.N   rp  )r   r   rq  rr  r2s        r0   r7   "DifferentialEvolutionSolver._rand1  sY    S"1"W%''
#djj$tr'::'< < 	=r[   c                    USSS24   R                   u  p#n[        R                  " U R                  U   5      nXPR                  U R                  S   U-
  -  -  nXPR                  U R                  U   U R                  U   -
  -  -  nU$ )zrandtobest1bin, randtobest1exp.Nru  r   )rW   rU   r   r   ru   )r   r   rq  rr  rv  rh  s         r0   r3   (DifferentialEvolutionSolver._randtobest1  s    S"1"W%''
,-** 2V ;<<** 3 $ 3!4 5 	5r[   c                     USSS24   R                   u  p4U R                  U   U R                  U R                  S   U R                  U   -
  U R                  U   -   U R                  U   -
  -  -   nU$ )z$currenttobest1bin, currenttobest1exp.NrP   r   rp  )r   rH  r   rq  rr  rh  s         r0   r4   +DifferentialEvolutionSolver._currenttobest1  s}    bqb!##//),tzz??1%	(BB??2&')-)<=0> > r[   c                     USSS24   R                   u  p#pEU R                  S   U R                  U R                  U   U R                  U   -   U R                  U   -
  U R                  U   -
  -  -   nU$ )zbest2bin, best2exp.N   r   rp  )r   r   rq  rr  rv  r3rh  s          r0   r5   "DifferentialEvolutionSolver._best2  s     bqb)++//!$tzz??2&)<<??2&')-)<=(> > r[   c                     USSS24   R                   u  p#pEnU R                  U   U R                  U R                  U   U R                  U   -   U R                  U   -
  U R                  U   -
  -  -   nU$ )zrand2bin, rand2exp.Nrb   rp  )r   r   rq  rr  rv  r~  r4rh  s           r0   r6   "DifferentialEvolutionSolver._rand2'  s    $S"1"W-////"%

??2&)<<??2&')-)<=)> > r[   c                     U R                   R                  U R                  5        U R                  SUS-    nX3U:g     SU $ )z
obtain random integers from range(self.num_population_members),
without replacement. You can't have the original candidate either.
NrJ   )r   shuffler   )r   rH  number_samplesidxss       r0   rf  +DifferentialEvolutionSolver._select_samples0  sK    
 	$$,,T-J-JK,,-@nq.@AI%&77r[   )#__recip_scale_arg2__scale_arg1__scale_arg2rt   r   r   rp   r   r   r%   r"   r   r(   r~   r#   rz   r   r,   r   r   r   r   rm   r   r   r!   r   r   r   r   ru   r   r   r   r   ),__name__
__module____qualname____firstlineno____doc__rk   rn   r   rU   r   r   r   r   r   r   propertyrX   r   r   r+   r   r   r   r   r   r\   r4  r7  r@  rQ  r   r   rD  rb  rE  rC  r2   r7   r3   r4   r5   r6   rf  __static_attributes__rD   r[   r0   r*   r*     sZ   k\ &#1&7%%%'I !) (&4): ( (*LM +-$dBHCTE$&Qt`
 EI!`D$L"H!F : : H H	FM^25n.(9v+.Z0+Z{3zPI/.'R$L==8r[   r*   c                   *    \ rS rSrSrS rS rS rSrg)r   i:  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                   ^ TU l         [        T[        5      (       a  U4S jnO@[        T[        5      (       a  U4S jnO$[        T[        5      (       a  S nO[        S5      eX0l        [        R                  " TR                  [        S9n[        R                  " TR                  [        S9n[        R                  " U5      nU" U5      nUR                  =U l        nUR                  U l        UR                  S:X  a  [        R                   " XG5      nUR                  S:X  a  [        R                   " XW5      nXE4U l        g )Nc                 z   > [         R                  " U 5      n [         R                  " TR                  U 5      5      $ rT   )rU   r   rV   r   )rX   
constraints    r0   r   (_ConstraintWrapper.__init__.<locals>.fun]  s(    JJqM}}Z^^A%677r[   c                 2  > [        TR                  5      (       a  TR                  nO [        R                  " TR                  5      nUR	                  U 5      nU R
                  S:X  a-  UR
                  S:X  a  [        R                  " U5      S S 2S4   nU$ )NrJ   rP   r   )r   ArU   r   dotndimr   )rX   r  r  r  s      r0   r   r  a  sn    JLL))"Ajll3AeeAh 66Q;388q= **S/!Q$/C
r[   c                 .    [         R                  " U 5      $ rT   )rU   r   )rX   s    r0   r   r  t  s    zz!}$r[   z*`constraint` of an unknown type is passed.r]   r   )r  r   r   r   r   ro   r   rU   r   r   r_   r   r   r   r   r  resizer-   )r   r  r)   r   r   r   f0ms    `      r0   r   _ConstraintWrapper.__init__Y  s    $j"5668 
$455$ 
F++% IJJZZ
U3ZZ
U3ZZ^ W gg%!!ww77a<2!B77a<2!Bhr[   c                 L    [         R                  " U R                  U5      5      $ rT   )rU   rV   r   )r   rX   s     r0   __call___ConstraintWrapper.__call__  s    }}TXXa[))r[   c                 n   U R                  [        R                  " U5      5      n [        R                  " U R                  S   UR
                  -
  S5      n[        R                  " UR
                  U R                  S   -
  S5      nX4-   R
                  nU$ ! [         a  n[        S5      UeSnAff = f)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   rJ   r(  N)r   rU   r   maximumr-   rW   ro   r  )r   rX   ev	excess_lb	excess_ubr  vs          r0   r  _ConstraintWrapper.violation  s    " XXbjjm$	=

4;;q>BDD#8!<I

244$++a.#8!<I "%%  		=  5 6 <==		=s   A"B 
B4#B//B4)r-   r  r   r   r   N)	r  r  r  r  r  r   r  r  r  rD   r[   r0   r   r   :  s    <1f*"r[   r   )rD   r8   rE   rF   rG   rH   rK   NNFTrL   r   rM   rJ   rD   N)r  rq   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   r*   r   rD   r[   r0   <module>r     s      3 D@ @P P !#
$ 88BJJ## F+;E9=EI=ACN9=_ (,_ ,_D}8 }8@*w wr[   