B
    î&]\ùª  ã               @   s¦   d Z ddlmZmZmZ ddlZddlZddlm	Z	m
Z
 ddlmZ ddlmZmZ ddlmZmZ dgZe ej¡jZddd„ZG dd„ deƒZG dd„ deƒZdS )zn
differential_evolution: The differential evolution global optimization algorithm
Added by Andrew Nelson 2014
é    )ÚdivisionÚprint_functionÚabsolute_importN)ÚOptimizeResultÚminimize)Ú_status_message)Úcheck_random_stateÚ
MapWrapper)ÚxrangeÚstring_typesÚdifferential_evolution© Úbest1binéè  é   ç{®Gáz„?©g      à?é   çffffffæ?FTÚlatinhypercubeÚ	immediater   c             C   sB   t | |||||||||	||
|||||d}| ¡ }W dQ R X |S )a¢-  Finds the global minimum of a multivariate function.

    Differential Evolution is stochastic in nature (does not use gradient
    methods) to find the minimium, 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 [1]_.

    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.
    bounds : sequence
        Bounds for variables.  ``(min, max)`` pairs for each element in ``x``,
        defining the lower and upper bounds for the optimizing argument of
        `func`. It is required to have ``len(bounds) == len(x)``.
        ``len(bounds)`` is used to determine the number of parameters in ``x``.
    args : tuple, optional
        Any additional fixed parameters needed to
        completely specify the objective function.
    strategy : str, optional
        The differential evolution strategy to use. Should be one of:

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

        The default is 'best1bin'.
    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 * len(x)``
    popsize : int, optional
        A multiplier for setting the total population size.  The population has
        ``popsize * len(x)`` individuals (unless the initial population is
        supplied via the `init` keyword).
    tol : float, optional
        Relative 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.
    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.
    seed : int or `np.random.RandomState`, optional
        If `seed` is not specified the `np.RandomState` singleton is used.
        If `seed` is an int, a new `np.random.RandomState` instance is used,
        seeded with seed.
        If `seed` is already a `np.random.RandomState instance`, then that
        `np.random.RandomState` instance is used.
        Specify `seed` for repeatable minimizations.
    disp : bool, optional
        Display status messages
    callback : callable, `callback(xk, convergence=val)`, optional
        A function to follow the progress of the minimization. ``xk`` is
        the current value of ``x0``. ``val`` represents the fractional
        value of the population convergence.  When ``val`` is greater than one
        the function halts. If callback returns `True`, then the minimization
        is halted (any polishing is still carried out).
    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.
    init : str or array-like, optional
        Specify which type of population initialization is performed. Should be
        one of:

            - 'latinhypercube'
            - 'random'
            - array specifying the initial population. The array should have
              shape ``(M, len(x))``, where len(x) 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. '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 subset 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, and
        the `workers` keyword 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``.
        Requires that `func` be pickleable.

        .. versionadded:: 1.2.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 and
        ``message`` which describes the cause of the termination. 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.

    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 [2]_ 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:`b_0`,
    so far:

    .. math::

        b' = b_0 + mutation * (population[rand0] - population[rand1])

    A trial vector is then constructed. Starting with a randomly chosen 'i'th
    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.
    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'``.

    .. versionadded:: 0.15.0

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

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

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

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

    >>> from scipy.optimize import differential_evolution
    >>> import numpy as np
    >>> 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)
    >>> result.x, result.fun
    (array([ 0.,  0.]), 4.4408920985006262e-16)

    References
    ----------
    .. [1] 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.
    .. [2] http://www1.icsi.berkeley.edu/~storn/code.html
    .. [3] http://en.wikipedia.org/wiki/Differential_evolution
    .. [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
    )ÚargsÚstrategyÚmaxiterÚpopsizeÚtolÚmutationÚrecombinationÚseedÚpolishÚcallbackÚdispÚinitÚatolÚupdatingÚworkersN)ÚDifferentialEvolutionSolverÚsolve)ÚfuncÚboundsr   r   r   r   r   r   r   r   r    r!   r   r"   r#   r$   r%   ZsolverZretr   r   úDlib/python3.7/site-packages/scipy/optimize/_differentialevolution.pyr      s     r
