Repository: scipy/scipy

Issue:
differential_evolution bug converges to wrong results in complex cases
The differential evolution does not converge correctly, and is incompatible with the original code (from algorithmic point of view) of Storn.
Storn claims that the algorithm has negligible advantage when increasing the population over 40 regardless of the number of objective function model variables. When I tried to use a population of ~60 with my problem which is quite complex (Solving Arrhenius parameters for several reactions). It converged to wrong results and the objective function was far from the correct values. While checking the code I found that the population which is used during an iteration is written during the same iteration. It creates an unacceptable bias in the direction of the currently best  result and all the population quickly converges to the same result which is wrong. In all the codes I found on the net including Storn`s code the population  used within an iteration is from previous iteration only, and the currently best result is saved in a different array designated for that purpose. at the end of the iteration the modified population is copied to the population to be used at the next iteration.
Privately fixing the code not to modify the population used in the same iteration solved the problem and the function converged correctly with the same small population. Larger populations partially "hide" the bug since it is a stochastic process and the bias becomes minor.
best1bin strategy was used. actually most o the arguments were the default ones, only maxiter, tol, callback, and disp were modified (larger maxiter and smaller tol)
I use Scipy version 0.18.1 from Anaconda distribution.

Another minor (not a bug but structural, implementation problem) problem. An attempt to use the strategy functions as generic preassigned in the constructor was made (very good), alas, not all functions had the same interface which results the need for if statement in the code, the function is not generic any more.
Attached is a fixed version of _differential_evolution.py with the bug and the second problems fixed, as I figured out. Not necessarily with the naming convention of the library.


[_differentialevolution.zip](https://github.com/scipy/scipy/files/1595085/_differentialevolution.zip)



Discussion:
There was actually another severe bug fixed. In the original class when the temporary tested  candidate created by _mutate the is better than the original one it is overridden (O.K). The problem is that if it was better than the currently best, than the 0 index population member was overridden rather than switched with the new best result (in the case where the tested candidate was not the first one in the population, but still was better than the one in the zero index). The previously best is lost as a population member and 2 copies of the new best now exist.
@yonadav Do you mind opening a pull request for this? It is not very convenient to download and setup everything from scratch let alone being able to use GitHub's review systems and so forth. 

Also if there are correctness/performance claims it is best to show the timings and results with a test suite.
There is no performance issue it is simply a bug, since it is a statistical process the bug may be obscured in many cases but it is still there. Verified against the C++ code published by Storn (one of the creators of the algorithm). I cannot publish the code for the objective function and the data-set of the experiment.
My code is just an example of a possible option to solve the problem, did not pay attention to coding conventions of the library. So my guess is that it is not a very good candidate for pull request and was given only as an algorithmic example of the solution to back up the explanation.
The code is an add-on not a must I could just leave the explanations.
If you think it is feasible for a pull request I can open one.
As for tests it should converge for a population of 40 as Storn claimed and it did after the correction for a very complex equation with 24 parameters to solve. It converged successfully for several different data-sets
The scipy version of `differential_evolution` is the variant outlined in Wormington et al., Phil. Trans. R. Soc. Lond. A (1999) 357, 2827–2848, 10.1098/rsta.1999.0469. The flowchart in fig1 outlines the optimization.
In this variant if the trial vector is better than the parameter vector then it replaces it, if it's better than the best fit vector it also replaces that - *within* the same generation. This leads to faster convergence. You are correct in saying that the code is not the same as the original Storn and Price algorithm, it's simply a variant.
Variants aren't bad if they lead to enhancements. For example, the original Storn and Price code didn't dither the mutation constant, F. However, this has been found to improve convergence behaviour, so it's probably better to have that variant.
Of course in your situation it seems that you don't want the aggressive variant. It would be relatively straightforward to add an `aggressive=True` as a keyword. If you want to turn off that feature you could supply `aggressive=False`. In that way the current behaviour is unchanged, but you'd also get what you liked.
The reference you have mentioned is not included in the documentation only Wikipedia,  Storn and Price article and Storn`s site. The C++ variant by Storn does include dithering, they do use the currently best result for the strategies which requires the best result within the same generation. However, they use the population from the previous iteration with the exception of the currently best result.
see my second comment, when a new best result it located and it is not on index 0 then both index 0 is overridden as well as the actual candidate location. I find it hard to believe that it is in the algorithm you have mentioned.
It might converge faster in simple cases but in more complex ones it drifts to a totally wrong solution unless you use a very large population. It depends on how computationally expensive  your objective function is. In a very expensive OF having twice the number of iterations but with population of 40 instead of 400 is much better.
As I mentioned before the reference you wrote is not quoted in the manual nor in the code, so I had no way to know about the variant it is based upon. 
I will stick to the variant I made which might converge slower but converges for me. The benefits of open source ....
It would be nice to have that keyword as well as adding the reference to your variant.
But still pay attention to my comment regarding the case when a best solution is located not at 0.
in that case you should switch between the previously best and the current best rather than overwrite it
I was going to reply to the second comment within the next couple of days.

