L iQ(dZddlZddlZddlmZmZddlmZm Z m Z m Z ddl m Z mZddlmZmZmZmZmZddlmZdgZej0ej2j4Zed d  ddd d dZGddZGddZy)zn differential_evolution: The differential evolution global optimization algorithm Added by Andrew Nelson 2014 N)OptimizeResultminimize)Boundsnew_bounds_to_oldNonlinearConstraintLinearConstraint)_status_message_wrap_callback)check_random_state MapWrapper_FunctionWrapper rng_integers_transition_to_rng)issparsedifferential_evolutionseed ) position_numF integrality vectorizedct||fid|d|d|d|d|d|d|d| d | d | d | d | d |d|d|d|d|d|d|5}|j}ddd|S#1swYSxYw)aTFinds 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 `). 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 argsstrategymaxiterpopsizetolmutation recombinationrngpolishcallbackdispinitatolupdatingworkers constraintsx0rrN)DifferentialEvolutionSolversolve)funcboundsrrrrrrrr r"r#r!r$r%r&r'r(r)rrsolverrets k/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/optimize/_differentialevolution.pyrrs^ %T6 < <.6 <-4 <.5 <;> </7  < 4A  < *-  < 6<  </7 <+/ <6: <AE </7 <.5 <2= <)+ <2= <1; <@Flln" J#" Js A  A*cNeZdZdZdddddddZddddddd Zd Zd d d dddddejdddddddd dfddddZ dZ dZ dZ dZ edZed Zd!Zd"Zd#Zd$Zd%Zd&Zd'Zd(Zd)Zd*Zd+Zd,Zd-Zd.Zd/Zd0Z d1Z!d2Z"d3Z#d4Z$d5Z%d6Z&d7Z'd8Z(d9Z)y):r*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 `_ 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 `). 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)best1binrandtobest1bincurrenttobest1binbest2binrand2binrand1bin)best1exprand1exprandtobest1expcurrenttobest1expbest2exprand2expzThe 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>5r8{Gz??ffffff?NFTlatinhypercuber immediaterJrc Tt|rne||jvrt||j||_n8||jvrt||j||_n t d||_t| d|_||_ |dvr||_ ||_ |dk7r(|dk(r#tjdtdd |_ |r%|dk7r tjd dd x|_ }|r(|dk(r#tjd tdd |_ |rd }|}t||_||c|_|_||_t)j*t)j,|rVt)j.t)j0|dk\s+t)j.t)j0|dkr t dd|_t5|dr7t7|dkDr)|d|dg|_|j2j9| |_t=|||_||_ tC|tDr]t)j0tG|jH|jJt7|jHtLjN|_(n&t)j0|djN|_(t)jR|jPddk7s2t)j*t)j,|jPs t d|d}||_*| t(jV} | |_,d|jPd|jPdzz|_-t)j\|jPd|jPdz |_/t)j`d5d|j^z |_1d|jbt)j,|jb<dddt)jR|jPd|_2tg| |_4t)j.|r=t)jj||jd}t)jl|tn}t)jp|jP\}}t)jr|}t)jt|}||||kj+s t dt)jv||dz t(jV}t)jv||dzt(jV }||_<||jPd|jxf<||jPd|jxf<nd |_<|jPd|jPdk(}t)jz|}t}d|t}d|jd|z z|_?|j~|jdf|_@d|_AtC|tr|dk(r|jn|dk(rutdt)jrt)j|j~z}||_?|j~|jdf|_@|jdnT|dk(r|jdn<|dk(r|jn&t |j|j||W|jt)jl|}|dkD|d kzj/r t d!||jd<||_Lg|_Mt5|d"r7|D]1} |jjt| |j3nt||jg|_Mt)j|jD cgc]} | jc} |_St)j|j~df|_Ut)j|j~tn|_Wt)j|j~|_Y| |_Zy#1swYxYwcc} w)#Nz'Please select a valid mutation strategyr)rMdeferredrJrMzhdifferential_evolution: the 'workers' keyword has overridden updating='immediate' to updating='deferred' stacklevelrOzPdifferential_evolution: the 'workers' keyword overrides the 'vectorized' keywordFzkdifferential_evolution: the 'vectorized' keyword has overridden updating='immediate' to updating='deferred'cLtj||jSN)np atleast_1dT)r,xs r0maplike_for_vectorized_funczIDifferentialEvolutionSolver.__init__..maplike_for_vectorized_func,s}}T!##Y//rzThe 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__dtypefloatz^bounds should be a sequence containing finite real valued (min, max) pairs for each value in xrErIignore)dividezlOne of the integrality constraints does not have any possible integer values between the lower/upper bounds.rLsobol) qmc_enginehaltonrandom?z3Some entries in x0 lay outside the specified bounds__len__)[callable _binomialgetattr mutation_func _exponential ValueErrorrr r"r! _updatingrwarningswarn UserWarningr _mapwrapperrr%scalerUallisfiniteanyarrayditherhasattrlensortcross_over_probabilityr r,r isinstancerrlbubr^rWlimitssizerinfmaxfun(_DifferentialEvolutionSolver__scale_arg1fabs(_DifferentialEvolutionSolver__scale_arg2errstate._DifferentialEvolutionSolver__recip_scale_arg2parameter_countr random_number_generator broadcast_toasarrayboolcopyceilfloor nextafterr count_nonzeromaxnum_population_memberspopulation_shape_nfevstrinit_population_lhsintlog2init_population_qmcinit_population_random,_DifferentialEvolutionSolver__init_error_msginit_population_array_unscale_parameters populationr(_wrapped_constraintsappend_ConstraintWrapperrXsum num_constrtotal_constraintszerosconstraint_violationonesfeasiblearange_random_population_indexr#)!selfr,r-rrrrrrrr rr"r#r!r$r%r&r'r(r)rrrYrrnlbnubebeb_countn_s x0_scaledcs! r0__init__z$DifferentialEvolutionSolver.__init__sd H    '!(t~~h/G!HD  ** *!(t/@/@/J!KD FG G  &x1IJ   0 0%DN$ a#A; 4DK KK   &3#%T40  ff %((#4VYY5;YY58^$E*/012 K ((69;;DK GGDKK #q (r{{4;;/0%& & ?G >VVF  4;;q>DKKN#BCGGDKKNT[[^$CD [[ ) O'($*;*;&;D #MND # #R[[1H1H%I$I J  O "wwt{{A6'9#'>$ 66+ //$$K**[$7KWWT[[)FBB"B{Or+6;;=!"<==,,r+4bff=C,,r+4rvvg>C*D /2DKK4+++ ,/2DKK4+++ ,$D [[^t{{1~ -##B''* c!T11H<= =' #"&!00B@ISY_5::< I"+DOOA '$&! ; *! ))00&q$&&1  #;7)D %"$#'#<#< =aQ\\ =" %'HHd.I.I1-M$N! ; ;TB )+ $2M2M(N% a O OP >s Ab>b%b"c>|j}d|jz }||j|jzt j dd|jdddtj fz}t j||_t|jD]>}|jt|j}|||f|jdd|f<@t j|jtj|_d|_y)z Initializes the population with Latin Hypercube Sampling. Latin Hypercube Sampling ensures that each parameter is uniformly sampled over its range. rfrrgF)endpointNr)rruniformrrUlinspacenewaxis zeros_likerranger permutationfullrpopulation_energiesr)rr segsizesamplesjorders r0rz/DifferentialEvolutionSolver.init_population_lhss ** 333S[[d.C.C[DD[[R)D)D*/112BJJ@@--0t++, 6AOOE$*E*E$FGE$+E1H$5DOOAqD ! 6 $&774+F+F+-66$3  rZcddlm}|j}|dk(r|j|j|}n[|dk(r|j |j|}n8|dk(r|j |j|}nt|j|j|j|_ tj|jtj|_d|_y) aRInitializes 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)drrbrd)nN) scipy.statsrrLatinHypercuberSobolHaltonrnrrerrrUrrrr)rrcrr samplers r0rz/DifferentialEvolutionSolver.init_population_qmcs $** ) )((4+?+?c(JG 7 "ii$"6"6SiAG 8 #jj4#7#7cjBGT223 3!..4+F+F.G$&774+F+F+-66$3  rZc|j}|j|j|_t j |j tj|_d|_ y)z Initializes the population at random. This type of initialization can possess clustering, Latin Hypercube sampling is generally better. rrN) rrrrrUrrrrr)rr s r0rz2DifferentialEvolutionSolver.init_population_random(sR **++4+@+@+A$&774+F+F+-66$3  rZcLtj|tj}tj|ddks4|jd|j k7st |jdk7r tdtj|j|dd|_ tj|jd|_ |j|j f|_ tj|jtj|_d|_y)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\rrarJrPzEThe population supplied needs to have shape (S, len(x)), where S > 4.N)rUrfloat64rshaperr{rncliprrrrrrrr)rr$popns r0rz1DifferentialEvolutionSolver.init_population_array7szz$bjj1 GGD! q  1 !5!55DJJ1$:; ;''$":":4"@!QG&(ggdooq&A#!%!|j|jdS)z3 The best solution from the solver r)_scale_parametersrrs r0rXzDifferentialEvolutionSolver.xZs %%dooa&899rZc8tjtj|jrtjStj |jtj tj|jtzz S)zb The standard deviation of the population energies divided by their mean. ) rUrwisinfrrstdabsmean_MACHEPSrs r0 convergencez'DifferentialEvolutionSolver.convergenceasf 66"((4334 566Mt//0 8 89:XEG HrZc@tjtj|jrytj|j|j |j tjtj|jzzkS)z: Return True if the solver has converged. F) rUrwrrrr%rrrrs r0 convergedz%DifferentialEvolutionSolver.convergedlsq 66"((4334 5t//0 266"''$*B*B"CDDEE FrZc d\}}td}tjtjjrwj j \__jj jjj<jtdjdzD]} tj"rt%d|djd j&rYj(j*t,zz }j/|d }||_ t1j'|}|rd }|sj3sn td }d}j/|||}j4rntjj6sNtj8j6r@j:j6}}|j<||d |f<|j<||d|f<d} j>rQd} jA|j<} tj8| dkDrtCjDdtFdj"rt%d| dtIfdtjJ|j<| j:jLjN} xj| jPz c_j|_(| jR|jRkr| jTrtj| j<j:dkrtjj:d | j<krt| jR|_)| j<|_| jV|_+| jRjd <jY| j<j d <j>rj>Dcgc]}|j[|j<c}|_.tj^tj`|j\|_1|jb|_2|jdd kDrd|_*d|jd|_3|S#t$rEd}jj kDr td}njj k(rd}YwxYw#t$rd}YwxYwcc}w)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`. )rFsuccessrJTmaxfevz8Maximum number of function evaluations has been reached.zdifferential_evolution step z: f(x)= rz in progress)nitmessagez&callback function requested stop earlyr)rr warning_flagzL-BFGS-Bz trust-constrrgzdifferential evolution didn't find a solution satisfying the constraints, attempting to polish from the least infeasible solutionrPrQzPolishing solution with ''cztjjtj|dS)Nr)listrsr,rU atleast_2d)rXrs r0z3DifferentialEvolutionSolver.solve..s0 $T%5%5diiqAQ%R STU VrZ)methodr-r(Fz7The solution does not satisfy the constraints, MAXCV = )4r rUrurr#_calculate_population_feasibilitiesrrr_calculate_population_energies_promote_lowest_energyrrnext StopIterationrrr#printr"rrr_resultrrr!rrwrrXr_constraint_violation_fnrprqrrrrrWr(nfevfunrjacr violationconstrr concatenateconstr_violationmaxcvr) rrrstatus_messagerres DE_resultrr polish_methodrresults ` r0r+z!DifferentialEvolutionSolver.solvewso(%\(3 66"((4334 588I 5DM44 33OODMM24  $ $T]] 3  ' ' )DLL1,-$ C T yy4SE:221568}}HH 0 08 ;<llsMlB"#(#' c(:#;L %MNt~~/A$ F-Y7NLLL^,!  ;;rvvd&6&67vvd&&''+kk43C3C )2[)Aq+~&)2[)Aq+~&&M(( . #'#@#@#M 66*R/0MM#8#.! = yy1-BCW ggikk2%2%)[[]]*.*:*: VXX56 & $hh & .4jj((+%)%=%=fhh%G"  $ $%)%>%> @ !!" IKK 8 @I )+y//0*2I &'88IO"$) !&==F__NZZ4;;.';N (%(#'L(D @s+ ST):"T;A T&%T&) T87T8c r|jdd}|jdd}|jdd}t|j|jd|j|||du|j |j |j}|jr|jDcgc]}|j|jc}|_ tjtj|j|_ |j|_|jdkDrd|_|Scc}w)NrrrFrT)rXrrrrrrr)getrrXrrrrrrrrUrrrrr)rkwdsrrrrrs r0rz#DifferentialEvolutionSolver._resultshhud#((9d+xx6 ff((+!---doo> $ 8 8    $ $&*&?&?A!"[[2AFM&(ffR^^FMM-J&KF #!22FL||a!& As*"D4ctj|d}t||j|jz }tj |tj }|j|} t|j|j|d|}tj|}|j|k7r"|jr tdtd||d||jr|xjdz c_|S|xj|z c_|S#ttf$r}td|d}~wwxYw)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),)`` rzzThe 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)rUrminrrrrrrrsr,squeeze TypeErrorrn RuntimeErrorr)rr num_membersSenergiesparameters_pop calc_energieses r0rz:DifferentialEvolutionSolver._calculate_population_energiess/$ggj!,   T[[4::5 677;/// ;    N1Q,?@MJJ}5M    ""$;<<JK K%1 ?? JJ!OJ JJ!OJ-:& P  s0=DD=, D88D=cPtj|j}||j}|jr(tj |j |}||}n4tj tj|jd}|j |dg|j d|g<|j|dgddf|jd|gddf<|j|dg|jd|g<|j|dgddf|jd|gddf<y)NrJaxisr) rUrrrrargminrrrr)ridxfeasible_solutionsidx_tls r0rz2DifferentialEvolutionSolver._promote_lowest_energyVs ii334 /  " "IId667IJKE"5)A "&&!:!:CDA+/+C+CQF+K  !Q(%)__aVQY%?A " $ q!f 5 q!f !!1a&!), !!1a&!),rZc tj||jz}tj||jf}d}|j D]}|j |jj}|jd|jk7s|dkDr|jd|k7r tdtj|||jf}||dd|||jzf<||jz }|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)). rrJMAn 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) rUrrrrrrrWrrr reshape)rrXr _outoffsetconrs r0rz4DifferentialEvolutionSolver._constraint_violation_fnjs* GGAJ$.. .xxD2234,, %C  acc"$$Awwr{cnn,Q1771:?"$9:: 1q#..12A67DF6CNN222 3 cnn $F? %B rZctj|d}|js1tj|ttj |dffS|j |}|jr%tj|j|}n;tj|Dcgc]}|j|c}}|dddf}tj|ddkD}||fScc}w)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. rrJNr) rUrrrrrrrrxrr)rrr r rrXrs r0rz?DifferentialEvolutionSolver._calculate_population_feasibilitiess$ggj!, ((77;-rxxa8H/II I// ; ??#%88--n=$ $&886D-F12.2-J-J1-M-F$G $81#= VV0q9A=>----Fs)C0c|SrTrDrs r0r[z$DifferentialEvolutionSolver.__iter__ rZc|SrTrDrs r0 __enter__z%DifferentialEvolutionSolver.__enter__r!rZc4|jj|SrT)rs__exit__)rrs r0r%z$DifferentialEvolutionSolver.__exit__s(t(($//rZcL|r|r||kS|r|sy|s||kjryy)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)ru)r energy_trialfeasible_trialcv_trial energy_orig feasible_origcv_origs r0 _accept_trialz)DifferentialEvolutionSolver._accept_trials8D ^;. . MX%8$=$=$?rZc $ tjtj|jrw|j |j \|_|_|j|j |j |j|j <|j|j;|jj|jd|jd|_ |jdk(rt|j D]}|j"|j$kDrt&|j)|}|j+||j-|}|j.rd|j1|}d}tj2}tj4|dkDsgd}|j7|}|xj"dz c_n>d}tj8dg}|j7|}|xj"dz c_|j;||||j||j ||j|sC||j |<tj<||j|<||j |<||j|<|j;||||jd|j d|jds|jn|jdk(r|j"|j$k\rt&|j?tj@|j }|j+||j |\}}tjB|j tj2}|j||||<tE||||j|j |jD cgc]} |j:| } } tjF| } tjH| ddtjJf||j |_tjH| ||j|_tjH| ||j |_tjH| ddtjJf||j|_|j|jL|jdfScc} w) 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. NrrJrMFTrgrO)'rUrurrrrrrrrryrrrtrorrrrr_mutate_ensure_constraintrrrrrr,rr-r _mutate_manyrrziprxwhererrX) r candidatetrial parameterscvrenergy trial_poptrial_energiesvallocs r0__next__z$DifferentialEvolutionSolver.__next__sQ 66"((4334 588I 5DM44 33OODMM24  $ $T]] 3  ' ' ) ;; "55==dkk!n>Bkk!nNDJ >>[ ("4#>#>?- 6 :: +'' Y/''."33E: ,,66zBB$HVVF66":>#'!%:!6 a #Ht,B!YYz2FJJ!OJ%%fh&*&>&>y&I&*mmI&>&*&?&? &JL27DOOI.:<**V:LD,,Y7/7DMM),;=D--i8))&(B*.*B*B1*E*.--*:*.*C*CA*FH335[- 6^^^z )zzT[[(##)) $556I  # #I . CCINLHbWWT%@%@"&&IN(,'J'J(#(%N8 $ ~xT5M5M}}d&?&?AB%4%%s+BCB((3-C hhs1bjj='9'0'+8DO(*xx0>040H0H(JD $HHS%-%)]]4DM)+Q ]1C13151J1J)LD %  ' ' )vvt//222+Bs3T c |j|dz |jzz}tj|jrEtj |j|j }tj||||<|S)z2Scale from a number between 0 and 1 to parameters.rI)rrrUrrrrround)rr5scaledis r0rz-DifferentialEvolutionSolver._scale_parameterssl""eckT5F5F%FF  D,, - 0 0&,,?A+F1I rZc@||jz |jzdzS)z2Scale from parameters to a number between 0 and 1.rI)rr)rr6s r0rz/DifferentialEvolutionSolver._unscale_parameterss#T...$2I2IICOOrZctj|dkD|dk}tj|x}r |jj |||<yy)z0Make sure the parameters lie between the limits.rJrrN)rU bitwise_orrrr)rr5maskoobs r0r0z.DifferentialEvolutionSolver._ensure_constraintsR}}UQY 2""4( (3 (66>>C>HE$K )rZc |j}d}|j|j}tt j |s9|j |||}|j |jfk7r{t||j d}t j|Dcgc]}|j |||c}t}|j ||jfk7r t||j|Scc}w)Nzqstrategy must have signature f(candidate: int, population: np.ndarray, rng=None) returning an array of shape (N,))r rr\) rrrr{rUrrrr rxr^r)rr4r msg _populationr5r rs r0_mutate_customz*DifferentialEvolutionSolver._mutate_customs** # ,,T__= 288I&'MM)[cMBE{{t3355"3''"AHHAJKAq+37KE{{q$"6"677"3''''.. Ls#Dc |j}t|}t|jr|j |St j |j|}t j|Dcgc]}|j|dc}}|jdvr|j||}n|j|}t||j|}|j||jf} | |jk} |j|jvr8t j |} d| | || f<t j"| ||}|S|j|j$vrqd| d<t'|D]\} d} || } | |jks| | | fs"|| | f|| | f<| dz|jz} | dz } | |jksU| | | fr;^|Sycc}w) z2Create trial vectors based on a mutation strategy.rarAr:rT).rrrJN)rr{rirrJrUrrrx_select_samplesrlrrrr}rjrr3rmr) r candidatesr r r5rrbprime fill_point crossoversrAr init_fills r0r1z(DifferentialEvolutionSolver._mutate_manys**  O DMM "&&z2 2 34(( K1D00A6KL ==F F'' G*>&?[@ $"="== ==DNN *  ! A+/Jq*Q-' (HHZ7EL ]]d// /!%Jv 1X &qM 4///Jq!t4D*0I*>E!Y,'!*Q$2F2F FIFA4///Jq!t4D L0)Ls3G$c|j}t|jr|j|St ||j }|j |d}tj|j|}|jdvr|j||}n|j|}|j|j }||jk}|j|jvrd||<tj|||}|S|j|jvrQd}d|d<||j kr9||r4||||<|dz|j z}|dz }||j kr||r4|Sy)z3Create a trial vector based on a mutation strategy.rarLrTrrJN)rrirrJrrrMrUrrrlrr}rjr3rm) rr4r rPrr5rOrQrAs r0r/z#DifferentialEvolutionSolver._mutateso** DMM "&&y1 1!#t';';< &&y!4 23 ==F F'' 7;F''0F[[d&:&:[; $"="== ==DNN * &*Jz "HHZ7EL ]]d// /A JqMd***z!}$*:$6j!(1n0D0DD Qd***z!} L0rZc|dddfj\}}|jd|j|j||j|z zzS)zbest1bin, best1exp.NrPrrWrrt)rrr0r1s r0r2z"DifferentialEvolutionSolver._best1s[ bqb!##B"TZZ$tr'::&<< =rZc|dddfj\}}}|j||j|j||j|z zzS)zrand1bin, rand1exp.NrU)rrrVrWr2s r0r7z"DifferentialEvolutionSolver._rand1s[S"1"W%'' B#djj$tr'::'<< =rZc|dddfj\}}}tj|j|}||j|jd|z zz }||j|j||j|z zz }|S)zrandtobest1bin, randtobest1exp.NrYr)rWrUrrrt)rrrVrWrZrOs r0r3z(DifferentialEvolutionSolver._randtobest1sS"1"W%'' B,-$** 2V ;<<$** 3 $ 3!45 5 rZc|dddfj\}}|j||j|jd|j|z |j|z|j|z zz}|S)z$currenttobest1bin, currenttobest1exp.NrPrrU)rr4rrVrWrOs r0r4z+DifferentialEvolutionSolver._currenttobest1sbqb!##B//),tzz??1% (BB??2&')-)<=0>> rZc|dddfj\}}}}|jd|j|j||j|z|j|z |j|z zz}|S)zbest2bin, best2exp.NrrU)rrrVrWrZr3rOs r0r5z"DifferentialEvolutionSolver._best2s bqb)++BB//!$tzz??2&)<<??2&')-)<=(>> rZc|dddfj\}}}}}|j||j|j||j|z|j|z |j|z zz}|S)zrand2bin, rand2exp.NrarU)rrrVrWrZr_r4rOs r0r6z"DifferentialEvolutionSolver._rand2(s$S"1"W-//BB//"% ??2&)<<??2&')-)<=)>> rZc|jj|j|jd|dz}|||k7d|S)z obtain random integers from range(self.num_population_members), without replacement. You can't have the original candidate either. NrJ)rshuffler)rr4number_samplesidxss r0rMz+DifferentialEvolutionSolver._select_samples1sM $$,,T-J-JK,,-@nq.@ADI%&77rZ)*__name__ __module__ __qualname____doc__rjrmrrUrrrrrrpropertyrXrrr+rrrrrr[r#r%r-r=rrr0rJr1r/r2r7r3r4r5r6rMrDrZr0r*r*sZk\&7%%% 'I !) (&4): ( ( *LM+-$dBHCTE$&Qt ` EI! `D$L"H !F:: HH FM^25n.(9v+.Z0+Z{3zPI /.'R$L== 8rZr*c"eZdZdZdZdZdZy)ra 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. ct|_ttrfd}n5ttrfd}nttrd}n t d||_tjjt}tjjt}tj|}||}|jx|_ }|j|_|jdk(rtj ||}|jdk(rtj ||}||f|_y)Ncvtj|}tjj|SrT)rUrrVr)rX constraints r0rz(_ConstraintWrapper.__init__..fun^s(JJqM}}Z^^A%677rZc tjr j}ntjj}|j |}|j dk(r+|j dk(rtj |dddf}|S)NrJrPr)rArUrdotndimr)rXrprrns r0rz(_ConstraintWrapper.__init__..funbskJLL)" A jll3AeeAh 66Q;388q=**S/!Q$/C rZc,tj|SrT)rUr)rXs r0rz(_ConstraintWrapper.__init__..funuszz!}$rZz*`constraint` of an unknown type is passed.r\r)rnr~rrrrnrrUrrr^rrrrrrresizer-)rrnr)rrrf0ms ` r0rz_ConstraintWrapper.__init__Zs$ j"5 6 8 $4 5 $ F + %IJ J ZZ U 3 ZZ U 3 ZZ^W gg%!!ww 77a<2q!B 77a<2q!B2h rZcJtj|j|SrT)rUrVr)rrXs r0__call__z_ConstraintWrapper.__call__s}}TXXa[))rZch|jtj|} tj|jd|j z d}tj|j |jdz d}||zj }|S#t $r}td|d}~wwxYw)aHow 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. rrJrN)rrUrmaximumr-rWrnr )rrXev excess_lb excess_ubrvs r0rz_ConstraintWrapper.violations"XXbjjm $ = 4;;q>BDD#8!rs3PPD@@' $ $ 288BJJ  # #F+;E9=EI=ACN9= _ (, _,_D}8}8@*wwrZ