c               @   s8  e Zd ZdZdddddddœZddddddd	œZd
Zddddddddejdddddddfdd„Z	dd„ Z
dd„ Zdd „ Zed!d"„ ƒZed#d$„ ƒZd%d&„ Zd'd(„ Zd)d*„ Zd+d,„ Zd-d.„ Zd/d0„ Zd1d2„ Zd3d4„ Zd5d6„ ZeZd7d8„ Zd9d:„ Zd;d<„ Zd=d>„ Zd?d@„ ZdAdB„ ZdCdD„ Z dEdF„ Z!dGdH„ Z"dIdJ„ Z#dKdL„ Z$dS )Mr&   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.
    bounds : sequence
        Bounds for variables.  ``(min, max)`` pairs for each element in ``x``,
        defining the lower and upper bounds for the optimizing argument of
        `func`. It is required to have ``len(bounds) == len(x)``.
        ``len(bounds)`` is used to determine the number of parameters in ``x``.
    args : tuple, optional
        Any additional fixed parameters needed to
        completely specify the objective function.
    strategy : str, optional
        The differential evolution strategy to use. Should be one of:

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

        The default is 'best1bin'

    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 * len(x)``
    popsize : int, optional
        A multiplier for setting the total population size.  The population has
        ``popsize * len(x)`` individuals (unless the initial population is
        supplied via the `init` keyword).
    tol : float, optional
        Relative 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.
    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.
    seed : int or `np.random.RandomState`, optional
        If `seed` is not specified the `np.random.RandomState` singleton is
        used.
        If `seed` is an int, a new `np.random.RandomState` instance is used,
        seeded with `seed`.
        If `seed` is already a `np.random.RandomState` instance, then that
        `np.random.RandomState` instance is used.
        Specify `seed` for repeatable minimizations.
    disp : bool, optional
        Display status messages
    callback : callable, `callback(xk, convergence=val)`, optional
        A function to follow the progress of the minimization. ``xk`` is
        the current value of ``x0``. ``val`` represents the fractional
        value of the population convergence.  When ``val`` is greater than one
        the function halts. If callback returns `True`, then the minimization
        is halted (any polishing is still carried out).
    polish : bool, optional
        If True, then `scipy.optimize.minimize` with the `L-BFGS-B` method
        is used to polish the best population member at the end. This requires
        a few more function evaluations.
    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'
            - 'random'
            - array specifying the initial population. The array should have
              shape ``(M, len(x))``, where len(x) 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. '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. 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, and the
        `workers` keyword 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.

    Ú_best1Ú_randtobest1Ú_currenttobest1Ú_best2Ú_rand2Ú_rand1)r   Zrandtobest1binÚcurrenttobest1binZbest2binZrand2binZrand1bin)Zbest1expZrand1expZrandtobest1expÚcurrenttobest1expZbest2expZrand2expz™The population initialization method must be one of 'latinhypercube' or 'random', or an array of shape (M, N) where N is the number of parameters and M>5r   r   iè  r   g{®Gáz„?)g      à?r   gffffffæ?NFTr   r   r   r   c             C   sn  || j krt| | j | ƒ| _n&|| jkr<t| | j| ƒ| _ntdƒ‚|| _|| _|| _|dkrd|| _|dkr†|dkr†t	 
dt¡ d| _t|ƒ| _|| | _| _|| _t t |¡¡rÜt t |¡dk¡sÜt t |¡dk ¡rätd	ƒ‚d | _t|d
ƒr t|ƒdkr |d |d g| _| j ¡  |	| _t||ƒ| _|| _tj|ddj| _t  | jd¡dksrt t | j¡¡sztdƒ‚|d krˆd}|| _!|d kržtj"}|| _#d| jd | jd   | _$t %| jd | jd  ¡| _&t  | jd¡| _'t(|
ƒ| _)t*d|| j' ƒ| _+| j+| j'f| _,d| _-t.|t/ƒrZ|dkr:|  0¡  n|dkrN|  1¡  n
t| j2ƒ‚n
|  3|¡ || _4d S )Nz'Please select a valid mutation strategy)r   Údeferredr   r   zhdifferential_evolution: the 'workers' keyword has overridden updating='immediate' to updating='deferred'r3   é   r   z€The 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__Úfloat)ZdtypezWbounds should be a sequence containing real valued (min, max) pairs for each value in xiè  g      à?é   r   Zrandom)5Ú	_binomialÚgetattrÚmutation_funcÚ_exponentialÚ
ValueErrorr   r    r   Ú	_updatingÚwarningsÚwarnÚUserWarningr	   Ú_mapwrapperr   r#   ÚscaleÚnpÚallZisfiniteÚanyÚarrayÚditherÚhasattrÚlenÚsortÚcross_over_probabilityÚ_FunctionWrapperr(   r   ÚTÚlimitsÚsizer   ÚinfÚmaxfunÚ(_DifferentialEvolutionSolver__scale_arg1ZfabsÚ(_DifferentialEvolutionSolver__scale_arg2Úparameter_countr   Úrandom_number_generatorÚmaxÚnum_population_membersÚpopulation_shapeÚ_nfevÚ
isinstancer   Úinit_population_lhsÚinit_population_randomÚ,_DifferentialEvolutionSolver__init_error_msgÚinit_population_arrayr!   )Úselfr(   r)   r   r   r   r   r   r   r   r   rQ   r    r!   r   r"   r#   r$   r%   r   r   r*   Ú__init__¬  sl    