Resolving patch:
diff --git a/scipy/_lib/_util.py b/scipy/_lib/_util.py
--- a/scipy/_lib/_util.py
+++ b/scipy/_lib/_util.py
@@ -6,6 +6,7 @@
 import warnings
 import numbers
 from collections import namedtuple
+from multiprocessing import Pool
 import inspect
 
 import numpy as np
@@ -337,3 +338,81 @@ def getargspec_no_self(func):
         if argspec.args[0] == 'self':
             argspec.args.pop(0)
         return argspec
+
+
+class MapWrapper(object):
+    """
+    Parallelisation wrapper for working with map-like callables, such as
+    `multiprocessing.Pool.map`.
+
+    Parameters
+    ----------
+    pool : int or map-like callable
+        If `pool` is an integer, then it specifies the number of threads to
+        use for parallelization. If ``int(pool) == 1``, then no parallel
+        processing is used and the map builtin is used.
+        If ``pool == -1``, then the pool will utilise all available CPUs.
+        If `pool` is a map-like callable that follows the same
+        calling sequence as the built-in map function, then this callable is
+        used for parallelisation.
+    """
+    def __init__(self, pool=1):
+        self.pool = None
+        self._mapfunc = map
+        self._own_pool = False
+
+        if callable(pool):
+            self.pool = pool
+            self._mapfunc = self.pool
+        else:
+            # user supplies a number
+            if int(pool) == -1:
+                # use as many processors as possible
+                self.pool = Pool()
+                self._mapfunc = self.pool.map
+                self._own_pool = True
+            elif int(pool) == 1:
+                pass
+            elif int(pool) > 1:
+                # use the number of processors requested
+                self.pool = Pool(processes=int(pool))
+                self._mapfunc = self.pool.map
+                self._own_pool = True
+            else:
+                raise RuntimeError("Number of workers specified must be -1,"
+                                   " an int >= 1, or an object with a 'map' method")
+
+    def __enter__(self):
+        return self
+
+    def __del__(self):
+        self.close()
+
+    def terminate(self):
+        if self._own_pool:
+            self.pool.terminate()
+
+    def join(self):
+        if self._own_pool:
+            self.pool.join()
+
+    def close(self):
+        if self._own_pool:
+            self.pool.close()
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        if self._own_pool:
+            if exc_type is None:
+                self.pool.close()
+                self.pool.join()
+            else:
+                self.pool.terminate()
+
+    def __call__(self, func, iterable):
+        # only accept one iterable because that's all Pool.map accepts
+        try:
+            return self._mapfunc(func, iterable)
+        except TypeError:
+            # wrong number of arguments
+            raise TypeError("The map-like callable must be of the"
+                            " form f(func, iterable)")
diff --git a/scipy/optimize/_differentialevolution.py b/scipy/optimize/_differentialevolution.py
--- a/scipy/optimize/_differentialevolution.py
+++ b/scipy/optimize/_differentialevolution.py
@@ -3,12 +3,13 @@
 Added by Andrew Nelson 2014
 """
 from __future__ import division, print_function, absolute_import
+import warnings
+
 import numpy as np
 from scipy.optimize import OptimizeResult, minimize
 from scipy.optimize.optimize import _status_message
-from scipy._lib._util import check_random_state
+from scipy._lib._util import check_random_state, MapWrapper
 from scipy._lib.six import xrange, string_types
-import warnings
 
 
 __all__ = ['differential_evolution']
@@ -20,8 +21,10 @@ def differential_evolution(func, bounds, args=(), strategy='best1bin',
                            maxiter=1000, popsize=15, tol=0.01,
                            mutation=(0.5, 1), recombination=0.7, seed=None,
                            callback=None, disp=False, polish=True,
-                           init='latinhypercube', atol=0):
+                           init='latinhypercube', atol=0, updating='immediate',
+                           workers=1):
     """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