z$DifferentialEvolutionSolver.__init__c             C   s¨   | j }d| j }|| | j¡ tjdd| jdddd…tjf  }t |¡| _x<t	| j
ƒD ].}| t	| jƒ¡}|||f | jdd…|f< qZW t | jtj¡| _d| _dS )zµ
        Initializes the population with Latin Hypercube Sampling.
        Latin Hypercube Sampling ensures that each parameter is uniformly
        sampled over its range.
        g      ð?g        F)ZendpointNr   )rU   rW   Úrandom_samplerX   rC   ZlinspaceÚnewaxisZ
zeros_likeÚ
populationÚrangerT   ZpermutationÚfullrP   Úpopulation_energiesrY   )r_   ÚrngZsegsizeÚsamplesÚjÚorderr   r   r*   r[     s    

z/DifferentialEvolutionSolver.init_population_lhsc             C   s0   | j }| | j¡| _t | jtj¡| _d| _	dS )z¢
        Initialises the population at random.  This type of initialization
        can possess clustering, Latin Hypercube sampling is generally better.
        r   N)
rU   ra   rX   rc   rC   re   rW   rP   rf   rY   )r_   rg   r   r   r*   r\   =  s
    
z2DifferentialEvolutionSolver.init_population_randomc             C   s’   t  |¡}t  |d¡dk s8|jd | jks8t|jƒdkr@tdƒ‚t  |  |¡dd¡| _	t  | j	d¡| _
| j
| jf| _t  | j
¡t j | _d| _dS )ar  
        Initialises the population with a user specified population.

        Parameters
        ----------
        init : np.ndarray
            Array specifying subset of the initial population. The array should
            have shape (M, len(x)), where len(x) is the number of parameters.
            The population is clipped to the lower and upper bounds.
        r   r7   r   r4   zEThe population supplied needs to have shape (M, len(x)), where M > 4.N)rC   ZasfarrayrO   ÚshaperT   rI   r<   ZclipÚ_unscale_parametersrc   rW   rX   ZonesrP   rf   rY   )r_   r"   Zpopnr   r   r*   r^   L  s    



z1DifferentialEvolutionSolver.init_population_arrayc             C   s   |   | jd ¡S )z3
        The best solution from the solver
        r   )Ú_scale_parametersrc   )r_   r   r   r*   Úxo  s    zDifferentialEvolutionSolver.xc             C   s:   t  t  | j¡¡rt jS t  | j¡t  t  | j¡t ¡ S )zb
        The standard deviation of the population energies divided by their
        mean.
        )	rC   rE   Úisinfrf   rP   ÚstdÚabsÚmeanÚ_MACHEPS)r_   r   r   r*   Úconvergencev  s    
z'DifferentialEvolutionSolver.convergencec             C   s*   t  | j¡| j| jt  t  | j¡¡  kS )z:
        Return True if the solver has converged.
        )rC   rp   rf   r#   r   rq   rr   )r_   r   r   r*   Ú	converged  s    
z%DifferentialEvolutionSolver.convergedc          	   C   s  d\}}t d }t t | j¡¡r@|  | j¡| jdd…< |  ¡  xtd| j	d ƒD ]ø}yt
| ƒ W n@ tk
r¤   d}| j| jkrŽt d }n| j| jkržd}P Y nX | jrÂtd|| jd	 f ƒ | j}| jrü| j|  | jd	 ¡| j| d
dkrüd}d}P t t | j¡¡rd}n*t | j¡| j| jt t | j¡¡  k}|sJ|rTP qTW t d }d}t| j| jd	 | j|||dk	d}| jr t| jt |j¡d| jj d}|  j|j!7  _| j|_!|j"|j"k r |j"|_"|j|_|j#|_#|j"| jd	< |  $|j¡| jd	< |S )a  
        Runs the DifferentialEvolutionSolver.

        Returns
        -------
        res : OptimizeResult
            The optimization result represented as a ``OptimizeResult`` object.
            Important attributes are: ``x`` the solution array, ``success`` a
            Boolean flag indicating if the optimizer exited successfully and
            ``message`` which describes the cause of the termination. 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.
        )r   FÚsuccessNr   TZmaxfevz8Maximum number of function evaluations has been reached.z(differential_evolution step %d: f(x)= %gr   )rt   z8callback function requested stop early by returning TrueFr   )rn   ÚfunÚnfevÚnitÚmessagerv   zL-BFGS-B)Úmethodr)   )%r   rC   rD   ro   rf   Ú_calculate_population_energiesrc   Ú_promote_lowest_energyr
   r   ÚnextÚStopIterationrY   rQ   r!   Úprintrt   r    rm   r   rE   rp   r#   rq   rr   r   rn   r   r   r(   ÚcopyrN   rM   rx   rw   Zjacrl   )r_   ry   Zwarning_flagZstatus_messagert   ZintolZ	DE_resultÚresultr   r   r*   r'   ‰  sr    



z!DifferentialEvolutionSolver.solvec          	   C   s’   t  |d¡}t|| j| ƒ}t  |t j¡}|  |¡}y*t|  | j	|d|… ¡ƒ}||d|…< W n  t
tfk
r~   tdƒ‚Y nX |  j|7  _|S )a›  
        Calculate the energies of all the population members at the same time.

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

        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')rC   rO   ÚminrQ   re   rP   rm   ÚlistrA   r(   Ú	TypeErrorr<   ÚRuntimeErrorrY   )r_   rc   Znum_membersZnfevsZenergiesZparameters_popZcalc_energiesr   r   r*   r|   ì  s    

z:DifferentialEvolutionSolver._calculate_population_energiesc             C   sP   t  | j¡}| j|dg | jd|g< | j|dgd d …f | jd|gd d …f< d S )Nr   )rC   Zargminrf   rc   )r_   Úlr   r   r*   r}     s    z2DifferentialEvolutionSolver._promote_lowest_energyc             C   s   | S )Nr   )r_   r   r   r*   r5     s    z$DifferentialEvolutionSolver.__iter__c             C   s   | S )Nr   )r_   r   r   r*   Ú	__enter__  s    z%DifferentialEvolutionSolver.__enter__c             G   s   | j  ¡  d S )N)rA   Úclose)r_   r   r   r   r*   Ú__exit__"  s    z$DifferentialEvolutionSolver.__exit__c             C   s   | j  ¡  d S )N)rA   r‰   )r_   r   r   r*   Ú__del__&  s    z#DifferentialEvolutionSolver.__del__c                s¨  t  t  ˆ j¡¡r0ˆ  ˆ j¡ˆ jdd…< ˆ  ¡  ˆ jdk	rdˆ j 	¡ ˆ jd ˆ jd   ˆ jd  ˆ _
ˆ jdkrxtˆ jƒD ]‚}ˆ jˆ jkrt‚ˆ  |¡}ˆ  |¡ ˆ  |¡}ˆ  |¡}ˆ  jd7  _|ˆ j| k r||ˆ j|< |ˆ j|< |ˆ jd k r|ˆ  ¡  q|W n”ˆ jdkr˜ˆ jˆ jkr"t‚t  ‡ fdd„tˆ jƒD ƒ¡}ˆ  |¡ ˆ  |¡}|ˆ jk }t  |dd…t jf |ˆ j¡ˆ _t  ||ˆ j¡ˆ _ˆ  ¡  ˆ jˆ jd fS )zÿ
        Evolve the population by a single generation

        Returns
        -------
        x : ndarray
            The best solution from the solver.
        fun : float
            Value of objective function obtained from the best solution.
        Nr   r   r   r3   c                s   g | ]}ˆ   |¡‘qS r   )Ú_mutate)Ú.0Úi)r_   r   r*   ú
<listcomp>f  s    z8DifferentialEvolutionSolver.__next__.<locals>.<listcomp>)rC   rD   ro   rf   r|   rc   r}   rG   rU   ÚrandrB   r=   rd   rW   rY   rQ   r   rŒ   Ú_ensure_constraintrm   r(   rF   Úwhererb   rn   )r_   Ú	candidateÚtrialÚ
parametersZenergyZ	trial_popZtrial_energiesZlocr   )r_   r*   Ú__next__*  sJ    
"