@@ -132,6 +135,29 @@ def differential_evolution(func, bounds, args=(), strategy='best1bin',
         ``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
     -------
@@ -162,12 +188,12 @@ def differential_evolution(func, bounds, args=(), strategy='best1bin',
 
     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
+    ``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
+    ``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.
@@ -175,6 +201,12 @@ def differential_evolution(func, bounds, args=(), strategy='best1bin',
     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
 
@@ -189,6 +221,14 @@ def differential_evolution(func, bounds, args=(), strategy='best1bin',
     >>> 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).
 
@@ -208,19 +248,30 @@ def differential_evolution(func, bounds, args=(), strategy='best1bin',
     .. [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] https://www1.icsi.berkeley.edu/~storn/code.html
-    .. [3] https://en.wikipedia.org/wiki/Differential_evolution
+    .. [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
     """
 
-    solver = DifferentialEvolutionSolver(func, bounds, args=args,
-                                         strategy=strategy, maxiter=maxiter,
-                                         popsize=popsize, tol=tol,
-                                         mutation=mutation,
-                                         recombination=recombination,
-                                         seed=seed, polish=polish,
-                                         callback=callback,
-                                         disp=disp, init=init, atol=atol)
-    return solver.solve()
+    # using a context manager means that any created Pool objects are
+    # cleared up.
+    with DifferentialEvolutionSolver(func, bounds, args=args,
+                                     strategy=strategy,
+                                     maxiter=maxiter,
+                                     popsize=popsize, tol=tol,
+                                     mutation=mutation,
+                                     recombination=recombination,
+                                     seed=seed, polish=polish,
+                                     callback=callback,
+                                     disp=disp, init=init, atol=atol,
+                                     updating=updating,
+                                     workers=workers) as solver:
+        ret = solver.solve()
+
+    return ret
 
 
 class DifferentialEvolutionSolver(object):
@@ -335,6 +386,25 @@ class DifferentialEvolutionSolver(object):
         ``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.
+
     """
 
     # Dispatch of mutation strategy method (binomial or exponential).
@@ -359,7 +429,8 @@ def __init__(self, func, bounds, args=(),
                  strategy='best1bin', maxiter=1000, popsize=15,
                  tol=0.01, mutation=(0.5, 1), recombination=0.7, seed=None,
                  maxfun=np.inf, callback=None, disp=False, polish=True,
-                 init='latinhypercube', atol=0):
+                 init='latinhypercube', atol=0, updating='immediate',
+                 workers=1):
 
         if strategy in self._binomial:
             self.mutation_func = getattr(self, self._binomial[strategy])
@@ -372,6 +443,20 @@ def __init__(self, func, bounds, args=(),
         self.callback = callback
         self.polish = polish
 
+        # set the updating / parallelisation options
+        if updating in ['immediate', 'deferred']:
+            self._updating = updating
+
+        # want to use parallelisation, but updating is immediate
+        if workers != 1 and updating == 'immediate':
+            warnings.warn("differential_evolution: the 'workers' keyword has"
+                          " overridden updating='immediate' to"
+                          " updating='deferred'", UserWarning)
+            self._updating = 'deferred'
+
+        # an object with a map method.
+        self._mapwrapper = MapWrapper(workers)
+
         # relative and absolute tolerances for convergence
         self.tol, self.atol = tol, atol
 
@@ -392,7 +477,9 @@ def __init__(self, func, bounds, args=(),
 
         self.cross_over_probability = recombination
 
-        self.func = func
+        # we create a wrapped function to allow the use of map (and Pool.map
+        # in the future)
+        self.func = _FunctionWrapper(func, args)
         self.args = args
 
         # convert tuple of lower and upper bounds to limits
@@ -507,7 +594,7 @@ def init_population_array(self, init):
         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`.
+            The population is clipped to the lower and upper bounds.
         """
         # make sure you're using a float array
         popn = np.asfarray(init)
@@ -537,11 +624,6 @@ def init_population_array(self, init):
     def x(self):
         """
         The best solution from the solver
-
-        Returns
-        -------
-        x : ndarray
-            The best solution from the solver.
         """
         return self._scale_parameters(self.population[0])
 
@@ -556,6 +638,14 @@ def convergence(self):
         return (np.std(self.population_energies) /
                 np.abs(np.mean(self.population_energies) + _MACHEPS))
 
+    def converged(self):
+        """
+        Return True if the solver has converged.
+        """
+        return (np.std(self.population_energies) <=
+                self.atol +
+                self.tol * np.abs(np.mean(self.population_energies)))
+
     def solve(self):
         """
         Runs the DifferentialEvolutionSolver.
@@ -580,7 +670,9 @@ def solve(self):
         # that someone can set maxiter=0, at which point we still want the
         # initial energies to be calculated (the following loop isn't run).
         if np.all(np.isinf(self.population_energies)):
-            self._calculate_population_energies()
+            self.population_energies[:] = self._calculate_population_energies(
+                self.population)
+            self._promote_lowest_energy()
 
         # do the optimisation.
         for nit in xrange(1, self.maxiter + 1):
@@ -589,7 +681,11 @@ def solve(self):
                 next(self)
             except StopIteration:
                 warning_flag = True
-                status_message = _status_message['maxfev']
+                if self._nfev > self.maxfun:
+                    status_message = _status_message['maxfev']
+                elif self._nfev == self.maxfun:
+                    status_message = ('Maximum number of function evaluations'
+                                      ' has been reached.')
                 break
 
             if self.disp:
@@ -634,8 +730,7 @@ def solve(self):
             result = minimize(self.func,
                               np.copy(DE_result.x),
                               method='L-BFGS-B',
-                              bounds=self.limits.T,
-                              args=self.args)
+                              bounds=self.limits.T)
 
             self._nfev += result.nfev
             DE_result.nfev = self._nfev
@@ -650,33 +745,68 @@ def solve(self):
 
         return DE_result
 
-    def _calculate_population_energies(self):
+    def _calculate_population_energies(self, population):
         """
         Calculate the energies of all the population members at the same time.
-        Puts the best member in first place. Useful if the population has just
-        been initialised.
-        """
-        for index, candidate in enumerate(self.population):
-            if self._nfev > self.maxfun:
-                break
 
-            parameters = self._scale_parameters(candidate)
-            self.population_energies[index] = self.func(parameters,
-                                                        *self.args)
-            self._nfev += 1
+        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))``.
 
-        minval = np.argmin(self.population_energies)
+        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),)``
+        """
+        num_members = np.size(population, 0)
+        nfevs = min(num_members,
+                    self.maxfun - num_members)
+
+        energies = np.full(num_members, np.inf)
+
+        parameters_pop = self._scale_parameters(population)
+        try:
+            calc_energies = list(self._mapwrapper(self.func,
+                                                  parameters_pop[0:nfevs]))
+            energies[0:nfevs] = calc_energies
+        except (TypeError, ValueError):
+            # wrong number of arguments for _mapwrapper
+            # or wrong length returned from the mapper
+            raise RuntimeError("The map-like callable must be of the"
+                               " form f(func, iterable), returning a sequence"
+                               " of numbers the same length as 'iterable'")
+
+        self._nfev += nfevs
+
+        return energies
+
+    def _promote_lowest_energy(self):
+        # promotes the lowest energy to the first entry in the population
+        l = np.argmin(self.population_energies)
 
         # put the lowest energy into the best solution position.
-        lowest_energy = self.population_energies[minval]
-        self.population_energies[minval] = self.population_energies[0]
-        self.population_energies[0] = lowest_energy
-
-        self.population[[0, minval], :] = self.population[[minval, 0], :]
+        self.population_energies[[0, l]] = self.population_energies[[l, 0]]
+        self.population[[0, l], :] = self.population[[l, 0], :]
 
     def __iter__(self):
         return self
 
+    def __enter__(self):
+        return self
+
+    def __exit__(self, *args):
+        # to make sure resources are closed down
+        self._mapwrapper.close()
+
+    def __del__(self):
+        # to make sure resources are closed down
+        self._mapwrapper.close()
+
     def __next__(self):
         """
         Evolve the population by a single generation
@@ -691,80 +821,92 @@ def __next__(self):
         # the population may have just been initialized (all entries are
         # np.inf). If it has you have to calculate the initial energies
         if np.all(np.isinf(self.population_energies)):
-            self._calculate_population_energies()
+            self.population_energies[:] = self._calculate_population_energies(
+                self.population)
+            self._promote_lowest_energy()
 
         if self.dither is not None:
             self.scale = (self.random_number_generator.rand()
                           * (self.dither[1] - self.dither[0]) + self.dither[0])
 
-        for candidate in range(self.num_population_members):
-            if self._nfev > self.maxfun:
-                raise StopIteration
+        if self._updating == 'immediate':
+            # update best solution immediately
+            for candidate in range(self.num_population_members):
+                if self._nfev > self.maxfun:
+                    raise StopIteration
 
-            # create a trial solution
-            trial = self._mutate(candidate)
+                # create a trial solution
+                trial = self._mutate(candidate)
 
-            # ensuring that it's in the range [0, 1)
-            self._ensure_constraint(trial)
+                # ensuring that it's in the range [0, 1)
+                self._ensure_constraint(trial)
 
-            # scale from [0, 1) to the actual parameter value
-            parameters = self._scale_parameters(trial)
+                # scale from [0, 1) to the actual parameter value
+                parameters = self._scale_parameters(trial)
 
-            # determine the energy of the objective function
-            energy = self.func(parameters, *self.args)
-            self._nfev += 1
+                # determine the energy of the objective function
+                energy = self.func(parameters)
+                self._nfev += 1
 
-            # if the energy of the trial candidate is lower than the
-            # original population member then replace it
-            if energy < self.population_energies[candidate]:
-                self.population[candidate] = trial
-                self.population_energies[candidate] = energy
+                # if the energy of the trial candidate is lower than the
+                # original population member then replace it
+                if energy < self.population_energies[candidate]:
+                    self.population[candidate] = trial
+                    self.population_energies[candidate] = energy
 
-                # if the trial candidate also has a lower energy than the
-                # best solution then replace that as well
-                if energy < self.population_energies[0]:
-                    self.population_energies[0] = energy
-                    self.population[0] = trial
+                    # if the trial candidate also has a lower energy than the
+                    # best solution then promote it to the best solution.
+                    if energy < self.population_energies[0]:
+                        self._promote_lowest_energy()
 
-        return self.x, self.population_energies[0]
+        elif self._updating == 'deferred':
+            # update best solution once per generation
+            if self._nfev >= self.maxfun:
+                raise StopIteration
 
-    def next(self):
-        """
-        Evolve the population by a single generation
+            # 'deferred' approach, vectorised form.
+            # create trial solutions
+            trial_pop = np.array(
+                [self._mutate(i) for i in range(self.num_population_members)])
 
-        Returns
-        -------
-        x : ndarray
-            The best solution from the solver.
-        fun : float
-            Value of objective function obtained from the best solution.
-        """
-        # next() is required for compatibility with Python2.7.
-        return self.__next__()
+            # enforce bounds
+            self._ensure_constraint(trial_pop)
+
+            # determine the energies of the objective function
+            trial_energies = self._calculate_population_energies(trial_pop)
+
+            # which solutions are improved?
+            loc = trial_energies < self.population_energies
+            self.population = np.where(loc[:, np.newaxis],
+                                       trial_pop,
+                                       self.population)
+            self.population_energies = np.where(loc,
+                                                trial_energies,
+                                                self.population_energies)
+
+            # make sure the best solution is updated if updating='deferred'.
+            # put the lowest energy into the best solution position.
+            self._promote_lowest_energy()
+
+        return self.x, self.population_energies[0]
+
+    next = __next__
 
     def _scale_parameters(self, trial):
-        """
-        scale from a number between 0 and 1 to parameters.
-        """
+        """Scale from a number between 0 and 1 to parameters."""
         return self.__scale_arg1 + (trial - 0.5) * self.__scale_arg2
 
     def _unscale_parameters(self, parameters):
-        """
-        scale from parameters to a number between 0 and 1.
-        """
+        """Scale from parameters to a number between 0 and 1."""
         return (parameters - self.__scale_arg1) / self.__scale_arg2 + 0.5
 
     def _ensure_constraint(self, trial):
-        """
-        make sure the parameters lie between the limits
-        """
-        for index in np.nonzero((trial < 0) | (trial > 1))[0]:
-            trial[index] = self.random_number_generator.rand()
+        """Make sure the parameters lie between the limits."""
+        mask = np.where((trial > 1) | (trial < 0))
+        trial[mask] = self.random_number_generator.rand(mask[0].size)
 
     def _mutate(self, candidate):
-        """
-        create a trial vector based on a mutation strategy
-        """
+        """Create a trial vector based on a mutation strategy."""
         trial = np.copy(self.population[candidate])
 
         rng = self.random_number_generator
@@ -800,25 +942,19 @@ def _mutate(self, candidate):
             return trial
 
     def _best1(self, samples):
-        """
-        best1bin, best1exp
-        """
+        """best1bin, best1exp"""
         r0, r1 = samples[:2]
         return (self.population[0] + self.scale *
                 (self.population[r0] - self.population[r1]))
 
     def _rand1(self, samples):
-        """
-        rand1bin, rand1exp
-        """
+        """rand1bin, rand1exp"""
         r0, r1, r2 = samples[:3]
         return (self.population[r0] + self.scale *
                 (self.population[r1] - self.population[r2]))
 
     def _randtobest1(self, samples):
-        """
-        randtobest1bin, randtobest1exp
-        """
+        """randtobest1bin, randtobest1exp"""
         r0, r1, r2 = samples[:3]
         bprime = np.copy(self.population[r0])
         bprime += self.scale * (self.population[0] - bprime)
@@ -827,19 +963,15 @@ def _randtobest1(self, samples):
         return bprime
 
     def _currenttobest1(self, candidate, samples):
-        """
-        currenttobest1bin, currenttobest1exp
-        """
+        """currenttobest1bin, currenttobest1exp"""
         r0, r1 = samples[:2]
-        bprime = (self.population[candidate] + self.scale * 
+        bprime = (self.population[candidate] + self.scale *
                   (self.population[0] - self.population[candidate] +
                    self.population[r0] - self.population[r1]))
         return bprime
 
     def _best2(self, samples):
-        """
-        best2bin, best2exp
-        """
+        """best2bin, best2exp"""
         r0, r1, r2, r3 = samples[:4]
         bprime = (self.population[0] + self.scale *
                   (self.population[r0] + self.population[r1] -
@@ -848,9 +980,7 @@ def _best2(self, samples):
         return bprime
 
     def _rand2(self, samples):
-        """
-        rand2bin, rand2exp
-        """
+        """rand2bin, rand2exp"""
         r0, r1, r2, r3, r4 = samples
         bprime = (self.population[r0] + self.scale *
                   (self.population[r1] + self.population[r2] -
@@ -869,3 +999,14 @@ def _select_samples(self, candidate, number_samples):
         idxs = idxs[:number_samples]
         return idxs
 
+
+class _FunctionWrapper(object):
+    """
+    Object to wrap user cost function, allowing picklability
+    """
+    def __init__(self, f, args):
+        self.f = f
+        self.args = [] if args is None else args
+
+    def __call__(self, x):
+        return self.f(x, *self.args)
diff --git a/tools/refguide_check.py b/tools/refguide_check.py
--- a/tools/refguide_check.py
+++ b/tools/refguide_check.py
@@ -645,6 +645,12 @@ def write(self, msg):
             else:
                 out(msg)
 
+        # a flush method is required when a doctest uses multiprocessing
+        # multiprocessing/popen_fork.py flushes sys.stderr
+        def flush(self):
+            if doctest_warnings:
+                sys.stdout.flush()
+
     # Run tests, trying to restore global state afterward
     old_printoptions = np.get_printoptions()
     old_errstate = np.seterr()


Test patch:
diff --git a/scipy/_lib/tests/test__util.py b/scipy/_lib/tests/test__util.py
--- a/scipy/_lib/tests/test__util.py
+++ b/scipy/_lib/tests/test__util.py
@@ -1,10 +1,12 @@
 from __future__ import division, print_function, absolute_import
+from multiprocessing import Pool
+from multiprocessing.pool import Pool as PWL
 
 import numpy as np
 from numpy.testing import assert_equal, assert_
 from pytest import raises as assert_raises
 
-from scipy._lib._util import _aligned_zeros, check_random_state
+from scipy._lib._util import _aligned_zeros, check_random_state, MapWrapper
 
 
 def test__aligned_zeros():
@@ -54,3 +56,54 @@ def test_check_random_state():
     rsi = check_random_state(None)
     assert_equal(type(rsi), np.random.RandomState)
     assert_raises(ValueError, check_random_state, 'a')
+
+
+class TestMapWrapper(object):
+
+    def setup_method(self):
+        self.input = np.arange(10.)
+        self.output = np.sin(self.input)
+
+    def test_serial(self):
+        p = MapWrapper(1)
+        assert_(p._mapfunc is map)
+        assert_(p.pool is None)
+        assert_(p._own_pool is False)
+        out = list(p(np.sin, self.input))
+        assert_equal(out, self.output)
+
+        with assert_raises(RuntimeError):
+            p = MapWrapper(0)
+
+    def test_parallel(self):
+        with MapWrapper(2) as p:
+            out = p(np.sin, self.input)
+            assert_equal(list(out), self.output)
+
+            assert_(p._own_pool is True)
+            assert_(isinstance(p.pool, PWL))
+            assert_(p._mapfunc is not None)
+
+        # the context manager should've closed the internal pool
+        # check that it has by asking it to calculate again.
+        with assert_raises(Exception) as excinfo:
+            p(np.sin, self.input)
+
+        # on py27 an AssertionError is raised, on >py27 it's a ValueError
+        err_type = excinfo.type
+        assert_((err_type is ValueError) or (err_type is AssertionError))
+
+        # can also set a PoolWrapper up with a map-like callable instance
+        try:
+            p = Pool(2)
+            q = MapWrapper(p.map)
+
+            assert_(q._own_pool is False)
+            q.close()
+
+            # closing the PoolWrapper shouldn't close the internal pool
+            # because it didn't create it
+            out = p.map(np.sin, self.input)
+            assert_equal(list(out), self.output)
+        finally:
+            p.close()
diff --git a/scipy/optimize/tests/test__differential_evolution.py b/scipy/optimize/tests/test__differential_evolution.py
--- a/scipy/optimize/tests/test__differential_evolution.py
+++ b/scipy/optimize/tests/test__differential_evolution.py
@@ -330,6 +330,21 @@ def test_maxfun_stops_solve(self):
                          'Maximum number of function evaluations has '
                               'been exceeded.')
 
+        # now repeat for updating='deferred version
+        solver = DifferentialEvolutionSolver(rosen,
+                                             self.bounds,
+                                             popsize=5,
+                                             polish=False,
+                                             maxfun=40,
+                                             updating='deferred')
+        result = solver.solve()
+
+        assert_equal(result.nfev, 40)
+        assert_equal(result.success, False)
+        assert_equal(result.message,
+                         'Maximum number of function evaluations has '
+                              'been reached.')
+
     def test_quadratic(self):
         # test the quadratic function from object
         solver = DifferentialEvolutionSolver(self.quadratic,
@@ -356,6 +371,7 @@ def test_seed_gives_repeatability(self):
                                         seed=1,
                                         tol=0.5)
         assert_equal(result.x, result2.x)
+        assert_equal(result.nfev, result2.nfev)
 
     def test_exp_runs(self):
         # test whether exponential mutation loop runs
@@ -377,8 +393,8 @@ def test_gh_4511_regression(self):
     def test_calculate_population_energies(self):
         # if popsize is 3 then the overall generation has size (6,)
         solver = DifferentialEvolutionSolver(rosen, self.bounds, popsize=3)
-        solver._calculate_population_energies()
-
+        solver._calculate_population_energies(solver.population)
+        solver._promote_lowest_energy()
         assert_equal(np.argmin(solver.population_energies), 0)
 
         # initial calculation of the energies should require 6 nfev.
@@ -487,3 +503,38 @@ def sometimes_inf(x):
         x_fit = differential_evolution(sometimes_inf,
                                        bounds=[(0, 1), (0, 1)],
                                        disp=False)
+
+    def test_deferred_updating(self):
+        # check setting of deferred updating, with default workers
+        bounds = [(0., 2.), (0., 2.), (0, 2), (0, 2)]
+        solver = DifferentialEvolutionSolver(rosen, bounds, updating='deferred')
+        assert_(solver._updating == 'deferred')
+        assert_(solver._mapwrapper._mapfunc is map)
+        solver.solve()
+
+    def test_immediate_updating(self):
+        # check setting of immediate updating, with default workers
+        bounds = [(0., 2.), (0., 2.)]
+        solver = DifferentialEvolutionSolver(rosen, bounds)
+        assert_(solver._updating == 'immediate')
+
+        # should raise a UserWarning because the updating='immediate'
+        # is being overriden by the workers keyword
+        with np.testing.assert_warns(UserWarning):
+            solver = DifferentialEvolutionSolver(rosen, bounds, workers=2)
+            assert_(solver._updating == 'deferred')
+
+    def test_parallel(self):
+        # smoke test for parallelisation with deferred updating
+        bounds = [(0., 2.), (0., 2.)]
+        with DifferentialEvolutionSolver(rosen, bounds,
+                                         updating='deferred',
+                                         workers=2) as solver:
+            assert_(solver._mapwrapper.pool is not None)
+            assert_(solver._updating == 'deferred')
+            solver.solve()
+
+    def test_converged(self):
+        solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)])
+        solver.solve()
+        assert_(solver.converged())