z$DifferentialEvolutionSolver.__next__c             C   s   | j |d | j  S )z2Scale from a number between 0 and 1 to parameters.g      à?)rR   rS   )r_   r”   r   r   r*   rm     s    z-DifferentialEvolutionSolver._scale_parametersc             C   s   || j  | j d S )z2Scale from parameters to a number between 0 and 1.g      à?)rR   rS   )r_   r•   r   r   r*   rl   ƒ  s    z/DifferentialEvolutionSolver._unscale_parametersc             C   s0   t  |dk|dk B ¡}| j |d j¡||< dS )z0Make sure the parameters lie between the limits.r   r   N)rC   r’   rU   r   rO   )r_   r”   Úmaskr   r   r*   r‘   ‡  s    z.DifferentialEvolutionSolver._ensure_constraintc             C   sê   t  | j| ¡}| j}| d| j¡}| jdkrD|  ||  |d¡¡}n|  |  |d¡¡}| j| j	kr’| 
| j¡}|| jk }d||< t  |||¡}|S | j| jkræd}x>|| jk rà| 
¡ | jk rà|| ||< |d | j }|d7 }q¤W |S dS )z3Create a trial vector based on a mutation strategy.r   )r2   r1   r7   Tr   N)rC   r   rc   rU   ZrandintrT   r   r:   Ú_select_samplesr8   r   rK   r’   r;   )r_   r“   r”   rg   Z
fill_pointÚbprimeZ
crossoversrŽ   r   r   r*   rŒ   Œ  s*    

z#DifferentialEvolutionSolver._mutatec             C   s4   |dd… \}}| j d | j| j | | j |    S )zbest1bin, best1expNr4   r   )rc   rB   )r_   rh   Úr0Úr1r   r   r*   r+   °  s    z"DifferentialEvolutionSolver._best1c             C   s6   |dd… \}}}| j | | j| j | | j |    S )zrand1bin, rand1expNé   )rc   rB   )r_   rh   rš   r›   Úr2r   r   r*   r0   ¶  s    z"DifferentialEvolutionSolver._rand1c             C   s\   |dd… \}}}t  | j| ¡}|| j| jd |  7 }|| j| j| | j|   7 }|S )zrandtobest1bin, randtobest1expNrœ   r   )rC   r   rc   rB   )r_   rh   rš   r›   r   r™   r   r   r*   r,   ¼  s    z(DifferentialEvolutionSolver._randtobest1c             C   sL   |dd… \}}| j | | j| j d | j |  | j |  | j |    }|S )z$currenttobest1bin, currenttobest1expNr4   r   )rc   rB   )r_   r“   rh   rš   r›   r™   r   r   r*   r-   Å  s    ,z+DifferentialEvolutionSolver._currenttobest1c             C   sP   |dd… \}}}}| j d | j| j | | j |  | j |  | j |    }|S )zbest2bin, best2expNé   r   )rc   rB   )r_   rh   rš   r›   r   Úr3r™   r   r   r*   r.   Í  s    ,z"DifferentialEvolutionSolver._best2c             C   sJ   |\}}}}}| j | | j| j | | j |  | j |  | j |    }|S )zrand2bin, rand2exp)rc   rB   )r_   rh   rš   r›   r   rŸ   Zr4r™   r   r   r*   r/   Ö  s    ,z"DifferentialEvolutionSolver._rand2c             C   s4   t t| jƒƒ}| |¡ | j |¡ |d|… }|S )z
        obtain random integers from range(self.num_population_members),
        without replacement.  You can't have the original candidate either.
        N)r„   rd   rW   ÚremoverU   Zshuffle)r_   r“   Znumber_samplesZidxsr   r   r*   r˜   ß  s
    
z+DifferentialEvolutionSolver._select_samples)%Ú__name__Ú
__module__Ú__qualname__Ú__doc__r8   r;   r]   rC   rP   r`   r[   r\   r^   Úpropertyrn   rt   ru   r'   r|   r}   r5   rˆ   rŠ   r‹   r–   r~   rm   rl   r‘   rŒ   r+   r0   r,   r-   r.   r/   r˜   r   r   r   r*   r&     s^    
f&#c(S$			r&   c               @   s    e Zd ZdZdd„ Zdd„ ZdS )rL   zB
    Object to wrap user cost function, allowing picklability
    c             C   s   || _ |d krg n|| _d S )N)Úfr   )r_   r¦   r   r   r   r*   r`   ï  s    z_FunctionWrapper.__init__c             C   s   | j |f| jžŽ S )N)r¦   r   )r_   rn   r   r   r*   Ú__call__ó  s    z_FunctionWrapper.__call__N)r¡   r¢   r£   r¤   r`   r§   r   r   r   r*   rL   ë  s   rL   )r   r   r   r   r   r   r   NNFTr   r   r   r   )r¤   Z
__future__r   r   r   r>   ZnumpyrC   Zscipy.optimizer   r   Zscipy.optimize.optimizer   Zscipy._lib._utilr   r	   Zscipy._lib.sixr
   r   Ú__all__ZfinfoZfloat64Zepsrs   r   Úobjectr&   rL   r   r   r   r*   Ú<module>   s.        
 }     [