
    J-jj             	          d Z ddlmZmZmZ ddlZddlmZ ddlZddl	Z	ddl
Z
ddl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 dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZmZ ddlmZ ddlmZ ddl m!Z" ddl#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z- ddl+m.Z. ddl+m/Z0 ddl1m2Z2m3Z4 ddl5 ddlm6Z7 dZ8	 dZ9	 dZ:	 dZ;	 dZ<	 ejz                  Z>[[[dZ?dZ@ej                  dk\  ZB	 dZC	 ej                  dk\  ZD	 dZE	 d ZF	  G d! d"eG      ZHd# ZId$ ZJd@d%ZK G d& d'e0      ZL G d( d)eM      ZNdZOdZPdZQdZRdZS G d* d+ ej                  d+g d,            ZU G d- d.eV      ZW G d/ d0eX      ZY G d1 d2ej                        Z[ G d3 d4eV      Z\ G d5 d6eM      Z]dAd7Z^dddd8dej                  dfd9Z`	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dBd:Zag Zbd; Zcd< Zdd= Zeededddfd>Zfeddddfd?Zgy)CzCMA-ES (evolution strategy), the main sub-module of `cma` implementing
in particular `CMAEvolutionStrategy`, `fmin2` and further ``fmin_*``
functions.
    )absolute_importdivisionprint_functionN   )range)infarray)
interfaces)options_parameters)transformations)optimization_tools)sampler)utils)
CMAOptionscma_default_options)warnings_and_exceptions)constraints_handler)fitness_models)	BoundNoneBoundPenaltyBoundTransform)IntegerCentering)CMADataLogger)
BlancClass)rglen)SolutionDict)Mhifloat)*)restricted_gaussian_samplerg     @   FTznot anymore in effect)      g    eAc                       e Zd ZdZy)InjectionWarningz5Injected solutions are not passed to tell as expectedN__name__
__module____qualname____doc__     d/Users/jameslopez/projects/TradingBot25/.venv/lib/python3.12/site-packages/cma/evolution_strategy.pyr%   r%     s    ?r,   r%   c                 *    | g S t        |       r| gS | S )zA `callable` is wrapped and `None` defaults to the empty list.

    All other values, in particular `False`, remain unmodified on return.
    )callable)cs    r-   _callable_to_listr1   
  s!    
 	y		!s
Hr,   c                      | r| d   S dS )z7a callable that does nothing and return args[0] in caser   Nr+   )argskwargss     r-   _passr5     s    47$$r,   c                     | rt         S t        S )z5return a functional or a template "empty" class.
    )_CMASolutionDict_functional_CMASolutionDict_empty)
functionals    r-   get_CMASolutionDictr:     s     +5&P:PPr,   c                   *     e Zd Z fdZ	 	 ddZ xZS )r7   c                 :    t        t        | 
  |i | d| _        y Nr   )superr7   __init__last_solution_index)selfr3   r4   	__class__s      r-   r?   z$_CMASolutionDict_functional.__init__  s     )494J6J#$ r,   c                    |-|| j                   kD  r|dz  dk  r| j                  d|dz
         n5|3|j                  d      r"|d   }|dz  dk  r| j                  d|dz
         | xj                  dz  c_        ||j                  d|      }||| j                   kD  rd| _        || _         n| j                   dz   }||}nd|i}|||d	<   ||d<   |||d
<   |||d<   || |<   |S )aT  insert an entry with key ``key`` and value
        ``value if value is not None else {'geno':key}`` and
        ``self[key]['kwarg'] = kwarg if kwarg is not None`` for the further kwargs.

        TODO: this looks overdesigned. Only the keyword `iteration` is
        currently used and not even necessary anymore because
        `SolutionDict` is now ordered. Just using `SolutionDict` would be
        good enough with insertions done using a `dict` as value if
        desired, or a single `info` argument could be implemented in
        `SolutionDict` for any additional information.
        
   r   i,     	iterationr         ?phenogenofitnesscma_norm)last_iterationtruncategetr@   )rA   keyrI   rF   rJ   valuerK   entrys           r-   insertz"_CMASolutionDict_functional.insert'  s%     Y1D1D%D)VX.\]I]MM#y1}-599[#9k*IB!#c9q=1  A% 		+y9I 4...+,("+D++c1IEcNE E&M&k&E) (E*S	r,   )NNNNN)r'   r(   r)   r?   rR   __classcell__rB   s   @r-   r7   r7     s    % >B%)*r,   r7   c                   4    e Zd ZdZd Zd Zd Zd Zd Zd Z	y)	r8   z(a hack to get most code examples runningc                      y Nr+   rA   r3   r4   s      r-   rR   z_CMASolutionDict_empty.insertU      r,   c                      y rW   r+   rA   rO   s     r-   rN   z_CMASolutionDict_empty.getW  s    r,   c                      y rW   r+   rX   s      r-   rM   z_CMASolutionDict_empty.truncateY  rY   r,   c                      y rW   r+   rX   s      r-   truncate_toz"_CMASolutionDict_empty.truncate_to[  rY   r,   c                     i S rW   r+   r[   s     r-   __getitem__z"_CMASolutionDict_empty.__getitem__]  s    	r,   c                      y rW   r+   )rA   rO   rP   s      r-   __setitem__z"_CMASolutionDict_empty.__setitem___  rY   r,   N)
r'   r(   r)   r*   rR   rN   rM   r^   r`   rb   r+   r,   r-   r8   r8   S  s#    2r,   r8   c                       e Zd ZdZy)CMAEvolutionStrategyResulta  A results tuple from `CMAEvolutionStrategy` property ``result``.

    This tuple contains in the given position and as attribute

    - 0 ``xbest`` best solution evaluated
    - 1 ``fbest`` objective function value of best solution
    - 2 ``evals_best`` evaluation count when ``xbest`` was evaluated
    - 3 ``evaluations`` evaluations overall done
    - 4 ``iterations``
    - 5 ``xfavorite`` distribution mean in "phenotype" space, to be
      considered as current best estimate of the optimum
    - 6 ``stds`` effective standard deviations, can be used to
      compute a lower bound on the expected coordinate-wise distance
      to the true optimum, which is (very) approximately stds[i] *
      dimension**0.5 / min(mueff, dimension) / 1.5 / 5 ~ std_i *
      dimension**0.5 / min(popsize / 2, dimension) / 5, where
      dimension = CMAEvolutionStrategy.N and mueff =
      CMAEvolutionStrategy.sp.weights.mueff ~ 0.3 * popsize.
    - 7 ``stop`` termination conditions in a dictionary

    The penalized best solution of the last completed iteration can be
    accessed via attribute ``pop_sorted[0]`` of `CMAEvolutionStrategy`
    and the respective objective function value via ``fit.fit[0]``.

    Details:

    - This class is of purely declarative nature and for providing
      this docstring. It does not provide any further functionality.
    - ``list(.fit.idx).index(0)`` is the index of the first sampled
      solution of the last completed iteration in ``pop_sorted``.

    Nr&   r+   r,   r-   rd   rd   n  s    r,   rd   )xbestfbest
evals_bestevaluations
iterations	xfavoritestdsstopc                   Z    e Zd ZdZd Zed        Zed        Zd Zd Z	d Z
d Zd	 Zd
 Zy)CMAEvolutionStrategyResult2aD  A results class.

    This class is of rather declarative nature allowing to access the result in
    its attributes after running an optimization. Additionally, the class
    provides a `names` and an `asdict` property.

    >>> import cma
    >>> es = cma.CMA(2 * [1], .1, {'verbose': -9}).optimize(cma.ff.sphere, 4, iterations=5)
    >>> isinstance(es.result, cma.evolution_strategy.CMAEvolutionStrategyResult2)
    True

    The easiest ways to examine the results visually is by ``list(es.result)``
    or like
    
    >>> es.result.asdict  # doctest: +ELLIPSIS
    {'xbest':...

    We can also check the available attribute names like

    >>> es.result.names  # doctest: +ELLIPSIS
    ['xbest', 'fbest',...

    and then check a value like

    >>> float(es.result.xbest[0]) < 10
    True

    Otherwise, the result class acts largely like a `dataclass` and like the
    original `namedtuple` `CMAEvolutionStrategyResult`, however with
    _additional_ attributes: as of 2025 the `.best_feasible` attribute has been
    added. For backward compatibility, index access of the original entries is
    possible but discouraged, like

    >>> es.result[1] == es.result[-7] == es.result.fbest  # deprecated
    True

    The nine result attributes are:

    ``xbest`` best solution evaluated, this may not reflect a good solution
    under noise or with a changing fitness function like in the constrained
    case.

    ``fbest`` objective function value of the best solution

    ``evals_best`` evaluation count when ``xbest`` was evaluated

    ``best_feasible`` is a dictionary with the keys ``'x', 'f', 'evals'``
    (and possibly others), the feasible counterparts to ``xbest, fbest,
    evals_best``. This is particularly useful with constraints.
    ``best_feasible`` is not accessible by index.

    ``evaluations`` overall done

    ``iterations`` overall done

    ``xfavorite`` final distribution mean in "phenotype" space, considered
    to be the current best estimate of the optimum.

    ``stds`` effective final standard deviations, can be used to compute a
    lower bound on the expected coordinate-wise distance to the true
    optimum, which is (very!) approximately ``stds[i] * dim**0.5 * 3 /
    np.minimum(popsize, 3 * dim + 15)`` (was: ``stds[i] * dimension**0.5 /
    min(mueff, dimension) / 1.5 / 5 ~ stds[i] * dimension**0.5 /
    min(popsize / 2, dimension) / 5``, where dimension =
    CMAEvolutionStrategy.N and mueff =
    CMAEvolutionStrategy.sp.weights.mueff ~ 0.3 * popsize).

  ``stop`` termination conditions in a dictionary.

    CAVEAT: in contrast to a named tuple, this class iterates over items, not
    values, hence ``dict(es.result)`` works as expected. ``list(es.result)`` is
    not backward compatible (providing a list of values without keys seems
    rather pointless given the values are not homogenuous). The previous value
    of ``list(es.result)`` can be obtained by ``[r[1] for r in es.result]``.

    While not provided in this class, the (penalized-)best solution
    of the last completed iteration can be accessed via the attribute
    ``.pop_sorted[0]`` of `CMAEvolutionStrategy` and the respective
    objective function value via ``.fit.fit[0]``.

    Details:

    - in addition to ``._asdict()`` and ``dir(.)`` (which works rather
      poorly) for the old `CMAEvolutionStrategyResult`, viewing with
      ``dict(.)`` and ``.asdict`` works for this class too.
    - ``list(CMA.fit.idx).index(i)`` is the index of the i-ths sampled solution
      of the last completed iteration in ``pop_sorted``. In other words, it is
      the (original) index of the i+1-th best solution.

    Technical details:

    - The class allows to have new attributes while keeping backward
      compatible index access of the original eight attributes of the
      `namedtuple` `CMAEvolutionStrategyResult`. ``es.result[-8]`` still
      equals ``es.result[0]``. Newly introduced attributes are ignored in
      this count and cannot be accessed by position index. Index access
      is discouraged.
    - inheriting from a `list` would work too, but we would have the list
      methods as additional attributes.

c
                    t        t                     t        fddD              | _        || _        || _        || _        || _        || _        || _	        || _
        || _        |	| _        | j                  D ]  \  }
}t        | |
|        y)zHset attributes with the arguments resembling `namedtuple` or `dataclass`c              3   ,   K   | ]  }||   f  y wrW   r+   ).0name_varss     r-   	<genexpr>z7CMAEvolutionStrategyResult2.__init__.<locals>.<genexpr>  s&      
#	!" 6:dE$K0	!"s   )	re   rf   rg   best_feasiblerh   ri   rj   rk   rl   N)dictlocalstuple_paramsre   rf   rg   ru   rh   ri   rj   rk   rl   setattr)rA   re   rf   rg   ru   rh   ri   rj   rk   rl   kvrs   s               @r-   r?   z$CMAEvolutionStrategyResult2.__init__   s     VX 
#	!"
# 
# 

$*&$"		 LLDAqD!Q !r,   c                 F    | j                   D cg c]  }|d   	 c}S c c}w )zlist of attribute namesr   ry   )rA   ps     r-   namesz!CMAEvolutionStrategyResult2.names-  s$     #ll+l!l+++s   c                 "    | j                         S rW   )_asdictrA   s    r-   asdictz"CMAEvolutionStrategyResult2.asdict2  s    ||~r,   c                 ,    t        | j                        S rW   )rv   ry   r   s    r-   r   z#CMAEvolutionStrategyResult2._asdict6  s    DLL!!r,   c                 z   |t        dd      vrt        dj                  |            |dv r| j                  }|S |dv r| j                  }|S |dv r| j
                  }|S |dv r| j                  }|S |dv r| j                  }|S |d	v r| j                  }|S |d
v r| j                  }|S |dv r| j                  }|S d}|S )zyfor backward compatibility, access by the (old) index works too,
        this is supposed to stay as is forever.
           z{0} is not a valid result index, only -8...7 are valid and refer to
0=xbest,fbest,evals_best,evaluations,iterations,xfavorite,stds,7=stop)r   r   )r   i)r"   i)rE   )   )   )r#   )   N)r   
IndexErrorformatre   rf   rg   rh   ri   rj   rk   rl   )rA   iress      r-   r`   z'CMAEvolutionStrategyResult2.__getitem__9  s    E"aL  g %fQi) ) '\tzz( 
' '\tzz 	( 
% #$w,t 	( 
# $%<t 	( 
! #$w,t	 	( 
 "#gt~~ 	( 
 Ltyy 	( 
 Ltyy 	( 
  	( 
r,   c                 ,    t        | j                        S rW   )lenry   r   s    r-   __len__z#CMAEvolutionStrategyResult2.__len__X  s    4<<  r,   c                 (    d | j                   D        S )zreturn iterator over namesc              3       K   | ]  }|  y wrW   r+   )rq   r   s     r-   rt   z7CMAEvolutionStrategyResult2.__iter__.<locals>.<genexpr>_  s     (<a<s   r~   r   s    r-   __iter__z$CMAEvolutionStrategyResult2.__iter__[  s     )4<<((r,   c                     dj                  ddj                  | j                  D cg c]  } dj                   |  c}            S c c}w )zstring representation of self.

        arrays come without commata like ``'[val1 val2 ...]'``, however in a `dict`
        they look like `repr(.)` like ``'array([val1, val2, ...])'``.
        {0}({1})rn   , {0}={1})r   joinry   )rA   r|   s     r-   __str__z#CMAEvolutionStrategyResult2.__str__f  sL       !>!%$,,+W,Q,<I,<,<a,@,+W!XZ 	Z+Ws   Ac                     dj                  ddj                  | j                  D cg c]   \  }}dj                  |t        |            " c}}            S c c}}w )Nr   rn   r   r   )r   r   ry   repr)rA   r{   r|   s      r-   __repr__z$CMAEvolutionStrategyResult2.__repr__q  sW      !>!%UYUaUa+bUaTQPQI,<,<QQ,HUa+b!ce 	e+bs   %AN)r'   r(   r)   r*   r?   propertyr   r   r   r`   r   r   r   r   r+   r,   r-   rn   rn     sW    dJ% Z , ,  ">!)	Zer,   rn   c                        e Zd ZdZed        Zy)_CMAEvolutionStrategyResulta  Deprecated: A results tuple from `CMAEvolutionStrategy` property ``result``.

    This tuple contains in the given position

    - 0 best solution evaluated, ``xbest``
    - 1 objective function value of best solution, ``f(xbest)``
    - 2 evaluation count when ``xbest`` was evaluated
    - 3 evaluations overall done
    - 4 iterations
    - 5 distribution mean in "phenotype" space, to be considered as
      current best estimate of the optimum
    - 6 effective standard deviations, give a lower bound on the expected
      coordinate-wise distance to the true optimum of (very) approximately
      std_i * dimension**0.5 / min(mueff, dimension) / 1.2 / 5
      ~ std_i * dimension**0.5 / min(popsize / 0.4, dimension) / 5, where
      mueff = CMAEvolutionStrategy.sp.weights.mueff ~ 0.3 * popsize.

    The penalized best solution of the last completed iteration can be
    accessed via attribute ``pop_sorted[0]`` of `CMAEvolutionStrategy`
    and the respective objective function value via ``fit.fit[0]``.

    Details:

    - This class is of purely declarative nature and for providing this
      docstring. It does not provide any further functionality.
    - ``list(fit.fit).find(0)`` is the index of the first sampled solution
      of the last completed iteration in ``pop_sorted``.

c           
          t        | j                  j                         | j                  | j                  | j                  | j                  dd | j                  j                        | j                  fz         S )zreturn a results tuple of type `CMAEvolutionStrategyResult`.

        `_generate` is a surrogate for the ``__init__`` method, which
        cannot be used to initialize the immutable `tuple` super class.
        Ninto_bounds)
r   bestrN   
countevals	countiterto_phenotypemeanboundary_handlerrepairrk   r   s    r-   	_generatez%_CMAEvolutionStrategyResult._generate  sj     +IIMMOOONNdiil*.*?*?*F*F  HII  	r,   N)r'   r(   r)   r*   staticmethodr   r+   r,   r-   r   r   u  s    >  r,   r   c            	           e Zd ZdZed        Z	 	 d8dZd9dZd Zd:d	Z	d9d
Z
d;dZ	 	 d<dZ	 	 d=dZd Zd Zd:dZddddddej$                  ddf	dZd Zd>dZ	 	 d9dZd Zd?dZ	 	 d@dZ	 	 	 dAdZej                  e_        d>dZd Zd Zd>dZd Zd Z ed         Z!ed!        Z"ed"        Z#ed#        Z$ed$        Z%	 	 dBd%Z&d& Z'd' Z(d( Z)d:d)Z*dCd*Z+ed+        Z,dDd,Z-d- Z.d. Z/dEd/Z0d>d0Z1d1 Z2d2 Z3d3 Z4ed4        Z5d5 Z6d9d6Z7d7 Z8y)FCMAEvolutionStrategya?0  CMA-ES stochastic optimizer class with ask-and-tell interface.

    Calling Sequences
    =================

    - ``es = CMAEvolutionStrategy(x0, sigma0)``

    - ``es = CMAEvolutionStrategy(x0, sigma0, opts)``

    - ``es = CMAEvolutionStrategy(x0, sigma0).optimize(objective_fct)``

    - ::

        res = CMAEvolutionStrategy(x0, sigma0,
                                opts).optimize(objective_fct).result

    Arguments
    =========
    `x0`
        initial solution, starting point. `x0` is given as "phenotype"
        which means, if::

            opts = {'transformation': [transform, inverse]}

        is given and ``inverse is None``, the initial mean is not
        consistent with `x0` in that ``transform(mean)`` does not
        equal to `x0` unless ``transform(mean)`` equals ``mean``.
    `sigma0`
        initial standard deviation.  The problem variables should
        have been scaled, such that a single standard deviation
        on all variables is useful and the optimum is expected to
        lie within about `x0` +- ``3*sigma0``. Often one wants to
        check for solutions close to the initial point. This allows,
        for example, for an easier check of consistency of the
        objective function and its interfacing with the optimizer.
        In this case, a much smaller `sigma0` is advisable.
    `opts`
        options, a dictionary with optional settings,
        see class `CMAOptions`.

    Main interface / usage
    ======================
    The interface is inherited from the generic `OOOptimizer`
    class (see also there). An object instance is generated from::

        es = cma.CMAEvolutionStrategy(8 * [0.5], 0.2)

    The least verbose interface is via the optimize method::

        es.optimize(objective_func)
        res = es.result

    More verbosely, the optimization is done using the
    methods `stop`, `ask`, and `tell`::

        while not es.stop():
            solutions = es.ask()
            es.tell(solutions, [cma.ff.rosen(s) for s in solutions])
            es.disp()
        es.result_pretty()


    where `ask` delivers new candidate solutions and `tell` updates
    the `optim` instance by passing the respective function values
    (the objective function `cma.ff.rosen` can be replaced by any
    properly defined objective function, see `cma.ff` for more
    examples).

    To change an option, for example a termination condition to
    continue the optimization, call::

        es.opts.set({'tolfacupx': 1e4})

    The class `CMAEvolutionStrategy` also provides::

        (solutions, func_values) = es.ask_and_eval(objective_func)

    and an entire optimization can also be written like::

        while not es.stop():
            es.tell(*es.ask_and_eval(objective_func))

    Besides for termination criteria, in CMA-ES only the ranks of the
    `func_values` are relevant.

    Attributes and Properties
    =========================
    - `inputargs`: passed input arguments
    - `inopts`: passed options
    - `opts`: actually used options, some of them can be changed any
      time via ``opts.set``, see class `CMAOptions`
    - `popsize`: population size lambda, number of candidate
      solutions returned by `ask` ()
    - `logger`: a `CMADataLogger` instance utilized by `optimize`

    Examples
    ========
    Super-short example, with output shown:

    >>> import cma
    >>> # construct an object instance in 4-D, sigma0=1:
    >>> es = cma.CMAEvolutionStrategy(4 * [1], 1, {'seed':234})
    ...      # doctest: +ELLIPSIS
    (4_w,8)-aCMA-ES (mu_w=2.6,w_1=52%) in dimension 4 (seed=234...)

    and optimize the ellipsoid function

    >>> es.optimize(cma.ff.elli, verb_disp=1)  # doctest: +ELLIPSIS
    Iterat #Fevals   function value  axis ratio  sigma  min&max std  t[m:s]
        1      8 2.09...
    >>> assert len(es.result) >= 8, es.result
    >>> assert es.result.fbest < 1e-9, es.result

    The optimization loop can also be written explicitly:

    >>> es = cma.CMAEvolutionStrategy(4 * [1], 1)  # doctest: +ELLIPSIS
    (4_w,8)-aCMA-ES (mu_w=2.6,w_1=52%) in dimension 4 (seed=...
    >>> while not es.stop():
    ...    X = es.ask()
    ...    es.tell(X, [cma.ff.elli(x) for x in X])
    ...    es.disp()  # doctest: +ELLIPSIS
    Iterat #Fevals   function value  axis ratio  sigma  min&max std  t[m:s]
        1      8 ...

    achieving the same result as above.

    An example with lower bounds (at zero) and handling infeasible
    solutions:

    >>> import numpy as np
    >>> es = cma.CMAEvolutionStrategy(10 * [0.2], 0.5,
    ...         {'bounds': [0, np.inf]})  #doctest: +ELLIPSIS
    (5_w,...
    >>> while not es.stop():
    ...     fit, X = [], []
    ...     while len(X) < es.popsize:
    ...         curr_fit = None
    ...         while curr_fit in (None, np.nan):
    ...             x = es.ask(1)[0]
    ...             curr_fit = cma.ff.somenan(x, cma.ff.elli) # might return np.nan
    ...         X.append(x)
    ...         fit.append(curr_fit)
    ...     es.tell(X, fit)
    ...     es.logger.add()
    ...     es.disp()  #doctest: +ELLIPSIS
    Itera...
    >>>
    >>> assert es.result.fbest < 1e-9, es.result
    >>> assert es.result.evals_best < 9000, es.result  # by internal termination
    >>> # es.logger.plot()  # will plot data
    >>> # cma.s.figshow()  # display plot window

    An example with user-defined transformation, in this case to realize
    a lower bound of 2.

    >>> import warnings
    >>> with warnings.catch_warnings(record=True) as warns:
    ...     es = cma.CMAEvolutionStrategy(5 * [3], 0.1,
    ...                 {"transformation": [lambda x: x**2+1.2, None],
    ...                  "ftarget": 1e-7 + 5.54781521192,
    ...                  "verbose": -2,})
    >>> warns[0].message  # doctest:+ELLIPSIS
    UserWarning('in class GenoPheno: user defined transformations have not been tested thoroughly (...
    >>> warns[1].message  # doctest:+ELLIPSIS
    UserWarning('computed initial point...
    >>> es.optimize(cma.ff.rosen, verb_disp=0)  #doctest: +ELLIPSIS
    <cma...
    >>> assert cma.ff.rosen(es.result.xbest) < 1e-7 + 5.54781521192, es.result
    >>> assert es.result.evals_best < 3300, es.result

    The inverse transformation is (only) necessary if the `BoundPenalty`
    boundary handler is used at the same time.

    The `CMAEvolutionStrategy` class also provides a default logger
    (cave: files are overwritten when the logger is used with the same
    filename prefix):

    >>> es = cma.CMAEvolutionStrategy(4 * [0.2], 0.5, {'verb_disp': 0})
    >>> es.logger.disp_header()  # annotate the print of disp
    Iterat Nfevals  function value    axis ratio maxstd  minstd
    >>> while not es.stop():
    ...     X = es.ask()
    ...     es.tell(X, [cma.ff.sphere(x) for x in X])
    ...     es.logger.add()  # log current iteration
    ...     es.logger.disp([-1])  # display info for last iteration   #doctest: +ELLIPSIS
        1  ...
    >>> es.logger.disp_header()
    Iterat Nfevals  function value    axis ratio maxstd  minstd
    >>> # es.logger.plot() # will make a plot

    Example implementing restarts with increasing popsize (IPOP):

    >>> bestever = cma.optimization_tools.BestSolution()
    >>> for lam in 10 * 2**np.arange(8):  # 10, 20, 40, 80, ..., 10 * 2**7
    ...     es = cma.CMAEvolutionStrategy(6 - 8 * np.random.rand(4),  # 4-D
    ...                                   5,  # initial std sigma0
    ...                                   {'popsize': lam,  # options
    ...                                    'verb_append': bestever.evalsall})
    ...     # logger = cma.CMADataLogger().register(es, append=bestever.evalsall)
    ...     while not es.stop():
    ...         X = es.ask()    # get list of new solutions
    ...         fit = [cma.ff.rastrigin(x) for x in X]  # evaluate each solution
    ...         es.tell(X, fit) # besides for termination only the ranking in fit is used
    ...
    ...         # display some output
    ...         # logger.add()  # add a "data point" to the log, writing in files
    ...         es.disp()  # uses option verb_disp with default 100
    ...
    ...     print('termination:', es.stop())
    ...     cma.s.pprint(es.best.__dict__)
    ...
    ...     bestever.update(es.best)
    ...
    ...     # show a plot
    ...     # logger.plot();
    ...     if bestever.f < 1e-8:  # global optimum was hit
    ...         break  #doctest: +ELLIPSIS
    (5_w,...
    >>> assert es.result.fbest < 1e-8, es.result

    On the Rastrigin function, usually after five restarts the global
    optimum is located.

    Using the `multiprocessing` module, we can evaluate the function in
    parallel with a simple modification of the example (however
    multiprocessing seems not always reliable):

    >>> from cma.fitness_functions import elli  # cannot be an instance method
    >>> from cma.optimization_tools import EvalParallel2
    >>> es = cma.CMAEvolutionStrategy(22 * [0.0], 1.0, {'maxiter':10})  # doctest:+ELLIPSIS
    (6_w,13)-aCMA-ES (mu_w=...
    >>> with EvalParallel2(elli, es.popsize + 1) as eval_all:
    ...     while not es.stop():
    ...         X = es.ask()
    ...         es.tell(X, eval_all(X))
    ...         es.disp()
    ...         # es.logger.add()  # doctest:+ELLIPSIS
    Iterat...

    The final example shows how to resume:

    >>> import pickle
    >>>
    >>> es0 = cma.CMAEvolutionStrategy(12 * [0.1],  # a new instance, 12-D
    ...                                0.12)         # initial std sigma0
    ...   #doctest: +ELLIPSIS
    (5_w,...
    >>> es0.optimize(cma.ff.rosen, iterations=100)  #doctest: +ELLIPSIS
    I...
    >>> s = es0.pickle_dumps()  # return pickle.dumps(es) with safeguards
    >>> # save string s to file like open(filename, 'wb').write(s)
    >>> del es0  # let's start fresh
    >>> # s = open(filename, 'rb').read()  # load string s from file
    >>> es = pickle.loads(s)  # read back es instance from string
    >>> # resuming
    >>> es.optimize(cma.ff.rosen, verb_disp=200)  #doctest: +ELLIPSIS
      200 ...
    >>> assert es.result.evals_best < 15000, es.result
    >>> assert cma.s.Mh.vequals_approximately(es.result.xbest, 12 * [1], 1e-5), es.result
    >>> assert len(es.result) >= 8, es.result

    Details
    =======
    The following two enhancements are implemented, the latter is only
    turned on by default for very small population sizes.

    *Active CMA* is implemented with option ``CMA_active`` and
    conducts an update of the covariance matrix with negative weights.
    The negative update is implemented, such that positive definiteness
    is guarantied. A typical speed up factor (number of f-evaluations)
    is between 1.1 and two.

    References: Jastrebski and Arnold, Improving evolution strategies
    through active covariance matrix adaptation, CEC 2006.
    Hansen, The CMA evolution strategy: a tutorial, arXiv 2016.

    *Selective mirroring* is implemented with option ``CMA_mirrors``
    in the method `get_mirror` and `get_selective_mirrors`.
    The method `ask_and_eval` (used by `fmin`) will then sample
    selectively mirrored vectors within the iteration
    (``CMA_mirrormethod==1``). Otherwise, or if ``CMA_mirromethod==2``,
    selective mirrors are injected for the next iteration.
    In selective mirroring, only the worst solutions are mirrored. With
    the default small number of mirrors, *pairwise selection* (where at
    most one of the two mirrors contribute to the update of the
    distribution mean) is implicitly guarantied under selective
    mirroring and therefore not explicitly implemented.

    Update: pairwise selection for injected mirrors is also applied in the
    covariance matrix update: for all injected solutions, as for those from
    TPA, this is now implemented in that the recombination weights are
    constrained to be nonnegative for injected solutions in the covariance
    matrix (otherwise recombination weights are anyway nonnegative). This
    is a precaution to prevent failure when injected solutions are
    systematically bad (see e.g. https://github.com/CMA-ES/pycma/issues/124),
    but may not be "optimal" for mirrors.

    References: Brockhoff et al, PPSN 2010, Auger et al, GECCO 2011.

    :See also: `fmin` (), `OOOptimizer`, `CMAOptions`, `plot` (), `ask` (),
        `tell` (), `ask_and_eval` ()

c                 .    | j                   j                  S )z:number of samples by default returned by `ask` ()
        )sppopsizer   s    r-   r   zCMAEvolutionStrategy.popsize  s     wwr,   r+   FNc                    |rs| j                   dkD  rd| j                  d   rU| j                  d   t        | j                  d         k7  r- t        j                  | j                  d         |       | _        || j                  _        | j                  | |xs+ |xs' |xr# | j                   | j                  j                  k7        }|r|D ]  }|j                  |d        |r(| j                  j                  dc}| j                  _
        |S )a  return the termination status as dictionary.

        With ``check == False``, the termination conditions are not checked
        and the status might not reflect the current situation.
        ``check_on_same_iteration == False`` (new) does not re-check during
        the same iteration. When termination options are manually changed,
        it must be set to `True` to advance afterwards.
        ``stop().clear()`` removes the currently active termination
        conditions.

        As a convenience feature, keywords in `ignore_list` are removed from
        the conditions.

        If `get_value` is set to a condition name (not the empty string),
        `stop` does not update the termination dictionary but returns the
        measured value that would be compared to the threshold. This only
        works for some conditions, like 'tolx'. If the condition name is
        not known or cannot be computed, `None` is returned and no warning
        is issued.

        Testing `get_value` functionality:

        >>> import cma
        >>> es = cma.CMAEvolutionStrategy(2 * [1], 1e4, {'verbose': -9})
        >>> with warnings.catch_warnings(record=True) as w:
        ...     es.stop(get_value='tolx')  # triggers zero iteration warning
        ...     assert len(w) == 1, [str(wi) for wi in w]
        >>> es = es.optimize(cma.ff.sphere, iterations=4)
        >>> assert 1e3 < es.stop(get_value='tolx') < 1e4, es.stop(get_value='tolx')
        >>> assert es.stop() == {}
        >>> assert es.stop(get_value='catch 22') is None

    r   termination_callbackN)r   optsstrr   ListOfCallablescallbackstop	_stopdict
_get_valuelastiterpop_value)rA   checkignore_listcheck_in_same_iteration	get_valuer   rO   s          r-   rl   zCMAEvolutionStrategy.stop  s    F dnnq(TYY7M-N		01SCY9Z5[[ X 5 5dii@V6W XY] ^D$-!nnT#: $Xi $X#(#VT^^t~~?V?V-VY"T" #)-)>)>&C&
r,   c                 ,    t        j                  dt         j                         |r||}~t        t	                      _         j
                  d= |i }| _        t        |      j                         }|j                  d      t               d   |d<   |j                  d      xt        _        }|dk  rd|d<   d|d	<   d|d
<   d|v r|j                  d      rt        d      d|v r|j                  d      rt        d       j                  |       t         j                         _        t        j"                  |      rt        dj%                  |            t'        j(                  |      dk7  st'        j*                  |      rt        dj%                  |            t-        |       _         j.                   _         j                   }t        j"                  |d         rt3        j4                  |d         |d<   t7        |d   t              s|d   J t7        |d   t              r j                   t        |d         z
  }|j9                  t	                      t'        j:                  |d         rd|d<   | _        t        j>                  |d         sB j<                  d   t&        j@                  jB                  u r|d   r(|d   tD        u stG        |d         jI                  d      rt&        j@                  jK                          tE        jD                         dtE        jD                         dz  z  z
  }tM        dt&        j@                  jO                         z  |z   dtE        jD                         dz  z  z         |d<   t&        j@                  jK                  |d          n1|d   dtD        fvr$t        jP                  dtG        |d         z         tS        jT                   j                   |d   |d   |d   |d          _+         jV                  jX                  s)t[        j\                  dj%                  d      t^               |d     _0        t7         j`                  tb              r ja                  |d!          _0        n0|d!   dd"g d#fvs|d!   d   |d!   d   t[        j\                  d$        j`                  je                         stg                _0        nu j`                  ji                   j                        s|d   dk\  rω j`                  jk                   j                        }	t[        j\                  d%t        |	      dkD  rd&nd'd(tG        |	      d)tG         jV                  jm                   j                              d*tG         j`                  jn                  d         d+tG         j`                  jn                  d         d,       |d-   V j`                  jq                  d. j                          j`                  jq                  d/ j                         z
  |d0   z  |d-<    j`                  js                  |d1           jV                  jt                  }
 jV                  jv                  r? jV                  jt                  )d2 }| jV                  _:        t[        j\                  d3        jV                  jy                  t'        jz                   j                  d4       j`                  j|                  d"5       _?        t'        jz                   j~                  d4       _@        t{         j~                  d4       _A        |
 jV                  _:        t         j~                         _B        | j                  k(  sJ |j                  ||       t        j                  |||d   dkD  6       _F         j                   _G        d7 } ||d8           _H        t7         j                  t              s|d9   rdnd" _J        d} fd;	} ||d<   ||d      |d<<    ||d-   ||t&        j                        |d-<   t        |d1         rA|j                  | j                  j                  j                         t                _P        nt         _P        d=d>k  rEt        |d1         r7	 dd?lRmS} t        j                  d@      }t[        j\                  |t^               d _V        dA _W        t7        |dB   t              st        d|dB   f      nd _Z        t'        j                  |       _\        t'        j                  |       _]        t'        j                  |       _^        dd>k  r | j<                  dC   ||       __        t'        j(                   j                        dk(  r7 j<                  dD   r( xj                  t'        j                  |      z  c__        tS        j                   j                         _b        t'        j                   j<                  dE         rى xj                  t'        j                  |      z  c_b        n | j<                  dC   ||       _b        t'        j                   j<                  dE         r( xj                  t'        j                  |      z  c_b        t'        j                   j                        r j                  n j                  j                          __         j<                  d   rt        j                  | j<                  d   F       _h         j                   j                          j<                  d   du rS j                  j                  j                  | j                  j                   j                  j                  d"G       n j<                  d   dk(  rt        dH       j                  j                  j                  | j                  j                   j                  j                         n | j<                  dI   ||      }d=d>k  r9t         j<                  dJ   dK      r dL j<                  dJ   v rd j<                  dM<    j<                  dN   Bt        j                  |t'        j                  |      z   j<                  dO   Cd: j                  j                   j                  j                  z   dPz   z   j                  z  dQz  n j<                  dO    j<                  dM    j<                  d    j<                  dR   S       _h         j                  j                   j                  j                  j                   j                  j                  j                  T      } j                  j                  j                  ||dU   |dV          nqt7         j<                  dN   tb              r@	   j<                  dN   |t'        j                  |      z  fi  j<                  dW    _h        n j<                  dN    _h        t7         j                  t        j                        sXt        jP                  dZtG        tc        t        j                              d[tG        tc         j                              d\        j                   j                          j                  |dkD  ]        j                  j                   _x         j                  d^z   _y        g  _z        g  _{        d _|        d _}        g  _~         jV                  jm                   j~                   j0                   j                  z   j                  z  z          jV                  jm                   j~                   j0                   j                  z   j                  z  z
        z
  d_z   j`                  jq                  d. j                          j`                  jq                  d/ j                         z
  z  }t'        j                  |dkD        ret'        j                   |dkD        d   }d`t        |      dkD  rdadbtG        |      z  fndcddtG        |d         z  fz  }t[        j\                  |       d _         j                   _        d _        d _        g  _        	  j                  j                           t        t                      _        	 tS        j                   j<                  t               _        	  t        t         j                  j                  dek  nt                      _        	 t#                _        t'        j(                          _        t-                _        |d^z  dd:df|z  z  z
  d:dg|dhz  z  z  z   z   j.                  _        t3        |di   |d	   |dj   k      j5                          _        t9                _        	 t=         j~                         _        d# _        	 t-                _        d jB                  _        d jB                  _        d jB                  _        d jB                  _        g  jB                  _        tM                jB                  _        tM                jB                  _        d jB                  _        d jB                  _        t&        j                   jB                  _        t&        j                   jB                  _        d jB                  _        d jB                  _        t        j^                          _        |d   dkD  r|d   dk\  r j                  j                  jb                  dkD  rdlndm} j                  jd                  rdn j                  jd                  z  ndm}tg        do j                  j                  jb                  z  |z   dp j                  j                  z  z   |z   dqz   |dr   rdsndmz   dtz   du j                  j                  j                  tM        dv j                  j                  d   z        fz  z   dw|tG        |d         tE        jh                         fz  z          |d   rډ j                  jj                  rdm}|d   durdx}|d   t&        j                  k  r|tG        tM        |d               z  }n%|tG        t'        jl                  |d               z  }|dyz  }|dztG        to        d: j                  j                   j                  j                  z   z              z   d{z   z  }tg        d||z          yyyyy# t        $ r Y w xY w#  t        |      t        |      kD  rt        jP                  dX       n#|d   dk7  rt        jP                  dY|d   z           j<                  dN   |fi  j<                  dW    _h        Y xY w# t        $ r Y Lw xY w)~zsee class `CMAEvolutionStrategy`

        `options` is for consistency with `fmin2` options and is only
        in effect if ``inopts is None``.
        oncecategoryNrA   verboser   r   	verb_dispverb_log	verb_plotnoise_handlingzOnoise_handling not available with class CMAEvolutionStrategy, use function fminrestartszIrestarts not available with class CMAEvolutionStrategy, use function fminzCsigma0 must be a scalar, a string like '{0}' is no longer permittedr   zinput argument sigma0 was {0} but must be (or evaluate to) a scalar, use `cma.ScaleCoordinates` or option `"CMA_stds"` when different sigmas in each coordinate are in order.fixed_variablesCMA_diagonalTseedrandntimeg    .Ag     j@zSseed=%s will never be used (seed is only used if option 'randn' is np.random.randn)scaling_of_variables	typical_xtransformationa"  genotype-phenotype transformations induced by {0}
 may not be compatible with more recently introduced code features (like integer handling) and are deprecated.
Rather use an objective function wrapper instead, see e.g.
`ScaleCoordinates` or `FixVariables` in `cma.fitness_transformations`.z
                        opts['scaling_of_variables'],
                        opts['typical_x'],
                        opts['fixed_variables'],
                        opts['transformation'])BoundaryHandlerboundsFr+   z
                Option 'bounds' ignored because a BoundaryHandler *instance* was found.
                Consider to pass only the desired BoundaryHandler class. zX
                Initial solution is out of the domain boundaries
                in indicesex z:
                    x0   = z
                    ldom = z
                    udom = zR
                THIS MIGHT LEAD TO AN EXCEPTION RAISED LATER ON.
                maxstdupperlowermaxstd_boundrangeinteger_variablesc                     | S rW   r+   xs    r-   identityz/CMAEvolutionStrategy.__init__.<locals>.identity  s    r,   zucomputed initial point may well be wrong, because no
inverse for the user provided phenotype transformation was givencopyfrom_boundsr   r   c                 2   | t        j                  d       t        } n@| du r.|j                  d   du r|j                  dkD  rt
        } nt        } n| du r
t               } t        | t              r( | |j                  |j                  j                        } | S )z+return instantiated sigma adaptation objectzValue `None` for option 'AdaptSigma' is ambiguous and
hence deprecated. AdaptSigma can be set to `True` or
`False` or a class or class instance which inherited from
`cma.sigma_adaptation.CMAAdaptSigmaBase`Tr   i+  F)	dimensionr   )r   print_warningCMAAdaptSigmaCSAr   NCMAAdaptSigmaTPACMAAdaptSigmaNone
isinstancetyper   r   )adapt_sigmarA   s     r-   instantiate_adapt_sigmaz>CMAEvolutionStrategy.__init__.<locals>.instantiate_adapt_sigma  s    "##?@
 /$99^,4#"2K"2K%/1+t,)DFFDGGOOTr,   
AdaptSigmamean_shift_line_samples      ?c                    | |S t        j                  |       dk(  r	 t        | d         }n|d   rt        j                  |       |kD  rzt	        t        t        |             D cg c]  }||d   vr| |    c}t              }t        |      |k7  rt        j                  dt        |      |fz  dj                         nR|r?t        |       |k  r1t        j                  | |t        |       z
  | d   gz  ft              }nt	        | t              }t        j                  |      d|fvr#t        d	|t        j                  |      fz        |S # t        $ r t        |       }Y Tw xY wc c}w )
zvreturn `default_value` as scalar or `in_` after removing
            fixed variables if ``len(in_) == N``
            r   r   r   dtypezresulting len %d != N = %deval_vectorrF   r   zEvector (like CMA_stds or minstd) must have dimension %d instead of %d)npsizefloat	TypeErrorr	   r   r   r   r   r   concatenate
ValueError)in_r   r   default_valuer   r   rA   s         r-   r   z2CMAEvolutionStrategy.__init__.<locals>.eval_vector  sn    {$$wws|q %A-C '(RWWS\A-=U3s8_ I_'(5F0G'G !V_ I"') s8q=''4C!}D%A s3x!|nncACLSWI+E%F+02 Cu-wws|Aq6) 145rwws|3DEF F J' ! %*C%Is   E &E/E,+E,minstd   rE   )integerzzOption 'integer_variables' is discouraged. Use class `cma.integer.CMAIntMixed` or function `cma.integer.fmin_int` instead.r   verb_appendCMA_stdsCMA_diagonal_decodingCMA_dampsvec_fac)r   )pos_defzOption 'CMA_diagonal' == 1 is disallowed.
                Use either `True` or an iteration number > 1 up to which C should be diagonal.
                Only `True` has linear memory demand.CMA_teststdsvvr`   
sweep_ccovCMA_const_traceCMA_samplerupdatecovwaitQ@-(;rD   CMA_eigenmethod)lazy_update_gapconstant_tracer   eigenmethodmuefflamc1cmuCMA_sampler_optionsz`different initial standard deviations are not supported by the current sampler and hence ignoredz6ignoring scaling factor %f
    for sample distributionzEstatistical model sampler did
    not evaluate to the expected type `z` but to type `z8`. This is
    likely to lead to an exception later on. )warnrG   g5^I @zValueWarning:

  Initial standard deviation%s larger than the bounded domain size in variable%s.
  Consider using `cma.ScaleCoordinates` if the bounded domain sizes differ significantly. 
zs sigma0 x stds arezs %sz sigma0 x stds isz %s!   g      @g      5@r"   verb_filenameprefixverb_log_expensive)moduloexpensive_modulo_w zmirr%dz(%dz,%dz)-
CMA_activeazCMA-ESz (mu_w=%2.1f,w_1=%d%%)d   z in dimension %d (seed=%s, %s)z for z iterationsz	 (1/ccov=)z    Covariance matrix is diagonal)r   )_cma_warningsfilterwarningNeverTestedWarningrv   rw   	inputargsinoptsr   
complementevalr   global_verbosityr  _set_x0r   x0N_phenois_strr   r   r   shaper  sigma0sigmaastliteral_evalr   evalallisinfr   is_nanrandomr   r   r   
startswithr   intrandr   r   	GenoPhenogp
isidentitywarningsr   DeprecationWarningr   r   
has_boundsr   is_in_boundsidx_out_of_boundsrH   r   
get_bounds"amend_bounds_for_integer_variablestf_genotf_phenorI   r	   inverser   mean_after_tellmean0r   amend_integer_optionsr   CMAParametersr   sp0r   r   mean_shift_samplesr   set_integer_min_stdweightsr  r   integer_centeringr5   r'  r	  format_messageImportErrorr   _isotropic_mean_shift_iterationboolmaxr   zerospcpc2pc_neg
sigma_vec0onesDiagonalDecoding	sigma_vecisfiniteisscalarr   r   GaussStandardConstantsm_updateBDfromSMfinalize_negative_weightsc1_sepcmu_sepr  r  hasattrGaussFullSampler
parameterslambda_minr
   ,StatisticalModelSamplerWithZeroMeanBaseClass_stds_into_limits	variancesdCDpop_injection_solutionspop_injection_directionsnumber_of_solutions_askednumber_of_injections_delivered_is_independent_sampleanynonzero_flgtelldoneitereigenupdatedcount_eigennoiseShsiglist
initialize	Exceptionr:   archive_sent_solutionssent_solutionsRoundIntegerVariablesround_integer_variables_round_integer_variablesarchive_after_sentr   archive_SolutionDict_injected_solutions_archiveotBestSolutionr   _BlancClassconstchiNr   registerlogger_CMAStopDictr   _StopTolXStagnation_stoptolxstagnationr   fitbndpenfit_plus_penidxhistlisthistbest
histmedianmedianmedian0
median_minmedian_previousmedian_got_worseflatfit_iterationsMoreToWritemore_to_writemulam_mirrprintasctimeCMA_onfloorround)rA   r5  r9  r0  optionsr   r3  r   six_decimalsidxstf_geno_backupr   r   r   r	  srk   r   relative_stdsr  	sweightedsmirrs   `                     r-   r?   zCMAEvolutionStrategy.__init__  st    	##F-:-M-M	Ov~FfhNN6">F&!,,.99Y'(l95DO48IIi4HH!1b  !D D !Dt#		2B(Cnoo$))J"7hiiR477|<<biijpqrr776?a288F#3 R %fVn. . Fm[[
 LL<<./0&)&6&6*+'-D"#4 12D9%&.	0 /d,-t4s4(9#:;;AVX88D()#'D 	||DL)yy!RYY__4F|tF|t';s4<?P?[?[\b?cIINN$$(IIK#9K2L$LL#&sRYY^^-='='L),		a)@(A $BDL		tF|,fdD\1##$y&)$v,&7%8 9!++DLL34[)./-.	0
 ww!!MM _ V 3 4
 +
 !%%6 7d++T2$($9$9$x.$ID!(^D%R#88Xq!)d8nQ.?.GMM M N $$//1$-KD! ((55dgg>	?a'00BB477KDMM "%TQvD8D	DGGMM$''23D1188;<D1188;<#> ? H~%"&"7"7"B"B7DLL"Y"&"7"7"B"B7DLL"Y#Z&*+>&?"@X !!DD,-/ 77 7&DGGOMM GGLL$''!=(,(=(=(E(E!& ! (	  "xx		=49940
( TYYDFF{{ 	""1f-$221dDOVWDWX77	( 343EtL+5d6F6FHX+Y*+ #'27 		< %T(^T1a@X$T(^T1bffEX t'()$$Q(=(=>%5d%;D"%*D"6c$234%((67 a*<=
 /1,d=148 q$}"567>? 	((1+88A;hhqkq5)$))J*?qIDOwwt'1,;R1S2771:-,==dooNDN{{499%789"''!*,(:)>aHDN{{499%789"''!*,02DNN0Kdnn151D1D1F O99^$33ATYYw=OPDG  )yy(D099!6:ggnn6:ggoo>C : E >*a/  "9 : : 99!6:ggjj6:ggkkC tyy8$BDAv499T?M:$		$737DII/0yy'/!224"''!*3D  99_5= dggjj477;;6>?$&&H2M!YY7#'99->#?))G, $		*; < GG&&TWW__-B-B+/77??+B+B ' D99!QtWahODIIm4d;D6dii6 $rwwqz 1D"&)),A"BDDG ))M2dggz'^'^_## ZTTUVTWW&	%( )
   )$4q$89''###')$(*%)*&./+&(# ''--		DJJ4ORVRXRX4X(XY GGMM$))djj4>>6QTXTZTZ6Z*Z[\_de 11<<WdllS"33>>wUVW 66-!#$**]Q./2C 3x!| +FSX,=>*=*/#c!f+*=*?	@  MM!  $	''- J12HIK	' )8(M(M II'>)@%	
D*2D2L ,077??R+?0BD F 	I+8?(OO%	 ]
S&AbdObC1Ho$EF

#D)>$?+/
+;59:N5OQQYQYZ^Q_ 	 &>#6tyy#A L= $ F"f ff#%66 $%!&'#"..0 q T)_%9 $ 2 2Q 6BI59WW5E5EH 0 012E%477??--.:Udggoo=VVY^^!%l!3#=?GH*dggoo.C.CStww_`OaIaEb-ccd 3aT&\9JDLLN5[[\ ] N#'t3AN+bff4ST.%9!:;;S$~*>!?@@&As5twwzzDGGKK7O1P+Q'RRUXXXA81<= )7# &: M  B	D4y3t9,++ -9 : aA++ -!%a-) *6dii6q D"&)),A"BDDGV  		s?   6AW  >AW C5AY W 	AWWAWWA:AYY
AYYAYc                    	  |       }t	        |t
        d      | _        | j                  j                  dk(  rd| j                  j                  v rt        j                  dt        | j                  j                        z   dz          | j                  j                  d   dk(  r| j                  d   | _        nG| j                  j                  d   dk(  r+t	        | j                  D cg c]  }|d   	 c}      | _        | j                  j                  dk7  rt        d	      t        | j                        dk  r+t        j                  d
t        | j                        z         	 | j                  j                  | j                  j                  d          y# t         $ r$ t        j                  |      rt        d      Y w xY wc c}w # t        $ r Y yw xY w)a  Assign `self.x0` from argument `x0`.

        Input `x0` may be a `callable` or a `list` or `numpy.ndarray` of
        the desired length.

        Below an artificial example is given, where calling `x0`
        delivers in the first two calls ``dimension * [5]`` and in
        succeeding calls``dimension * [0.01]``. Only the initial value of
        0.01 solves the Rastrigin function:

        >>> import cma
        >>> class X0:
        ...     def __init__(self, dimension):
        ...         self.irun = 0
        ...         self.dimension = dimension
        ...     def __call__(self):
        ...         
        ...         self.irun += 1
        ...         return (self.dimension * [5] if self.irun < 3
        ...                 else self.dimension * [0.01])
        >>> xopt, es = cma.fmin2(cma.ff.rastrigin, X0(3), 0.01,
        ...                      {'verbose':-9}, restarts=1)
        >>> assert es.result.fbest > 1e-5
        >>> xopt, es = cma.fmin2(cma.ff.rastrigin, X0(3), 0.01,
        ...                      {'verbose':-9}, restarts=2)
        >>> assert es.result.fbest < 1e-5  # third run succeeds due to x0

        z9x0 may be a callable, but a string is no longer permittedT)r   r   r"   r   z:input x0 should be a list or 1-D array, trying to flatten z-arrayr   zx0 must be 1-D arrayzInitial solution argument x0=%s is 1-dimensional.
Optimization in 1-D is not supported and may bail or work poorly. 
See issues https://github.com/CMA-ES/pycma/issues/86 and https://github.com/CMA-ES/pycma/issues/302.N)r  r   r7  r  r	   r  r5  ndimr8  r   r   r   resizeNotImplementedError)rA   r5  r   s      r-   r4  zCMAEvolutionStrategy._set_x0  s   :	^B
 %d377<<1dggmm!3 \ #DGGMM 2!35=!> ?ww}}Q1$''!*q!Q&tww 7w!1w 7877<<1344tww<1 !K #&dgg,!/ 0	GGNN477==+,)  	^||B !\]]  	^ !8 # 		s)   F )G)2G )G	G		GGc                    t        j                  | j                  d   dkD        }t        j                  t        j                  | j                  d               }| j                  dk  rt        j
                  d      nd}	 |s|syd }g }t        | j                        D ]Y  \  }}d	}	|r || j                  d   |      }
||
k  }	|r |	s || j                  d   |      }
||
|z  kD  }	|	sK| j                  j                  | j                         |dk(  s/t        j                  | j                  j                  |   
z        sIt        j                  d
j                  || j                  j                  |   
| j                               nS| j                  j                  || j                  j                  |   |
z  |z         | j                   |xx   |
|z  z  cc<   |sD|j#                  ||
|z  f       \ |rs|d   \  }}t        j                  dj                  || j                  || j                  |   dj                  t%        |      dkD  rt%        |      dz
  nd                   yy)zIset ``self.sigma_vec.scaling`` to respect ``opts['max/minstd']``
        r  r   r   r"   g-C6?r   Nc                 :    t        j                  |       r| S | |   S rW   )r   rh  )bndsr   s     r-   get_iz5CMAEvolutionStrategy._stds_into_limits.<locals>.get_i  s    {{4 7Nr,   Fzo_stds_into_limits: sigmavec update omitted due to an inadmissible value s={0}, scaling[i]={1}, sb={2}, stds={3}zXSampling standard deviation i={0}{4} at iteration {1} multiplied by {2} to stds[{0}]={3}z (and {0} others)r'  )r   r~  r   rg  r   exp	enumeraterk   rf  _init_r   scalingrG  r   r   set_ira  appendr   )rA   r   is_minis_maxinitial_linalg_fixr  warning_datar   r  foundsbsss               r-   ru  z&CMAEvolutionStrategy._stds_into_limits  s&    		(+a/0DIIh$789-1^^q-@RVVD\aBf	 dii(DAqE499X.2Be499X.2B!333%%dff-6T^^-C-CA-F-K!LMM #X4>>#9#9!#<b$))LN NN((DNN,B,B1,E,JQ,NOHHQK26)K ''BqD	2% )&  OEArMM B#VAt~~r499Q<$7$>$>'*<'81'< @C<?PST?TBD%FGH r,   c                 2   || j                   }t        | j                        }||j                  |        t	        |       | j
                  j                  | j                  dd | j                  j                        ||      }|j                  |        |S )au  tentative copy of self, versatile (interface and functionalities may change).

        `sigma` overwrites the original initial `sigma`.
        `inopts` allows to overwrite any of the original options.

        This copy may not work as expected depending on the used sampler.

        Copy mean and sample distribution parameters and input options. Do
        not copy evolution paths, termination status or other state variables.

        >>> import cma
        >>> es = cma.CMAEvolutionStrategy(3 * [1], 0.1,
        ...          {'bounds':[0,9], 'verbose':-9}).optimize(cma.ff.elli, iterations=10)
        >>> es2 = es._copy_light()
        >>> assert es2.sigma == es.sigma
        >>> assert not sum((es.sm.C - es2.sm.C).flat > 1e-12), (es.sm.C, es2.sm.C)
        >>> assert not sum((es.sm.C - es2.sm.C).flat < -1e-12), (es.sm.C, es2.sm.C)
        >>> es3 = es._copy_light(sigma=3)
        >>> assert es3.sigma == es3.sigma0 == 3
        >>> es.mean[0] = -11
        >>> es4 = es._copy_light(inopts={'CMA_on': False})
        >>> assert es4.sp.c1 == es4.sp.cmu == 0
        >>> assert es.mean[0] == -11 and es4.mean[0] >= -4.5

        Nr   )r:  rv   r0  updater   rE  rH   r   r   r   _set_C_from)rA   r:  r0  r   ess        r-   _copy_lightz CMAEvolutionStrategy._copy_light  s    4 =JJEDKK KKT$Zdiil262G2G2N2N & Pt% 	t	r,   c                 P   |j                   | j                   k7  r9t        j                  dj                  |j                   | j                                |r~t	        j
                  |j                  j                        | _        t        j                  | j                  dk(        s.t        j                  dj                  | j                               	 |j                  j                  j                         | j                  _        t        j                  | j                  dk(        s/t        j                  dj                  | j                               	 | j                  j!                  d       | j#                          y# t        $ r t        j                  d       Y Lw xY w)zset the current covariance matrix from another class instance.

        If `scaling`, also set the diagonal decoding scaling from `es.sigma_vec`.

        This method may not work as expected unless the default sampler is
        used.
        zTsetting C with dimension {0} != {1} (the current dimension). This is likely to fail.r   z>self.pc2={0} != 0 may not be compatible with changed sigma_vecz5self.pc={0} != 0 may not be compatible with changed Cz#`self.sm.C = es.sm.C.copy()` failedr   N)r   rG  r   r   r   re  rf  r  r   allra  rj  Cr   r`  r  
update_nowrk  )rA   r  r  s      r-   r  z CMAEvolutionStrategy._set_C_from0  s    44466>MM @!6"$$/1 ,==bll>R>RSDN66$((a-(^%vdhh/1	0DGGI 66$''Q,'U%vdgg02  	AMM?@	As   3F F%$F%r   c                      j                   dk\  sJ  j                   dk(  rt        j                          _        n j                  j                     j
                  |||fi |}|D cg c]4  } j                  j                  |d j                  j                        6 }	}|]t         j                  t        j                        s$t        j                  ddd j                   d	       t        j                   d
t"        j$                         	  j                  j&                  st        j                  d        fdd*fd	}
d*d}	  j(                   j                   k(  r/t        j                  d j                    j*                  d           j                    _        t/        dt1        |	      dz
  f      }	 d j2                  |<   | j8                  } j                  j                  |d j                  j                        }  ||g|       } j                  j:                  r& j                   j                  j=                         rdd}t         j                  t>              r j                  j                  nzt         j                  t@              r fd}  |||            }nK j                  t         j                  tB              rn$tE        dtG         j                        z   dz          fd} |
||      }||z  |z   } j*                  d   r%t        j                   dt"        j$                         t1        |       jH                  k7  r8t        j                   dj7                  t1        |       jH                                j                  jJ                  tM        jN                   j                  jP                  jR                   jT                  |z        z  }tW        |dz        }|r| jX                   jH                  |z  dz  z   jT                  tM        jN                   j                  jP                   j                  jJ                  |z        z  z  z
  ||<   ddk  rɉ j*                  d    rtW        tM        jN                   j                  jP                  jR                   jT                  d!z  |z         j                  jJ                  z  dz        }|r%| jX                   jH                  |z  dz  z  |z  z
  n|||<   n&|||<   t        j                  d" j                   #        j                  j                  ||   d j                  j                        |	|<   ddk  rut[        d$|	|    j8                  z         t[        d%|	|    j8                  z
         t[        d&|       t[        d'|	|    j8                  z
  |z
  tW        |dz        dz  z         t]        |      D ]0  } j^                  ja                  |	|   ||    j                   )       2  jb                  je                  |	       |	S c c}w # t,        $ r Y w xY w# t4        $ r0}t        j                   dj7                  ||             Y d}~d}~ww xY w# t,        $ r.}t        j                   d(j7                  |             Y d}~d}~ww xY w)+a  get/sample new candidate solutions.

        Solutions are sampled from a multi-variate
        normal distribution and transformed to f-representation
        (phenotype) to be evaluated.

        Arguments
        ---------
            `number`
                number of returned solutions, by default the
                population size ``popsize`` (AKA ``lambda``).
            `xmean`
                distribution mean, phenotyp?
            `sigma_fac`
                multiplier for internal sample width (standard
                deviation)
            `gradf`
                gradient, ``len(gradf(x)) == len(x)``, if
                ``gradf is not None`` the third solution in the
                returned list is "sampled" in supposedly Newton
                direction ``np.dot(C, gradf(xmean, *args))``.
            `args`
                additional arguments passed to gradf
            `kwargs`
                if `ignore_integer_variables` do not change integer
                variables at all which is in particular useful when a small
                mutation is added to a given solution and integer values
                are not supposed to be disturbed at all and/or moved across
                a plateau boundary.

        Return
        ------
        A list of N-dimensional candidate solutions to be evaluated

        Example
        -------
        >>> import cma
        >>> es = cma.CMAEvolutionStrategy([0,0,0,0], 0.3)  #doctest: +ELLIPSIS
        (4_w,...
        >>> while not es.stop() and es.best.f > 1e-6:
        ...     X = es.ask()  # get list of new solutions
        ...     fit = [cma.ff.rosen(x) for x in X]  # call fct with each solution
        ...     es.tell(X, fit)  # feed values

        :See: `ask_and_eval`, `ask_geno`, `tell`
    r   Tr   r   NzSGradient injection may fail, because
sampler attributes `B` and `D` are not presentaskr   r   maxwarnszthe `gradf` argument to `ask` has not been thoroughly tested,
  consider to use ``es.inject(es.mean - delta * gradf(es.mean)`` with a large value for delta.r   z
                    using the gradient (option ``gradf``) with a non-linear
                    coordinate-wise transformation (option ``transformation``)
                    has never been tested.c                     j                   d   s| S t        j                  t        t	        |             D cg c]  }|j                   d   vr| |    c}      S c c}w )z9return y unchanged or a copy of y without fixed variablesr   )r   r   asarrayr   r   )yr   rA   s     r-   	_rm_fixedz+CMAEvolutionStrategy.ask.<locals>._rm_fixed  sf    99%67 ::U3q6] 'Q]*+499=N3O*O ()t] 'Q R R 'Qs   Ac                 t    |ddt        |       z   z  n|}  || |z          || |z
        z
        d|z  z  S )zmap is a coordinate-wise independent map, return
                    the estimated diagonal of the Jacobian.
                    :0yE>r   r"   )abs)r   mapepsilonepsr  s       r-    grad_numerical_of_coordinate_mapzBCMAEvolutionStrategy.ask.<locals>.grad_numerical_of_coordinate_map  sF     29$!c!f*-gC$SS\CCL%@AQWMMr,   c                 (   |ddt        |       z   z  n|}t        j                  t        |             }t        j                  t        |             }t	        |       D ]2  }||   ||<    || |z          || |z
        z
  d||   z  z  ||<   d||<   4 |S )zLreturn symmetric numerical gradient of func : R^n -> R.
                    r  r   r"   r   )r  r   r_  r   r   )r   funcr  r  gradeir   s          r-   grad_numerical_symz4CMAEvolutionStrategy.ask.<locals>.grad_numerical_sym  s     29$!c!f*-gC88CF+D#a&)B"1X #A1#'B<$q2v,#>1SV8"LQ !1 &  Kr,   z0gradient is used several times in this iterationr   )rF   r   r"   Fz6Exception {0} when setting _is_independent_sample[{1}]c                 ~    j                   j                  | t        t        |       d| ii      j                        S )NrI   )r   __call__r  rx   rE  )r   rA   s    r-   fpenaltyz*CMAEvolutionStrategy.ask.<locals>.fpenalty  s;    #'#8#8#A#A !=%(VQK1H#I477$T Tr,   z unknown boundary handling methodz when using gradfc                 >    j                   j                  |       S )Nr   )rE  rH   )r   boundary_repairrA   s    r-   _gp_for_num_gradz2CMAEvolutionStrategy.ask.<locals>._gp_for_num_grad  s    #ww}}QO}LLr,   r   zgradient with fixed variables was never tested, consider
  to implement a simple transformation of the objective instead
  see `cma.fitness_transformations.FixVariables`zSgradient dimension={0}!={1}=genotype dimension.This will lead to an exception soon.rG   r  rE   r  r   zgradient zero observedr   zx/mz  x-m=z    g=z      (x-m-g)/||g||=z,Gradient injection failed with exception {0}rI   rF   rW   )3r   r   ElapsedWCTimetimerticask_genorE  rH   r   r   r   rj  r   rp  r   rG  r   r,  r.  islinearlast_iteration_with_gradientr   AttributeErrorrs  r   r}  r  r   r   rF  rI  r   r   r   r  r   r   rx  r   dotBTrf  sumr:  r  r   r  rR   r  round_population)rA   numberxmean	sigma_facgradfr3   r4   pop_genor   	pop_phenor  r  index_for_gradientexphenograd_at_meangradpenr  r  gradgpr|   qr   r  r  s   `                      @@r-   r  zCMAEvolutionStrategy.askN  sx   ` ~~""" >>Q,,.DJJJNN 4==	DVD "*+!)A WW]]14/3/D/D/K/K # M!) 	 + dggw'?'?@## %U$)+A$(NNQ@ MM 1 '99;wXww'''' ). /
RN
 88DNNJ++ -1<@NN,0IIi,@B 9=D5 &)!S^A-=)>%?"DFKD//0BC = IIEu4373H3H3O3O ' Q(v)=)=>ww))d.C.C.O 11<<>&*OG!$"7"7H*.*?*?*F*F#D$9$9$02T #,,>uh,O"P..6&t'<'<(131> 5 567/01 1M=eEUVF#/&#87#BL 99./MM #M "/!A!AC |$.MM #I#)6#l*;TVV#DF GGIItwwyy{{DNN\4Q RR 1I384::#'66A:"3<4#'>>BFF47799dggiiRSm4T#T<V 4VH/0 Av$))D/		T^^R5G,5V!WZ^ZaZaZcZc!cfg gh  ! 8=tzz+/66A:*;@<>J@K 8K&+ !!34 49H/0''(@26..B 15/0t $ 5 5 < < 1> 1>	,- 6%+=!>!JK(%&89DIIEG(L109=O3PSWS\S\3\_k3kors  BC  tC  pD  FI  pI  3I  J "A&&y|(1+26.. ' B #$ 	%%66yAy+f & 
 ! DMM"Z%+VA/A%BD DDV " XLSSTUVWWXsn   -9Y#:Z4 AY( -Z4 Y8 P2Z4 (	Y51Z4 4Y55Z4 8	Z1%Z,&Z4 ,Z11Z4 4	[+=$[&&[+c                 r   ||dk  r| j                   j                  }| j                  dk(  r0t        | j                        t        | j
                        z   | _        | j                  d   rB| j                  | j                  d   d          | j                  | j                  d   d          |}|| j                  }n	 | j                  |   d   }ddk  rC| j                  d	   r4| j                  dk(  r	 d
| _        | j                   j#                  |      }|S || j$                  z  }| j                  rd
| _        g | _        g }|dkD  r|!t)        j*                  || j                        r| j                  dk  rt        | j                        | j                  dz
  kD  rgt-        j.                  dt        | j                        | j                  fz  dt        | j                        dz   z  z   | j                  dk(  rdndz          | j                  rt        |      |k\  rn| j                  j1                  d      }	| j3                  |	      | j4                  dz  | j                  d   z  kD  r| j7                  |	      }
nd}
|	|
| j$                  z  z  }	|j9                  |	       | j                  r| j
                  rQ|j9                  | j
                  j1                  d      | j                  z
  | j$                  z         | j
                  rQ| j:                  r| j                  dkD  st        |      dkD  rt        |      dk  rt=        d      |dxx   | j7                  |d         | j$                  z  z  cc<   |dxx   t?        j@                  |d   dz        t?        j@                  |d   dz        z  dz  z  cc<   t)        j*                  |d   |d          s;t-        jB                  ddd| j                        }|xr tE        jF                  |       | xjH                  t        |      z  c_$        | j                  dk  s| j:                  r| jH                  dk\  sJ |t        |      z
  }|dkD  r| jJ                  t?        jL                  | jN                  jQ                  |            z  }| jS                  | jN                         |r1t        | j                  d         dkD  rd|dd| j                  d   f<   | j                   jT                  r| j                  d   dk(  rtW        t)        jX                  | j                   jT                  |z  | j                  z              D ]j  }d|dz   z  t        |      kD  r?t-        j.                  d|| j                   jT                  fz  dd| j                  d        n|dd|z  z
      |dd|z  z
  <   l t        |      rot?        jZ                  ||f      }nWt]        |      }|t        |      k7  r.tE        jF                  dj_                  t        |      |             |t        |      k  sJ | j                  d   dkD  rX| j                  dk  rIt        |      r>| j`                  tb        ur,t-        jd                  dt        |      t        |      fz         |||z  z   }tg        |dt        |             D ]5  \  }}| j                  |t        | jh                        d| jh                  |<   7 d| _5        || _        | xj                  t        |      z  c_        |dkD  s|t        | jl                        k\  r&t        |      d
gz  to        d|f      d gz  z   | _6        |S # t        $ r' 	 | j                  |   d   }n# t        $ r Y nw xY wY w xY w)!a  get new candidate solutions in genotyp.

        Solutions are sampled from a multi-variate normal distribution.

        Arguments are
            `number`
                number of returned solutions, by default the
                population size `popsize` (AKA lambda).
            `xmean`
                distribution mean
            `sigma_fac`
                multiplier for internal sample width (standard
                deviation)
            `ignore_integer_variables`
                allows to not change integer variables at all which is in
                particular useful when a (small) mutation is added to a
                given solution.

        `ask_geno` returns a list of N-dimensional candidate solutions
        in genotyp representation and is called by `ask`.

        Details: updates the sample distribution if needed and might
        change the geno-pheno transformation during this update.

        :See: `ask`, `ask_and_eval`
    Nr   r   conditioncov_alleviater   rI   r  rE   CMA_AIIFr   r"   z/  %d special injected samples with popsize %d, zpopsize %d will be usedz/ and the warning is suppressed in the followingr'  rG   !CMA_injections_threshold_keep_lena4  Mean shift samples are expected but missing.
This happens if, for example, `ask` is called  more than once, without calling `tell`
(because the first call removes the samples from the injection list).
`cma.sigma_adaptation.CMAAdaptSigmaTPA` step-size adaptation generates mean shift
samples and relies on them. 
Using ``ask(1)`` for any subsequent calls of `ask` works OK and TPA works if the
first two samples from the first call are retained as first samples when calling `tell`. 
EXAMPLE: 
    X = es.ask()
    X.append(es.ask(1)[0])
    ...
    es.tell(X, ...)z@mean_shift_samples, but the first two solutions are not mirrors.r  r   r   CMA_mirrormethodz?fewer mirrors generated than given in parameter setting (%d<%d))rF   r  r   zC{0} injections were handled while only {1} sample(s) were asked forr   z6   %d pre-injected solutions will be used (popsize=%d))rF   indexcounterT)8r   r   r{  r   rz  ry  number_of_injectionsr   %alleviate_conditioning_in_coordinatesalleviate_conditioningr   r  KeyErrorr  r   r  aiir  r:  aryr   vequals_approximatelyr   r   r   mahalanobis_normr   ,_random_rescaling_factor_to_mahalanobis_sizer  rV  RuntimeErrorr   r  format_warningrG  r   r|  rf  r  rj  samplerk  r  r   sroundvstackr	   r   r   r   print_messager  r  evaluations_per_f_valuer}  r^  )rA   r  r   r  ignore_integer_variables	xmean_argr   r:  arinjr  	nominatormNiidr  r   r   s                   r-   r  zCMAEvolutionStrategy.ask_geno0  s   > >VaZWW__F))Q.D112D0012 % 99-.66tyyAY7Z[\7]^''		2J(KB(OP	=IIEU+F3 6yy#>>Q&$)!hhll6*
DJJ&  %DDH A:9,0H0HTXT]T]0^~~!5569II##$U'*4+H+H'I4<<&X%Y&?3tGdGdCehiCi&j%k ]a\j\jno\o'Xuw%y z
 //u:'1155a8 ((+dffckDIIFi<j.jj $ Q QRS TI !IY++Q // ..d::>>qADIIMQUQ[Q[[\ ..&&DNNQ,>#e*q.u:>&. , aDMMeTUhWZ^ZdZdddaRVVE!HaK0266%(A+3FFLL//a58)D,,0&(> NN	,A ./-C8==3C//3u:=/NNQ&d.E.E::a?A @ E
"!8..2::dggnnT.B#CCC  )'C		:M0N,ORS,S9:Atyy!4556wwDII.@$AQ$Fryy)9)9F)BT\\)QRSAAE{SX-++,m/0$''2B2B.C-D'13I6:nn56	8
 '*2A:&6CQU
O T 5zii-,CU# 006s5z60JLSZ'''IIi 1$!);E
  (88 X!$USX 6!7 8 eck!c+3u:./DAq!^^t??@3D,,Q/ 0 ()$&&#c(2&A:3t'B'B#CC*-e*w*>4F B!FB# +#D'
c   //6v>E 	s6    ^ 	^6^#"^6#	^/,^6.^//^65^6c           	          || j                   z
  }t        |      rF|t         | j                  d   dt	        |            d   dz        dz  | j                  |      z  z  }|| j                   z  }|S )z5change `x` like for injection, all on genotypic levelr   r   r   r"   rG   )r   r~  r  r   r   r  rA   r   s     r-   random_rescale_to_mahalanobisz2CMAEvolutionStrategy.random_rescale_to_mahalanobis  sn    		Mq6'TYYw'3q6215q893>AVAVWXAYYYA	TYYr,   c                 n   t        |      | j                  k7  r#t        dt        |      | j                  fz        t        |      s#t	        j
                  dd| j                         yt        j                   | j                  d   dt        |            d   d	z        d
z  | j                  |      z  S )z``self.mean + self._random_rescaling_factor_to_mahalanobis_size(y) * y``
        is guarantied to appear like from the sample distribution.
        zlen(y)=%d != %d=dimensionz,input was all-zeros, which is probably a bugr  r   r   r   r   r   r"   rG   )r   r   r  r~  r   r   r   r   r  r   r  )rA   r  s     r-   r  zACMAEvolutionStrategy._random_rescaling_factor_to_mahalanobis_size  s     q6TVV8CFDFF;KKLL1v NI*...: vv(dii(CF3A69:C?$BWBWXYBZZZr,   c                    	 | j                   |   d   | j                  z
  }|s|| j                  |      z  }| j                  |z
  }| j                  j                  || j                  j                        }| j                   j                  ||| j                         | j                  || j                  j                        }|S #  | j                  j                  || j                  j
                  d      | j                  z
  }Y xY w)a  return ``_round_int_variables(pheno(self.mean - (geno(x) - self.mean)))``

        and update `sent_solutions` and `_round_integer_variables.archive` archives.

        >>> import numpy as np, cma
        >>> es = cma.CMAEvolutionStrategy(np.random.randn(3), 1)  #doctest: +ELLIPSIS
        (3_w,...
        >>> x = np.random.randn(3)
        >>> assert cma.utilities.math.Mh.vequals_approximately(es.mean - (x - es.mean), es.get_mirror(x, preserve_length=True))
        >>> x = es.ask(1)[0]
        >>> vals = (es.get_mirror(x) - es.mean) / (x - es.mean)
        >>> assert cma.utilities.math.Mh.equals_approximately(sum(vals), len(vals) * vals[0])

        TODO: this implementation is yet experimental.

        TODO: this implementation includes geno-pheno transformation,
        however in general GP-transformation should be separated from
        specific code.

        Selectively mirrored sampling improves to a moderate extend but
        overadditively with active CMA for quite understandable reasons.

        Optimal number of mirrors are suprisingly small: 1,2,3 for
        maxlam=7,13,20 where 3,6,10 are the respective maximal possible
        mirrors that must be clearly suboptimal.

        rI   Tr   r   r  )r  )r  r   rE  rI   r   rP  r  rH   r   rR   r   _round_int_variablesr  r  )rA   r   preserve_lengthdxr  s        r-   
get_mirrorzCMAEvolutionStrategy.get_mirror  s    8	5$$Q'/$));B
 $CCBGGBIINGGMM!)>)>)E)EMF""11"G%%a1N1N1V1V%W	5aT-B-B-J-J#'  )+/995Bs   C ADc                    | j                   j                  }|t        |      }| j                  d   dk(  rUt	        j
                  | j                   j                  |z  | j                   j                  z        }| j                  | _        nd}||dz  k  sJ t        j                  |      | _        | j                  d   }g }| j                  ||||      }|| j                  }g }|
rt        |d      r|j                  } ||g| }t        |d      r/| xj                   |j                  z
  | j                  z
  z  c_        |r8| j                  d   dkD  r&| j                  dk  rt#        j$                  d	d
d       |dkD  r6| j                  dk  r't#        j$                  dd
d       nt'        |      dgz  }t)        |      D ]  }|j+                  d      |j+                  d      }}d}|
 |||      s{|
rt#        j$                  dd
d       |dz  }|r| j                  d||      d   }nZ|||z
  k\  rR|||z
  k(  r#t        j,                  |      dd|z
  d   | _        | j/                  || j                  |dz
  |z
              }d}ddk  r$| j0                  dz  | j3                  ||z
        z  }|	dk(  r	 ||g| n |||	|z  ||z
  z  z   g| } |||      rU|dkD  rP ||gt)        t        |dz
              D cg c]%  }|	dk(  r	 ||g| n |||	|z  ||z
  z  z   g| ' c}z         }|dz   dz  dk(  r$t#        j$                  d|| j                  fz         |p |||      s{|j5                  |       |j5                  |        t        |      | _        t9        d |D              rt)        t'        |            D cg c]!  }||   t#        j:                  ||         r|# }}t#        j$                  dt=        |dd       t'        |      dkD  rdndz   dt=        |      dd| j                         ||fS c c}w c c}w )a?  sample `number` solutions and evaluate them on `func`.

        Each solution ``s`` is resampled until
        ``self.is_feasible(s, func(s)) is True``.

        Arguments
        ---------
        `func`:
            objective function, ``func(x)`` accepts a `numpy.ndarray`
            and returns a scalar ``if not parallel_mode``. Else returns a
            `list` of scalars from a `list` of `numpy.ndarray`.
        `args`:
            additional parameters for `func`
        `gradf`:
            gradient of objective function, ``g = gradf(x, *args)``
            must satisfy ``len(g) == len(x)``
        `number`:
            number of solutions to be sampled, by default
            population size ``popsize`` (AKA lambda)
        `xmean`:
            mean for sampling the solutions, by default ``self.mean``.
        `sigma_fac`:
            multiplier for sampling width, standard deviation, for example
            to get a small perturbation of solution `xmean`
        `evaluations`:
            number of evaluations for each sampled solution
        `aggregation`:
            function that aggregates `evaluations` values to
            as single value.
        `kappa`:
            multiplier used for the evaluation of the solutions, in
            that ``func(m + kappa*(x - m))`` is the f-value for ``x``.

        Return
        ------
        ``(X, fit)``, where

        - `X`: list of solutions
        - `fit`: list of respective function values

        Details
        -------
        While ``not self.is_feasible(x, func(x))`` new solutions are
        sampled. By default
        ``self.is_feasible == cma.feasible == lambda x, f: f not in (None, np.nan)``.
        The argument to `func` can be freely modified within `func`.

        Depending on the ``CMA_mirrors`` option, some solutions are not
        sampled independently but as mirrors of other bad solutions. This
        is a simple derandomization that can save 10-30% of the
        evaluations in particular with small populations, for example on
        the cigar function.

        Example
        -------
        >>> import cma
        >>> x0, sigma0 = 8 * [10], 1  # 8-D
        >>> es = cma.CMAEvolutionStrategy(x0, sigma0)  #doctest: +ELLIPSIS
        (5_w,...
        >>> while not es.stop():
        ...     X, fit = es.ask_and_eval(cma.ff.elli)  # handles NaN with resampling
        ...     es.tell(X, fit)  # pass on fitness values
        ...     es.disp(20) # print every 20-th iteration  #doctest: +ELLIPSIS
        Iterat #Fevals...
        >>> print('terminated on ' + str(es.stop()))  #doctest: +ELLIPSIS
        terminated on ...

        A single iteration step can be expressed in one line, such that
        an entire optimization after initialization becomes::

            while not es.stop():
                es.tell(*es.ask_and_eval(cma.ff.elli))

        Nr  r   r   r"   is_feasible)r   r  r3   rh   z0selective mirrors will not work in parallel modeask_and_evalr   z6aggregating evaluations will not work in parallel moder   zrejection sampling will not work in parallel mode unless the parallel_objective makes a distinction
between called with a numpy array vs a list (of numpy arrays) as first argument.r  rE   rG     z=  %d solutions rejected (f-value NaN or None) at iteration %dc              3   R   K   | ]  }|d u xs t        j                  |       ! y wrW   r   r?  rq   fs     r-   rt   z4CMAEvolutionStrategy.ask_and_eval.<locals>.<genexpr>  s%     9SqDy+ELLO+S   %'z	f-values    z...r'  z  contain None or NaN at indices ask_and_tell)r   r   rB  r   r   r  r  r   _mirrormethod1_doner   arangemirrors_idxr  r   ro  rh   r   r   r   r   r   r   argsortr1  r   r  r  r"  r~  r?  r   )rA   r  r3   r  r  r   r  rh   aggregationkappaparallel_moder   nmirrorsr3  r  X_firstXevals0	fit_firstr{   r   r9  rejectedlength_normalizer_ir   r  s                              r-   r4  z!CMAEvolutionStrategy.ask_and_eval:  s   Z ''//&kG99'(A-yy!1!1G!;dggoo!MNH'+~~D$ H7a<'''99X.ii. ((7%u4(H=IIEt]+))W,t,It]+4#3#3f#<t||#KKDII&89A=$..STBT##F"$:< Q4>>A#5##L"$:< Gv-IwA;;q>9==#3qAH);q!#4 ''< '(>@ AE95a8A'H,,Gh..+-::c?2b8mB;N+O($*:*:7Q;?*K(LMA %&!6 )-d6K6KAPUI6V(V% ',qjDNTN):!:a%i!HH     q!$q#QC5:3{Q;O5P+R5Pr ?DqjDNTN,0AR9RVWZ_V_9`1`,hcg,h-i5P+R %R SA qLD(A-''(g#T^^4)5 6Q );q!#4T JJqMHHQK]  ^ (+;'7$9S99$SX ?!1v~c!f)= D ?#&s3Bx=SX]EPR#S#&t9!. !/ 6 $0 #v%+R?s   *Q&Qc                 L   | j                   s| j                  rt        d      g }| j                  r| j                  | j
                  z
  g}|j                  |d           |d   j                  J 	 |d   d   dk(  r=t        j                  |d   dk(        r"t        j                  ddd| j                         | j                  d	   r)|j                  | j                  j!                                | j"                  j$                  r| j                  d
   dk(  s:| j                  d
   dk(  r`t'        | d      r| j(                  | j                  dz
  k  r8t+        |      }|| j-                         z  }t/        |t+        |            | _        || _         |S # t        $ r Y /w xY w)aL  provide genotypic directions for TPA and selective mirroring,
        with no specific length normalization, to be used in the
        coming iteration.

        Details:
        This method is called in the end of `tell`. The result is
        assigned to ``self.pop_injection_directions`` and used in
        `ask_geno`.

        zFound unused injected direction/solutions.
                This could be a bug in the calling order/logics or due to
                a too small popsize used in `ask()` or when only using
                `ask(1)` repeatedly. r   r   r   g        zzero mean shift encountered_prepare_injection_directionsr   pc_line_samplesr  r"   r=  )rz  ry  r  rV  r   mean_oldr  baser  r   r  r   r   r   r   r`  r   r   r  ro  r=  r   get_selective_mirrorsr   _indices_of_selective_mirrors)rA   r  i0s      r-   rM  z2CMAEvolutionStrategy._prepare_injection_directions  su    ((D,H,H ) * * ""99t}},-CJJAwA+++2wqzQ266#b'S.#9##$A>5t~~G 99&'JJtww||~&77		,-2II01Q6#D*?@004>>A3EESB4--//C16r3s81DD.(+%
! "'4's   !F 	F#"F#c                    || j                   j                  }t        | d      sg | _        g }t	        d|dz         D ]}  }d| j
                  d   v s'| j                  j                  |    | j                  vs;|j                  | j                  | j                  | j                  j                  |       z
          t        |      |t        | j                        z
  k\  sJ |S )a  get mirror genotypic directions from worst solutions.

        Details:

        To be called after the mean has been updated.

        Takes the last ``number=sp.lam_mirr`` entries in the
        ``self.pop[self.fit.idx]`` as solutions to be mirrored.

        Do not take a mirror if it is suspected to stem from a
        previous mirror in order to not go endlessly back and forth.
        rR  r   zall-selective-mirrorsr  )r   r  ro  rR  r   r   r  r  r  rO  r   r   )rA   r  r   r   s       r-   rQ  z*CMAEvolutionStrategy.get_selective_mirrors	  s     >WW%%Ft<=13D.q&1*%A&$))D/9TXX\\1"=MUYUwUw=w

4==488DHHLL!4D+EEF & 3x6C(J(J$KKKKK
r,   c           
      4   | j                   d   rt        j                  |      s|S |d}|d }n|du rd }| j                  | j                  j
                  z  t        j                  | j                  j                        z  }t        | j                  j                  |      D ]p  \  }} ||      s| j                   d   D ]P  }t        j                  ||         |||   z  kD  s%||xx   |||   z  t        j                  ||         z  z  cc<   R r |S )a6  versatile: limit absolute values of int-coordinates in vector list `dX`

         relative to the current sample standard deviations and by default
         only when the respective recombination weight is negative.

        This function is currently not in effect (called with threshold=inf)
        and not guarantied to stay as is.

        ``dX == pop_sorted - mold`` where ``pop_sorted`` is a genotype.

        ``threshold=2.3`` by default.
        
        A 2.3-sigma threshold affects 2 x 1.1% of the unmodified
        (nonsorted) normal samples.
        r   gffffff@c                     | dk  S r=   r+   ws    r-   recombination_weight_conditionzZCMAEvolutionStrategy.limit_integer_relative_deltas.<locals>.recombination_weight_condition>	  s    1ur,   Tc                      yNTr+   rW  s    r-   rY  zZCMAEvolutionStrategy.limit_integer_relative_deltas.<locals>.recombination_weight_conditionA	  s    r,   )r   r   rg  r:  rf  r  sqrtrj  rv  zipr   rX  r  )rA   dX	thresholdrY  rk   rX  r0  r   s           r-   limit_integer_relative_deltasz2CMAEvolutionStrategy.limit_integer_relative_deltas(	  s    " yy,-R[[5KII)1+t3zzDNN222RWWTWW=N=N5OO"-EAr-a0#67Avvbe}y47'::1T!W!4rvvbe}!DD 8 . 	r,   c                     | j                  |s|r$ | j                  j                  |g|i |      S | j                  j                  |d| j                  j                              S )aI  return integer-rounded phenotype depending on `round_integer_variables` module setting.

        Without further arguments, `self.gp.pheno` is called with
        ``copy=True, into_bounds=self.boundary_handler.repair`` as
        additional arguments, otherwise ``*args, **kwargs`` are passed
        to `self.gp.pheno`.
        Tr  )r.  rE  rH   r   r   )rA   solutionr3   r4   s       r-   r   z!CMAEvolutionStrategy.to_phenotypeL	  sq     ((/3v *7x)Q$)Q&)Q [ 	[)-xd<@<Q<Q<X<X *7 *Z[ 	[r,   c                    t         rt        | j                  d         s|S t        j                  | j                  j                  d| j                  d               }|s|rt        j                  |d      n|}	 t        j                  ||         ||<   |r|||<   |S # t        $ r% |D ]  }t        j                  ||         ||<    Y 6w xY w)a  return `solution` with integer variables rounded
   
        depending on the `round_integer_variables` module setting and based
        on the ``integer_variables`` option. `solution` is interpreted as
        phenotype. Fixed variables are not rounded.

        Insert original solution in `archive` like ``archive[rounded_solution]
        = solution`` if ``archive is not None``.

        When archiving, create a new solution array copy first, as with
        `copy_when_changed`.

        Details: This method relies somewhat on
        ``len(opts['integer_variables']) ==
        len(opts['_pheno_integer_variables'])``.

        TODO: inserting in the archive here may be too obfuscating?
        However, the conditional copying looks more practical here than
        outside.
    r   _pheno_integer_variablesTr   )	r  r   r   r   r  rN   r	   r  r  )rA   rb  copy_when_changedr  r  	solution_r   s          r-   r.  z)CMAEvolutionStrategy._round_int_variablesY	  s    * 'c$))<O2P.QOjj'A'+yy1D'EG H - XXhT2 		5XXin5IcN
 !)GI  	5!xx4	! 	5s   ;B +CCc                 .    | j                  |||||      S )a-  pass objective function values to prepare for next iteration.

        This core procedure of the CMA-ES algorithm updates all state
        variables, in particular the two evolution paths, the distribution
        mean, the covariance matrix and a step-size.

        CAVEAT: the argument positions are different for `tell` and `tell2`.

        Arguments
        ---------
        `solutions`
            list or array of candidate solution points (of
            type `numpy.ndarray`), most presumably before
            delivered by method `ask()` or `ask_and_eval()`.
        `function_values`
            list or array of objective function values
            corresponding to the respective points. Beside for termination
            decisions, only the ranking of values in `function_values`
            is used.
        `constraints_values`
            can be used as _positional_ argument in 3rd position only with
            `tell2`. A list of inequality constraints values for each
            solution in `solutions`. Feasible solutions have a nonpositive
            value of all constraints.
        `check_points`
            If ``check_points is None``, only solutions that are not generated
            by `ask()` are possibly clipped (recommended). ``False`` does not clip
            any solution (not recommended).
            If ``True``, clips solutions that realize long steps (i.e. also
            those that are unlikely to be generated with `ask()`). `check_points`
            can be a list of indices to be checked in solutions.
        `copy`
            ``solutions`` can be modified in this routine, if ``copy is False``

        Details
        -------
        `tell()` updates the parameters of the multivariate
        normal search distribution, namely covariance matrix and
        step-size and updates also the attributes ``countiter`` and
        ``countevals``. To check the points for consistency is quadratic
        in the dimension (like sampling points).

        Bugs
        ----
        The effect of changing the solutions delivered by `ask()`
        depends on whether boundary handling is applied. With boundary
        handling, modifications are disregarded. This is necessary to
        apply the default boundary handling that uses unrepaired
        solutions but might change in future.

        Example
        -------

        >>> import cma
        >>> func = cma.ff.sphere  # choose objective function
        >>> funb = cma.BoundDomainTransform(func, [1, None])  # set bounds
        >>> def cons(x):  # define constraints
        ...     return [2 - x[0]]
        >>> consb = cma.BoundDomainTransform(cons, [1, None])
        >>> es = cma.CMAEvolutionStrategy(np.random.rand(2) / 3, 1.5)  # doctest:+ELLIPSIS
        (3_...
        >>> while not es.stop():
        ...    X = es.ask()
        ...    es.tell2(X, [funb(x) for x in X], [consb(x) for x in X])
        >>> assert all(funb.transform(es.best_feasible.x) >= [2 - 1e-5, 1 - 1e-5])
        >>> assert all(funb.transform(es.best_feasible.x) <= [2 + 1e-5, 1 + 1e-5])

        The value of `es.result.xbest` is not reliable with constraints,
        because a dynamic augmented Lagrangian is optimized. Instead, use
        `es.result.xfavorite` or `es.best_feasible.x`.

        :See: class `CMAEvolutionStrategy`, `ask`, `ask_and_eval`, `fmin`
    )constraints_valuescheck_pointsr   )tell2)rA   	solutionsfunction_valuesri  r   rh  s         r-   tellzCMAEvolutionStrategy.tell	  s(    V zz)_-?'3#  % 	%r,   c                 B   | j                   rt        d      t               j                         D ci c]  \  }}|dk7  s|| c}}| _        t        |      }|t        |      k7  rt        dt        |      |fz        || j                  j                  z   dk  rt        dt        |      z   dz   dz         t        j                  |d         s	 t        j                  |d   d         rx| j                  d	k  rVt        j                  d
t        |d         dt        t        |d               d      }	|	xr t!        j"                  |	       |D 
cg c]  }
|
d   	 }}
nt        d      	 t'        d |D              rt)        |      D cg c]
  \  }}|	| }}}t)        |      D cg c]   \  }}|	t        j*                  |      s|" }}}t        j,                  |D cg c]  }|t        j*                  |      s| c}      }	t        j.                  dt        |      dt        |      dt        |	      dd| j                         ||z   D ]  }|	||<   	 t1        d |D              st)        |      D cg c]%  \  }}t        j2                  t5        |            s|' }}}t        j.                  dt        |      dt        |D cg c]  }||   	 c}      ddd| j                         |'|t        |      k7  rt        dt        |      |fz        | j6                  | j8                  k  st;        | j<                        set        j.                  d| j8                  | j6                  t        | j>                        t        | j@                        z   fz  dd| j                         d| _        | xj                  d	z  c_        | xjB                  || jD                  z  z  c_!        | jF                  jI                  || jJ                  || jB                         || jM                  |||      }| jN                  jQ                  |tR        |dv       }d!dk  r[|}|D cg c]  }| jT                  jW                  ||        }}| jT                  jY                  ||tR        | jZ                  |dv"       | j\                  }| j                  }d!dk  rJ||j^                  k7  r;t        j.                  d#       | j                  ja                  | jb                  |       d	dk  r||j^                  d$z   kD  s&||j^                  d$z
  k  s||j^                  k  rN|d%k  rId&}	t        j.                  d'je                  |	t        |      |j^                  |	      dd| j                         ||jf                  jh                  k  r/t        d(je                  ||jf                  jh                              | jb                  d)   d*u xs | j                  | jb                  d)   k  }|sYtk        | jl                  tn        jp                        r5to        jr                  |      | _6        | ju                  | jl                         | jw                  |dd$ |d$d        | jx                  } | jz                  jI                  ||       || jJ                  | j|                        |_?        t        j                  |j~                        |z   |_A        t        j                  |j                        |_C        t        |      |_<        |j                  j                  d|jx                  d          t        |jx                        d$z  }t5        t        |jx                        d$z  r|jx                  |   n$|jx                  |d	z
     |jx                  |   z   d$z        |_        | j                  d%z  dk(  rO|j                  j                  d|jx                  d          |j                  j                  d|j,                         t        |j                        d+kD  r4|j                  j                          |j                  j                          t        |j                        d,d-|z  |j^                  z  z   kD  r|j                  j                          |j                  |j,                  |_J        |j                  |j,                  kD  r|j,                  |_K        |j,                  |j                  k  rd|_M        n|xj                  d	z  c_M        |j,                  |_L        d| _N        g }t)        |      D ]  \  }}d	dk  rU|| j|                  j                  || jz                  j                  |d.dg d/fvr| j                  nd| jJ                  0      gz  }| jJ                  j                  |d      }t        s|| jT                  j                  ||||   1        | jJ                  | jT                  fD ]C  }|j                  t        t        d$|j^                  z  d2f      d-|j^                  z  f             E || _I        | j                  j                  |        | j                  d	kD  r| j                  | _Y        | j                  | _X        | j                  }|dd.dg d/fvr)	 t        |      r|}D ]  }| j                  ||           t        j                  |      |j                     }| j                  |      }d}| jb                  d3   d4k(  rt        | d5      s$t        j.                  d6dd| j                         n|jx                  d   | j                  kD  r| j                  j                         }| j                  |       t        j                  |gt        |      z         }d	}t        j$                  d7| j                  |jx                  d   fz  dd| j                  | jb                  d8   9       n| jb                  d3   r| jF                  j                  |jx                  d   k  r| jF                  j                  | jF                  j                  g}nh| j|                  j                  t        | jF                  j                  d*:      | jz                  j                  d.:      g}t        j.                  d;d       | j                  |d          t        j                  |d   gt        |      z         }d	}|| _N        | j                  |d|jf                  jh                   | j                         t        j                  |jf                  j                  |d|jf                  jh                         | _Z        |j                  d	k7  rD| xj                  |j                  z  c_Z        | xj                  d	|j                  z
  |z  z  c_Z        d!dk  r| jb                  d<   r|r| j                  j                  t        d	| jb                  d<   |z  d=z  d$z   | j                  jf                  j                  d=z  | j                  j                  z  | j                  | j                  |z
        z  z        z  }n| j                  j                  }d!dk  r,| xj                  t;        | j                  d$z        gz  c_n        d!dk  r| xj                  | j                  jf                  j                  d=z  t;        d>| j                  z  t        j                  | j                  j                  | j                  |z
        z  d$z        d=z  z  | j                  z  |d=z  z  |z  gz  c_n        |j                  }| jb                  d?   | jb                  d@   z  | jl                  j                  |jf                  j                  |jf                  j                  A      jW                  dB|j                        z  } | jb                  d?   | jb                  dC   z  | jl                  j                         jW                  dD|j                        z  }!|r$|j                  |j                  |j                  }!} }| j                  j                  |       }"d!dk  r| j                  d	k(  rt        dE       t        r'|"s%| j                  j                  | j                         d!dk  r#|"s!t        t        | j                        dFz          t         j                  sd	}"| j                  d	k(  rt        dG       | d	d	|"d$z  z
  |z  d$|z
  z  z
  z  }#d	|z
  | j                  z  |"|d$|z
  z  | j                  jf                  j                  z  d=z  | j                  z  |z  z  | j                  |z
  z  | j                  j                  z  z   | _        | jb                  dH   r,| jl                  j                  | j                        | _        | j                  j                  | j                  jf                  j                  | jb                  d@   | jb                  dC   I      }$|$dJ   }%d	|%z
  | j                  z  |"|%d$|%z
  z  | j                  jf                  j                  z  d=z  | j                  z  |z  z  | j                  |z
  z  z   | _        	 | j                   | j                  ||z
  t        j                  t        j                        }&|#|!z   dkD  r|jg                  t        |&            }'|#g|'D (cg c]  }(|!|(z  	 c}(z   })|$dB   g|'D (cg c]
  }(|$dD   |(z   c}(z   }*t        |&      t        |jf                        kD  r|#g|jf                  D (cg c]  }(|!|(z  	 c}(z   }+|+dd	|jf                  jh                  z    t        |&      t        |jf                        z
  dgz  z   |+d	|jf                  jh                  z   d z   }+|)|+k(  sJ dK| jb                  d<   v r8t        j                  |)      })|)|)dkD  xx   d	| jb                  d<   dK   z   z  cc<   t        |)      t        |&      d	z   k(  sJ |D ]O  }|d	|z   z  }|)|   dk  r|)|xx   | jb                  dL   z  cc<   |*|   dk  s6|*|xx   | jb                  dL   z  cc<   Q |r| j                  jI                  | jl                  j                  | j                        gt        | jl                  j                  |&| j                  | j                  j                  z  z              z   t        j                  d$      t        j                  |)      z  | jb                  dM   N       n&|&| j                  | j                  j                  z  z  },| jb                  dO   rt        | jl                  dP      r|*D (cg c]<  }(| jb                  d?   | jb                  dO   z  | jl                  j                  z  |(z  > }-}(| j                  jI                  | jl                  j                  | j                  | j                  j                  z        g|,D .cg c]  }.| jl                  j                  |.        c}.z   |-| jb                  dM   N       d!dk  r(|&| j                  | j                  j                  z  z  },| j                  }/t         j                   r{	 | j\                  d=z  t        j"                  j%                  | j                  j&                        z  }0|0| jl                  j)                  | j                  j&                        z  }/| jl                  jI                  | |#dQz   z  d=z  |/z  gt        |,      z   |)       t'        t        j                  | jl                  j*                        dk        r,t        dRt        | jl                  j*                        z        | ju                  | jl                         | j                  | _        	 | xj                  | j                  j/                  | |S      z  c_r        | jb                  dT   r| jx                  j                  | jb                  dT   k\  rt        | dU      sd-dgz  | _        | j                  | jx                  j                  | j,                  | j                  f| j2                  | j                  t        | j2                        z  <   | j,                  | _r        | j5                          d!dk  rt'        | j                  | j                  j                  z  | j6                  d=z  z  t        j                  | jb                  dV         k        rt        t        j                  | jb                  dV         | j                  | j6                  d=z  z  z        | _r        t1        | j                  | j                  z  | j6                  d=z  z  dWt        j                  | jb                  dV         z  k\        sJ t'        | j                  | j                  j                  z  | j6                  d=z  z  t        j                  | jb                  dX         kD        rOt        t        j                  | jb                  dX         | j                  | j6                  d=z  z  z        | _r        | j                  t        | j                        z  | jb                  dY   k  r3t5        | jb                  dY   t        | j                        z        | _r        t8        d	kD  r| j                  t8        | j:                  z  kD  r	 t5        | j                  t        | jl                  j*                        d=z  z        }1|1d	kD  rq	 | xjl                  |1z  c_6        | xj                  |1d=z  z  c_r        | xj,                  |1d=z  z  c_        | jb                  dZxx   |1d=z  z  cc<   | ju                          t         j>                  rtA        t         j>                        rW| xj                  t        j>                  | j                        t        j>                  | j                        z  z  c_Z        nz| xj                  t        jB                  t;        t        jD                  | j                              t;        t        jD                  | j                              z        z  c_Z        d!dk  rtk        | jz                  tF              ry| jz                  jI                  | j                        sSt        | jz                  j                  | jz                  jK                  | j                  d.[      d.[      d.:      | _Z        tL        r| jO                         | _        | jb                  d8   d\kD  r}| j                  dk  rntk        | j                  tP              sSt        | j>                        r>t        j$                  d]t        | j>                        | j                  d$k(  rd^nd_fz         d| _        g | _I        | j                  | jT                  dd | jV                  jY                  | jb                  d`         jI                  | j                         d*| _         	 | jZ                  j]                          | j                  ja                          d!dk  r6| j                  ja                  | jb                  | jb                  d?   db       yyc c}}w c c}
w #  t        j$                  d|z  ddd| j                          xY wc c}}w c c}}w c c}w c c}}w c c}w c c}w # t        $ r t        |j^                        }Y Hw xY w# t        $ r Y 2w xY wc c}(w c c}(w c c}(w c c}(w c c}.w #   xY w# t0        t        f$ r! | j                  jI                  | |S       Y w xY w# t<        $ r Y w xY w# t<        $ r Y +w xY w# t        $ r@ t!        j"                  da| j                  z         t        j^                         | _        Y w xY w)cz
see `tell`z4tell can currently only be called once per iterationrA   z)#f-values = %d must equal #solutions = %drE   zpopulation size z is too small with option zCMA_mirrors * popsize < 0.5r   r   z[function_values is not a list of scalars,
                        the first element equals z with non-scalar type zq.
                        Using now ``[v[0] for v in function_values]`` instead (further warnings are suppressed)z3objective function values must be a list of scalarszfunction values=%srm  r   	   )method_name
class_namer   rF   c              3   R   K   | ]  }|d u xs t        j                  |       ! y wrW   r7  r8  s     r-   rt   z-CMAEvolutionStrategy.tell2.<locals>.<genexpr>	  s%     E_qDy+ELLO+_r:  Nzfunction values with index /z2 are nan/None and will be set to the median value r  c              3   X   K   | ]"  }t        j                  t        |             $ y wrW   )r   rg  r  )rq   vals     r-   rt   z-CMAEvolutionStrategy.tell2.<locals>.<genexpr>	  s     Fos2;;uSz*os   (*z are not finite but .z3#constraints_values = %d must equal #solutions = %dzno independent samples generated because the
                number of injected solutions, %d, equals the number of
                solutions asked, %d, where %d solutions remain to be injected
                r  )r   F)revert_modifiedr   r  )rw  r   r   z3population size has changed, recomputing parametersr"   r   z/The number of solutions passed to `tell` shouldz{0} generally be the same as (or close to) the population size,
  was: len(solutions)={1} != {2}=popsize.
  To suppress this warning execute
warnings.filterwarnings('ignore', message='{3}.*')
zLnot enough solutions passed to function tell (passed solutions={0} < mu={1})r   Tg     @rD   r;  Fr+   )r   r   r  )rP   rJ   r5  CMA_elitistinitialf0zHSet attribute `es.f0` to make initial elitism
available or use cma.fmin.zinitial solution injected %f<%fr   r   r   zgenotype for elitist not foundr  rG   r   r  CMA_rankoner  r  
CMA_rankmur  zparameters modifiedz: hsig-stallzhsig=1CSA_invariant_path)	c1_factor
cmu_factorccinc_cmu_posCMA_active_injectedr   )integer_indicesr  beta_diagonal_accelerationr  z{A sampler variance has become negative after the update, this must be considered as a bug.
Variances `self.sm.variances`=%s)rl  +stall_sigma_change_on_divergence_iterations(_stall_sigma_change_on_divergence_eventsr  gv?r   mindx
tolupsigma)copy_if_changedr   z*   %d directions prepared for injection %sz (no more messages will be shown)r'  tolxstagnationzCMAEvolutionStrategy.tell(countiter=%d): "timer" attribute not found, probably because `ask` was never called. 
Timing is likely to work only until `tell` is called (again), because `tic` will never be called again afterwards.)ccovfacr   )r  r  rw   items_tell2_argsr   r  r   r  r   r   rh  r   r   r  r   rG  r   r!  r~  r  r?  r  r   r  rg  r  r{  r  r  r}  rz  ry  r   r"  r   r  r  _constraints_handlingr  unrounded_population&round_integer_variables_revert_changesr  rN   catch_and_truncater.  r   r   setr   r   rX  r  r   rj  r   ri  rp  rk  _record_rankingsr  r   rE  r  r  r  r@  r  sortedr  rR   r  r  r   r  r  r  r  
pop_sortedrI   rP  repair_genotyper  r^   rs  r^  r   check_consistencyrO  mean_old_oldr   r  r   !_clean_injected_solutions_archivero  rz  rR  r   r+  r  r9  x_genor	   r   rY  r  positive_weightscmeanr  r  r  rx  r  r  r:  r  rq  rr  r  r  cc_seprm  rn  hsigr  _record_hsigr  r  r   _hsigr`  rf  r  transform_inverse_path_for_invariant_updatera  isotropic_mean_shiftr  r`  r   integer_active_limit_std3integer_active_limit_recombination_weight_conditionlogr  
_ps_for_pclinalgnormps	transformrv  
_sigma_oldupdate2r  r  ru  rw  _redistribute_sigma_abover9  r  _stationary_spherer/   r\  squarer   rJ  r   _new_injectionsrM  r   r|  rQ  r  
set_paramsr  pauser  r   )2rA   rk  rl  rh  ri  r   r{   r|   r  r'  ru  r   r9  idx_noneidx_nanr  
solutions_r  r   r   flg_diagonalr  r   s_genoarcmoldinjected_solutions_indicesprepended_solutionsx_elitxpr  r  r  r  r  c1a	dd_paramscc2pop_zero_weightsrX  sampler_weightssampler_weights_dd_sampler_weightspop_zero_encodedwszr`  facalphas2                                                     r-   rj  zCMAEvolutionStrategy.tell2	  sH   
 UVV .4X^^-=M-=TQfAqD-=M)n#o&&H #O 4c:; < <!!!A%/#c(:9::; < < {{?1-.;;q1!45~~*!00 03?13E/FDQ`abQcLdHe2g " $%#9q)99H&I#s1vO&I$%Z[[ 'J E_EE&/&@N&@daAI&@HN%.%?e%?TQ1=UZUaUabcUdq%?Ge		o EomELLO o E FA#&w<XA!HIN 6H x'%&" (FoFF!*?!; 1!;A++eAh/ !;C 1#&s8Sc1Rc/!2Dc1R-S!UV[ 6H )cS9K5L.LR #$6 7=> ? ? ))T-F-FF334 ! 00554889C@\@\<]]_!_ 2DNND *+&!3!=!===		,,ot	P )"88(:IGO 11FFy,R!-Z!? G A	 6"J9BCA))!Q/ICLL++Iz,R+/+D+D!-Z!? , A FFWW 6cRZZ' UVGGKK		3'q5cBJJN*cBJJN.B"**qAA !% &,VAs9~rzz1%M &(>P  @$fS"**--8: : yy0D8 F..DIIn,EE 	
477G4Q4Q R..q1DG  )obq1?123FG hh IT**11/4HTXTgTgimipipq
 ::cjj1OC**S--.) 	3771:&LASWW)93771:!$1
!:a ?A
 ^^aA%LL3771:.NN!!!SZZ0s||s"LLNN sxx=2Q 333HHLLN;;**CK>>CJJ& ZZCN::,,,#$C   A% !jj i(DAq1uQ(,(=(=(E(E
 =IQVXY[]_aPb<bD$8$8hl$($7$7 % 9 : : ((,,Q5F!f&8##AV_Q=O#P ) ''6COOCa"**nd%;!<b2::o NOP 7 **40>>A $D		}}
 eQB77(|$&C $$SV,  jjocgg&%)%K%KC%P"  99]#y04&##12DNND dgg%*226:jj&DI!56&'###$E%)WWcggaj$9%:%'=$(NNDIIi<PR YY}%$))++
*Byy+ii&&'
 ggll54#@#'#8#8#@#@(- # / 0 ##$DfM..r!u5**beWtCy01C"#s>BJJMM2DII> FF2::66NRZZ]]8KL	88q=II!III!bhh,$..I 6diio,GGMMCTYYt_q-@3,F,J&&+dggmm;%%dii$&678,9 %: :E GGMME 63tyy!|#4"556477??#8#8##=b466kRVVDFFHHdii$6F%GG!KLcQ$Rzz$"$%sF$+-2$3 #4 4 UUYYx 499]#;;dgg>P>P**""

(:(: ?Q ?<<?Cbee<LMii!DIIl$;;dgg>P>P>R>V>VW\^`^d^d>ee))RYY

CB $$T*6 ~~"+, $$T^^46c$..)N:;D~~"h
 AT1W*a"f556r6TWW$t1r6]TWW__%:%::S@4::M (!$(II$4(68<8N8N(O O 99)*.2gg.G.G.PD+NN--dggoo.C.C26))M2J3799\3J . *	 oGtxx'$AG_tww'<'<<sBTZZO +!$(II$4+6 6	%%
 55d
*CC*^^` 9q= zz#h-0H"e&A1sQw&AAO"+D/!2@H6J@H1)E"2Q"66J "J 8}s2::.$'5RZZ+HZC!GZ+H#H ()9!BJJMM/:XRZZ8QC?@(2::==)9:; ! '*::::		$/"$**_"=! 34DIIdOM<Z8ZZ4 '3x=1+<<<</ Q,,,"1%)#A&$))4I*JJ&%a(1,&q)TYY7L-MM) 0 %%WW..tww78228)-dnn6L6L)L4N O PP FF1I

? ;;$(II.A$B & D $,tzzDNN<R<R/R#S 9945'$''Kg:hJ\^J\Q ))H-		:Q0RR''<<=?@AJ\  ^NN))22488dnn>T>T3TUVCSTCSaTWW66q9CSTU(,		2E(F	 * H 6'/4::@V@V3V'W$WW((""ffckBIINN4;K;K;N;N,OO "DGG$5$5 ,,//%1 1 sU{!3c 9B >?"#34 5-/ 2::dgg//0145" $FHKDGGL]L]H^$_ ` ` 	TWW% **	KJJ$**2248G 3 I IJ 99BC))TYY7d-ee4!KL@BdV=  9 94??DJJ\X 99NNS)V)V%WWY DJ  64:: 6 66#E

499X#678 9 DIIh,?!@%)^^dggsl%B"D E
4::6#E2::dii.A#BBC D D DTZZ$.."8"88477C<G

499X#678 9 DIIh,?!@!%$''3,!>"@ A
 ::DFF#dii&88tyy1CK?@DJ$q(

6DD/djj3tww/@/@+A3+FFG 19/5( 

eSj0
5#:5		,/5#:=/,,. ((
556		j;;DMMJ(;;DIIFG H	 		RWWS4==)A%B%(499)=%>&? @ @	 6j!6!6G--::499Ed33;;%%,,TYY,N$) < +168DI ,0,N,N,PD)		)$q(T^^a-?t//1ABD112##$P%()F)F%G%)^^q%8 &H>@%B%B C 34D/"&))Q  ++DII6F,GHOOPTPYPYZ 	/JJ 	  "6GGKK		499X+>KJ _ N& 'J##$8?$J06CY,-I NeE1 2SP Dr  (BJJ'(P  		 'B6J ,IB^ U" "E  $^4 	K##D/#J	K\ %   f  	/MM Q !NN	+ ,
 ,,.DJ	/s<  A~<A~<BA A#A 
A4A42
A:=A:A:- B@ 	*B@B@2#B@!B@ LB@: M5BANBAOBAX!ABAZ>#BA
]A:BA$ b1BA* o#9BB0 p"BB }	BC A *A1@B@7@6B@7@:
BAABAA$BA'A*.BBBBBB
BB-B,BB-B0
BB>B=BB>CABDD
BDc                 |   |!t        | d      st        j                  d       |t        | d      st        j                  |      }nMt        j                  t        ||      D cg c]"  \  }}|t        | j                  |            z   $ c}}      }|d| j                  j                  j                   D cg c].  }| j                  j                  j                  ||   ||         0 }}| j                  t        u rt        j                   }d}	nt        j"                  }d}	|D 
cg c]P  }
| j$                  j'                   ||
      |	| j(                  j*                  | j,                  | j.                        R }}
| j                  || j0                         t        j2                  | j                  j                  j4                  |      }| j                  j6                  dk7  rB|| j                  j6                  z  }|d| j                  j6                  z
  | j0                  z  z  }|S c c}}w c c}w c c}
w )a  return an updated mean based on the input arguments,

        namely, the solutions `X` and the ranking implied by `F` and `G`.
        `G` is only used if the constraints handling is active. Elements of
        `X` are transformed to the genotype as by default, with repair and
        with accessing the sent solutions archive.

        This method is meant to give a headsup _before_ to call `tell` of
        what the updated mean will be and can be useful, for example, for
        constraints surrogates.
    Naugmented_lagrangianzget_new_mean: was called with constraints values G,
 however `self` has no attribute `augmented_lagrangian`
 to process them. G is hence ignored.TF)r   r   r   r  r   )ro  rG  r   r   r@  r]  r  r  r   rX  r  r  r  rN   rY  r5   r  r	   rE  rI   r   rP  r  r  r   r  r  r  )rA   rF  FGr  r9  gr   aar   r   r   r   s                r-   get_new_meanz!CMAEvolutionStrategy.get_new_mean  s    =/E!FMM D E 9GD*@A**Q-C**,/1I7,5&1a  #d&?&?&B"CC,57 8C -477??--.0. **2266qtQqTB. 	
 0 !!U*BDBD 
 1 ww||BqE!%(,(=(=(E(E#'#7#7$($7$7	  9
  	  	sDII.vvdggoo66<77==ADGGMM!DQ&$))33D;7
0s   &'H.
:3H4*AH9c                      y)zRdo nothing by default, otherwise assign to `_record_rankings_` after instantiationNr+   )rA   valsrl  s      r-   r  z%CMAEvolutionStrategy._record_rankings   s    r,   c                     t        |      }t        j                  |t        | j                  j                        z         }t        j                  |t        |      z         }|dd |dd g| _        | j                  S )zcompute ranks of `vals` in `function_values` and

        in `self.fit.fit` and store the results in `_recorded_rankings`.
        The ranking differences between two solutions appear to be similar
        in the current and last iteration.
        Nr"   )r  r   ranksr  _recorded_rankings)rA   r  rl  r0r1s        r-   _record_rankings_z&CMAEvolutionStrategy._record_rankings_"  sj     Dz[[TXX\\ 223[[_ 556#%bq62bq6"2&&&r,   c                 @   |D ]  }|t        |      | j                  k7  rt        dd| j                  z  z         t        j                  |t
              }|r| j                  j                  |       r| j                  j                  || j                  z
          y)a  inject list of one or several genotypic solution(s).

        This is the preferable way to pass outside proposal solutions
        into `CMAEvolutionStrategy`. Passing (bad) solutions directly
        via `tell` is likely to fail when ``CMA_active is True`` as by
        default.

        Unless ``force is True``, the `solutions` are used as direction
        relative to the distribution mean to compute a new candidate
        solution returned in method `ask_geno` which in turn is used in
        method `ask`. Even when ``force is True``, the update in `tell`
        takes later care of possibly trimming the update vector.

        `inject` is to be called before `ask` or after `tell` and can be
        called repeatedly.

        >>> import cma
        >>> es = cma.CMAEvolutionStrategy(4 * [1], 2)  #doctest: +ELLIPSIS
        (4_w,...
        >>> while not es.stop():
        ...     es.inject([4 * [0.0]])
        ...     X = es.ask()
        ...     if es.countiter == 0:
        ...         assert X[0][0] == X[0][1]  # injected sol. is on the diagonal
        ...     es.tell(X, [cma.ff.sphere(x) for x in X])

        Details: injected solutions are not used in the "active" update which
        would decrease variance in the covariance matrix in this direction.
        Nz%method `inject` needs a list or arrayz" each el with dimension (`len`) %dr   )
r   r   r  r   r  r  ry  r  rz  r   )rA   rk  forcerb  s       r-   injectzCMAEvolutionStrategy.inject/  s    < "H8}& !H;dffD"F G Gzz(%8H,,33H=--44X		5IJ "r,   c                 |   g }t        |      D ]U  \  }}	 | j                  j                  |      }t        | j                  t
              r	|d   dkD  sE|j                  |       W t        | j                  j                               D ]  \  }}|d   | j                  dz
  k  st        | d      r| j                  j                  rHt        | j                  t
              r|d   dkD  r&t        j                  dt!        |      z  t"               | j                  j                  |        |S # t        $ r Y ,w xY w)zreturn indices of `pop` which are in ``self._injected_solutions_archive`` and

        were "externally" injected (non-TPA).

        Remove old entries from ``self._injected_solutions_archive`` and warn in case.
        r  r   rF   r"   integer_mutationsa  orphanated injected solution %s
                            This could be a bug in the calling order/logics or due to
                            a too small popsize used in `ask()` or when only using
                            `ask(1)` repeatedly. Please check carefully.
                            In case this is desired, the warning can be surpressed with
                            ``warnings.simplefilter("ignore", cma.evolution_strategy.InjectionWarning)``
                            )r  r  r   r   r   r   r  r  r  r  r   ro  r  is_nonerG  r   r   r%   )rA   r   indicesr   r   r  r{   s          r-   r  z6CMAEvolutionStrategy._clean_injected_solutions_archiveY  s'    cNDAq&4488;
 "$"2"24DE7VWNN1% # 99??ABDAq~ 22&9:--55&t'7'79IJ W:>  '  #&a&') +;< 0044Q7# C$ /  s   D..	D;:D;c                    |j                         D ]  \  }}|| j                  v rV| j                  d   dkD  r4dt               |   vr%t        j                  dj                  ||             || j                  |<   jt        j                  dj                  ||              | j                  j                  | j                  | j                  d          | j                         j                          | S )a  clear termination and set any `CMAOptions` passed via

        keyword arguments or like ``**opts_dict``. The validity of the option
        names is checked, the validity of the values is not checked.

        Some resettings will not be effective. For those with a ``'#v'``
        flag in their description, the effectiveness is guarantied. See
        `CMAOptions`.

        Return `self`, the new options are in ``self.opts``.
        r   r   z#vzO{0} is not a versatile option, resetting to {1} may not have the desired effectznoption {0} is not recognized (hence value {1} is ignored)
  Check out `cma.CMAOptions` to see the valid names.r  )r  )
r  r   r   rG  r   r   r   r  rl   clear)rA   r4   r{   r|   s       r-   reset_optionsz"CMAEvolutionStrategy.reset_options  s     LLNDAqDII~99Y'!+JLO0KMM #EEKVAq\S 		! U%va|- # 	DIItyy':;		r,   c                     | j                   | j                  j                  z  | j                  j                  t        j                  | j                  j                        z  z  S )zreturn array of coordinate-wise standard deviations (phenotypic).

        Takes into account geno-phenotype transformation, step-size,
        diagonal decoding, and the covariance matrix. Only the latter three
        apply to `self.mean`.
        )	r:  rE  scalesrf  r  r   r\  rj  rv  r   s    r-   rk   zCMAEvolutionStrategy.stds  sI     dggnn,''"''$''2C2C*DDF 	Gr,   c                     | j                   | j                  j                  t        j                  | j
                  j                        z  z  S )a  return array of coordinate-wise standard deviations (genotypic).

        Takes into account step-size, diagonal decoding, and the covariance
        matrix but not the geno-phenotype transformation. Only the former
        three apply to `self.mean`.
        )r:  rf  r  r   r\  rj  rv  r   s    r-   
_stds_genozCMAEvolutionStrategy._stds_geno  s5     zzT^^33bggdgg>O>O6PPQQr,   c                     | j                   S )a-  return a `CMAEvolutionStrategyResult2` class instance.

        :See: `cma.evolution_strategy.CMAEvolutionStrategyResult2`
            or try ``help(...result)`` on the ``result`` property
            of an `CMAEvolutionStrategy` instance or an
            `CMAEvolutionStrategyResult2` instance.
    )_result2r   s    r-   resultzCMAEvolutionStrategy.result  s     }}r,   c                    | j                   j                         \  }}}t        |||| j                  | j                  | j                  | j                  dd | j                  j                        | j                  | j                               S )a8  return a `CMAEvolutionStrategyResult` `namedtuple`.

        :See: `cma.evolution_strategy.CMAEvolutionStrategyResult`
            or try ``help(...result)`` on the ``result`` property
            of an `CMAEvolutionStrategy` instance or on the
            `CMAEvolutionStrategyResult` instance itself.

        Nr   )r   rN   rd   r   r   r   r   r   r   rk   rl   )rA   r   r9  evalss       r-   _result0zCMAEvolutionStrategy._result0  st     iimmo1e)OONNdiil8M8M8T8TUIIIIK	
 		
r,   c                 X     fd} j                   j                         \  }}} |||d|d      }t        |||| j                   j                   j
                  j                   j                  dd  j                  j                         j                   j                         	      S )a;  return a `CMAEvolutionStrategyResult2` class instance.

        :See: `cma.evolution_strategy.CMAEvolutionStrategyResult2`
            or try ``help(..._result2)`` on the ``result2`` property
            of an `CMAEvolutionStrategy` instance or on the
            `CMAEvolutionStrategyResult2` instance itself.
    c                     t        d      r.t        d      }dD cg c]  }t        ||d       c}\  } }}}d}t               t        j                  fdD              S c c}w )z~assumes that `.best_feasible` is a BestFeasibleSolution.

            Otherwise we get more `None` value entries.
            ru   )r   r9  r  countNc              3   4   K   | ]  }|d v r	||   f  yw))r   r9  r  r  feasible_iterationsNr+   )rq   r{   ds     r-   rt   zGCMAEvolutionStrategy._result2.<locals>.get_best_feas.<locals>.<genexpr>  s)      %U1 $SS '(1Ys   )ro  getattrrw   r   
DictClass2)	r   r9  r  r  r  r   fieldr  rA   s	          @r-   get_best_feasz4CMAEvolutionStrategy._result2.<locals>.get_best_feas  s    
 t_-t_5)A0C)A 18eT0J)A0C,1a,A## %U %U V V	0Cs   A%Nr   )r   rN   rn   r   r   rE  rH   r   r   r   rk   rl   )rA   r  r   r9  r  	best_feass   `     r-   r  zCMAEvolutionStrategy._result2  s    	V iimmo1e!!QeT:	*OONNGGMM$))A,D4I4I4P4PMQIIIIK
 	
r,   c                 z   || j                   j                  }t        dj                  | j	                         |rdj                  |      nd|dkD  rdj                  ||dkD  rdnd      nd             t        d	| j                   j
                  j                  || j                  | j                   j                  fz         | j                  d
k  rt        ddj                  t        | j                  | j                  | j                  j                              j                               j!                  dd      j!                  dd      z          t        ddj                  t        | j"                        j                               j!                  dd      j!                  dd      z          | j$                  S t        dt        | j                  | j                  | j                  j                        dd       dd z         t        dt        | j"                  dd       dd z         | j$                  S )zEpretty print result.

        Returns `result` of ``self``.

        Nztermination on {0}{1}{2}z ({0})r'  r   z after {0} restart{1}r   r  z6final/bestever f-value = %e %e after %d/%d evaluationsro  zincumbent solution: r   r   r   z[,[zstd deviations: zincumbent solution: %s ...]r   r   zstd deviations: %s ...])r   r9  r  r   rl   lastr   r  r   r   r   r   r   r   r   splitreplacerk   r  )rA   number_of_restartstime_str	fbestevers       r-   result_prettyz"CMAEvolutionStrategy.result_pretty  s    		I 	(//		/7(//(+R *A- *00*3E3ICrS35	7 	8 	FIINNi$))//JK K 	L66A:(388C8I8I$))aeavava}a}8I8~4  5F  5F  5H  ,I,3GC,>wwtS?QR S$sxxDII0D0D0F'G,3GC,>wwtS?QR S
 {{ /3t7H7H`d`u`u`|`|7H7}  A  @A  8B  4C  DG  EG  4H  I  J+s499Ra=/A#2/FGH{{r,   c                    | j                   dkD  r.t        j                  dj                  | j                                t	        | d      r.t        j                  dj                  | j
                               t        j                  | j                        | _        t        t        | j
                  _
        | j                  d   dk  rd| j
                  _
        t        j                         | _        d| _        d| _        t"        rug | _        t        j&                  t        j(                        t        j&                  t        j*                        t        j&                  t        j,                        g| _        yy)	z<assign `augmented_lagrangian` and `best_feasible` attributesr   z<Late initialization of constraints handling at iteration {0}r  z&overwriting augmented_lagrangian = {0}Nr   r   F)r   rG  r   r   ro  r  _constraints_handlerAugmentedLagrangianr   !tell_augmented_lagrangian_loggingloggingr   r  BestFeasibleSolutionru   _last_feasible_f_first_feasible_ftell_constraints_archives_con_archivesConstrainedSolutionsArchive
_g_pos_max
_g_pos_sum_g_pos_squared_sumr   s    r-   _tear_up_constraints_handlingz2CMAEvolutionStrategy._tear_up_constraints_handling  s   >>AMMN') 4/0MMB#VD$=$=>@$8$L$LTVV$T!,80QD%%-99Y"$05D%%-446 $!%$!#D(DDEYEdEde(DDEYEdEde(DDEYElElm"D %r,   c           
      &   |S t        | d      s| j                          | j                  j                  |       |D cg c]  }| j                  |       }}t	        |      D cg c]  \  }}|t        |      z    }}}t        j                  |      }	| j                  j                  |	   ||	          |D cg c]  }| j                  |       }}|D cg c]  }t        |       }
}t              t        |
      k(  s	J |
f       t	        |
      D cg c]
  \  }}||z    }}}t        |      D cg c]  \  }}t        d |D              r| }}}|rnt        fd|D              | _        | j                  | j                  | _        |D ]3  }| j                  j                  |   ||   ||   ||   d||   i       5 t         rd}n| j                  Gt"        t        j$                  t        j&                  |
            z   t%        dt%              f      z   }nE| j                  t        |      z
  }|s+|t        j                  t        j&                  |
            z  }t(        rt        | d      ru| j*                  rit	        |||      D ]X  \  }}}}t-        j.                  | j                  j0                  ||||      }| j*                  D ]  }|j                  |||        Z t         s| j2                  t4        k  r8| j                  ,|D cg c]   }t7        t        d |D              |z         " c}S |D cg c]  }t7        ||z          c}S c c}w c c}}w c c}w c c}w c c}}w c c}}w c c}w c c}w )	a  return "fake" `function_values` when `constraints_values` are given

        and update the augmented Lagrangian coefficients before. `solutions`
        are passed only to record the best feasible solution.

        The returned fitness values are the augmented Lagrangians with an
        offset such that the value is never below the function value of the
        last seen feasible solution (best per iteration). If no feasible
        solution was seen yet, add `initial_infeasibility_foffset` and the
        current maximal penalty as offsets.

        Use also module settings `tell_find_feasible_first` and
        `tell_find_feasible_only`.
    r  c              3   &   K   | ]	  }|d k    yw)r   Nr+   )rq   vis     r-   rt   z=CMAEvolutionStrategy._constraints_handling.<locals>.<genexpr>T  s     "7Qr27Qs   c              3   (   K   | ]	  }|     y wrW   r+   )rq   r   rl  s     r-   rt   z=CMAEvolutionStrategy._constraints_handling.<locals>.<genexpr>W  s     'UDTq(:DTs   al_penaltiesinfor   r  c              3   2   K   | ]  }|d kD  s	|dz    ywr   r"   Nr+   rq   gis     r-   rt   z=CMAEvolutionStrategy._constraints_handling.<locals>.<genexpr>~  s     :a26b!ea   

)ro  r  r  set_coefficientsr]  r  r   argminr  r   r  r  rs  r	  r
  ru   tell_find_feasible_only"tell_initial_infeasibility_foffsetr^  r  r  r  r  constraints_info_dictcount_callsr   tell_find_feasible_firstr  )rA   rl  rh  rk  r  r  r9  r   	al_valuesiminal_penalty_sumsr   r|   feasible_indicesf_offsetr   fvalgvalsalvalsr  r)  ru  s    `                    r-   r  z*CMAEvolutionStrategy._constraints_handling/  s    %""t34..0!!22/	1 ?QQ>P11!4>PQ.1/<.PQ.PFQQQZ.P	Qyy#!!(()>);D)A	C>PQ>P11!4>PQ+78<a3q6<8?#s?';;_o=__;),_o)NO)Nv1QU)N	O -66H,I 9,I&1a""7Q"77 ,I 9$''UDT'U$UD!%%-)-)>)>&%""))'*,>q,A<PQ?!!NLO+L * N & #H##+9BFF/=1 1363;O7P3QRH ,,s9~=H#BFF266/#:;;$)GDL^L^*-!?4F+V&4+AA 55AA1dESY[++AHHT5$/ ,	+V #t~~8P'P+/+A+A+I 01/ #:a::XEF/1 11:;#cHn%;;q RQ R8O9V1;s0   M(+M-M3M8"M=N$%N	Nc                     ddl }	 |j                  |       }|S #  d| j                  c| _        }	 |j                  |       }n#   xY w	 || _        Y |S # || _        w xY wxY w)a  return ``pickle.dumps(self)``,

        if necessary remove unpickleable (and also unnecessary) local
        function reference beforehand.

        The resulting `bytes` string-object can be saved to a file like::

            import cma
            es = cma.CMAEvolutionStrategy(3 * [1], 1)
            es.optimize(cma.ff.elli, iterations=22)
            filename = 'es-pickle-test'
            open(filename, 'wb').write(es.pickle_dumps())

        and recovered like::

            import pickle
            es = pickle.load(open(filename, 'rb'))

        or::

            es = pickle.loads(open(filename, 'rb').read())
            es.optimize(cma.ff.elli, iterations=22)  # continue optimizing

        r   N)pickledumpsobjective_function)rA   r.  r  funs       r-   pickle_dumpsz!CMAEvolutionStrategy.pickle_dumps  sv    2 		.T"A 	.+/1H1H(D#S.LL&E  +.' +.'s2    AAAAA	A	AAc                    t        j                  |      }t        j                  | j                        }ddk  r| j                  dz  d| j                  z  | j                  dz   z  z   }| j	                  ||z
        |z  }|dkD  r |r||z
  |z  |z   }|S ||z  }||z  }||z  }|S ddk  rDt        j
                  t        j                  ||z  dz  | j                  z  dz
  dz        dz        S |S )a[  make sure that solutions fit to the sample distribution.

        This interface is versatile and likely to change.

        We currently assume that this is idempotent.

        The Mahalanobis distance ``x - self.mean`` is clipping at
        ``N**0.5 + 2 * N / (N + 2)``, but the specific repair
        mechanism may change in future.
        r   rE   rG   r"   r  )r   r  r   r   r  r  tanh)rA   r   r  r  upper_lengthr  s         r-   r  z$CMAEvolutionStrategy.repair_genotype  s     JJqMzz$))$q5663;TVVtvvz)BBL''D1L@CQw"TS(4/A  IAHAIA  avvbggs(:Q'>'G!'Kq&PQTUUVVr,   c                     | j                   s#t        j                  ddd| j                         yt	        j
                  | j                  j                  d|dz  g      \  }}||k(  r| xj                  |z  c_        yy)a  increase `sigma` by `sigma_fac` in case of a plateau.

        A plateau is assumed to be present if the best sample and
        ``popsize * sample_fraction``-th best sample have the same
        fitness.

        Example:

        >>> import cma
        >>> def f(X):
        ...     return (len(X) - 1) * [1] + [2]
        >>> es = cma.CMAEvolutionStrategy(4 * [0], 5, {'verbose':-9, 'tolflatfitness':1e4})
        >>> while not es.stop():
        ...     X = es.ask()
        ...     es.tell(X, f(X))
        ...     es.manage_plateaus()
        >>> if es.sigma < 1.5**es.countiter: print((es.sigma, 1.5**es.countiter, es.stop()))

        zYInbetween `ask` and `tell` plateaus cannot be managed, because `sigma` should not change.manage_plateausr   Nr   r*  )r  r   r   r   r   prctiler  r:  )rA   r  sample_fractionrz  fms        r-   r7  z$CMAEvolutionStrategy.manage_plateaus  sr    (    !>,.D $0 DHHLL1o.C*DEB8JJ)#J r,   c                    	 | j                   j                  S # t        $ r1 t        | j                        t        | j                        z  dz  cY S t        $ r1 t        | j                        t        | j                        z  dz  cY S w xY w)zcondition number of the statistical-model sampler.

        Details: neither encoding/decoding from `sigma_vec`-scaling nor
        `gp`-transformation are taken into account for this computation.
        r"   )rj  condition_numberr  r^  rx  rs  r  r   s    r-   r<  z%CMAEvolutionStrategy.condition_number  sn    	277+++ 	2K#dff+-11# 	2K#dff+-11	2s    7B
6B
	B
c                 z   |rWt        j                  |      rBt        j                  | j                        t        j                  | j                        z  |k  ryt        | d      rTt        | j                  t        j                        r.t        j                  | j                        t        j                  | j                        z  }| j                  j                  }| j                  j                         }| xj                  |z  c_        | xj                  |z  c_        | j                  | j                         t        j                   d|t        j                  | j                        t        j                  | j                        z  || j                  j                  fz  | j"                         yyy)zpass scaling from `C` to `sigma_vec`.

        As a result, `C` is a correlation matrix, i.e., all diagonal
        entries of `C` are `1`.
        Nrj  ze
condition in coordinate system exceeded %.1e, rescaled to %.1e, 
condition changed from %.1e to %.1er   )r   rg  r^  rw  rs  ro  r   rj  r   rp  r<  to_correlation_matrixrf  r`  rk  r   r!  r   )rA   	conditionold_coordinate_conditionold_conditionfactorss        r-   r  z:CMAEvolutionStrategy.alleviate_conditioning_in_coordinates  s.    Y!766$''?RVVDGG_4y@4:dggw7O7O#P')vvdgg'H$ GG44Mgg335GNNg%NGGwG  ) !H 0266$''?1R$dgg&>&>@!@
 #nn. $Qr,   c                 V    t        j                  | j                  j                  |      S rW   )r   r  rE  
_tf_matrixr*  s     r-   _tfpzCMAEvolutionStrategy._tfp$  s    vvdgg((!,,r,   c                 V    t        j                  | j                  j                  |      S rW   )r   r  rE  _tf_matrix_invr*  s     r-   _tfgzCMAEvolutionStrategy._tfg&  s    vvdgg,,a00r,   c                    | j                   j                  r|r| j                  |k  ryt        | j                  d         r%t        j                  ddd| j                  d       y	 | j                  }| j                  j                         }| j                  j                  d	      }t        j                  || j                        | _        t        j                  || j                  | j                  z        | _        | j!                  | j                         | j!                  | j                         | j                  |j$                  z  j$                  | j                   _        || j                  z  | j                   _        t+        j,                  | j                  j.                  dz        | _        | j0                  | j                   _        | j4                  | j                   _        d| j                   _        | j8                  | j:                  usJ | j                   j7                  | j8                        | _        t=        | j>                        D ]-  \  }}| j                   j7                  |      | j>                  |<   / t=        | j@                        D ]-  \  }}| j                   j7                  |      | j@                  |<   / | j                   j7                  | j:                        | _        t        j                  d|| j                  fz  dd| j                         y# t"        $ r t        j                  d
d       Y yw xY w)a9  pass conditioning of `C` to linear transformation in `self.gp`.

        Argument `condition` defines the limit condition number above
        which the action is taken.

        >>> import cma
        >>> for dd in [0, 1]:
        ...     es = cma.CMA(2 * [1], 0.1, {'CMA_diagonal_decoding' : dd, 'verbose':-9})
        ...     es = es.optimize(cma.ff.elli, iterations=4)
        ...     es.alleviate_conditioning(1.01)  # check that alleviation_conditioning "works"
        ...     assert all(es.sigma_vec.scaling == [1, 1]), es.sigma_vec.scaling
        ...     assert es.sm.condition_number <= 1.01, es.sm.C

        Details: the action applies only if `self.gp.isidentity`. Then,
        the covariance matrix `C` is set (back) to identity and a
        respective linear transformation is "added" to `self.gp`.
        Nr   z<geno-pheno transformation not implemented with int-variablesr  r   r   r  T)resetzNot Implemented)rp  r   Fz
        geno-pheno transformation introduced based on the
        current covariance matrix with condition %.1e -> %.1e,
        injected solutions become "invalid" in this iteration)!rE  rF  r<  r   r   r   r   r   rj   to_linear_transformation_inverseto_linear_transformationr   r  r`  ra  rf  rk  r  r  rD  rG  r   re  r  rE  rO  rH  rN  r   rO  r  ry  rz  )rA   r?  old_condition_numbertf_invtfr   r   s          r-   r  z+CMAEvolutionStrategy.alleviate_conditioning)  s   & ww!!d6K6Ki6Wtyy,-.J(*@, 
	#'#8#8 WW==?F111=BffVTWW-DGvvfdhh&?@DH  )
 	TWW% #nnrtt366!'$..!8(99$..:P:PRS:ST  99))"yy--- GGOODII.	d::;DAq.2ggooa.@D((+ <d;;<DAq/3wwq/AD))!, = 6 	 A 01F1FG	H
 %&<NN	I # 	 1,DF	s   'B4L( ( M
Mc                 >   || j                   }t        |t        j                        rFt	        d      | _        |j                  dz  | _        t	        d      | _        | j                  | _	        yt        |t        j                  t        j                  f      r|j                  | _	        y| j                   j                  | _        	 | j                   j
                  | _        | j                   j                  | _        | j                  %t!        j"                  | j                        | _	        yy# t        $ rd | j                  B | j                  d   | j                        \  | _        | _        | xj                  dz  c_        nddk  rd| _        d| _        Y w xY w)zhelper function for a smooth transition to sampling classes.

        By now all tests run through without this method in effect.
        Gradient injection and noeffectaxis however rely on the
        non-documented attributes B and D in the sampler. Nr   rG   r  r  rE   )rj  r   r   ri  r	   r  rv  rx  r  rw  _rgsGaussVDSamplerGaussVkDSamplercovariance_matrixr  r   r   diag)rA   sm_s     r-   rk  z$CMAEvolutionStrategy._updateBDfromSMw  s1    ;''Cc78891XDF]]C'DF1XDFffDGd1143G3GHImmDGWW..DF	" vv!''$&&/ " " "66%%ATYY/@%A$&&%INDFDFFFsNF!V!DF!DF"s   6D/ /A*FFc                 H   | j                   dkD  rt        j                  d       t        |      t        |      k7  r;t	        dt        t        |            z   dz   t        t        |            z   dz         | j                  j                  }t        |      |z  dk7  r/t	        dt        t        |            z   dz   t        |      z         t        t        |      |z        D ]<  }| j                          | j                  |||z  |dz   |z   |||z  |dz   |z          > y)	a  Resume a run using the solution history.

        CAVEAT: this hasn't been thoroughly tested or in intensive use.

        Given all "previous" candidate solutions and their respective
        function values, the state of a `CMAEvolutionStrategy` object
        can be reconstructed from this history. This is the purpose of
        function `feed_for_resume`.

        Arguments
        ---------
        `X`:
          (all) solution points in chronological order, phenotypic
          representation. The number of points must be a multiple
          of popsize.
        `function_values`:
          respective objective function values

        Details
        -------
        `feed_for_resume` can be called repeatedly with only parts of
        the history. The part must have the length of a multiple
        of the population size.
        `feed_for_resume` feeds the history in popsize-chunks into `tell`.
        The state of the random number generator might not be
        reconstructed, but this would be only relevant for the future.

        Example
        -------
        ::

            import cma

            # prepare
            (x0, sigma0) = ... # initial values from previous trial
            X = ... # list of generated solutions from a previous trial
            f = ... # respective list of f-values

            # resume
            es = cma.CMAEvolutionStrategy(x0, sigma0)
            es.feed_for_resume(X, f)

            # continue with func as objective function
            while not es.stop():
                X = es.ask()
                es.tell(X, [func(x) for x in X])


        Credits to Dirk Bueche and Fabrice Marchal for the feeding idea.

        :See also: class `CMAEvolutionStrategy` for a simple dump/load
            to resume.

        r   z8feed should generally be used with a new object instanceznumber of solutions z and number function values z must not differz( must be a multiple of popsize (lambda) r   N)r   r   r   r   r  r   r   r   r   r  rm  )rA   rF  rl  r   r   s        r-   feed_for_resumez$CMAEvolutionStrategy.feed_for_resume  s"   n >>A Z[q6S))3c#a&kA./C()*,>? @ @ ''//FW"3c#a&kA>?L! " " s1v()AHHJ IIaGQUg$56%a'k1q5G2CDF *r,   c                 v   	 | j                   j                          	 | j                   j                  | j                   j
                  k(  r| j                  | j                          yy# t        $ r | j                   j                  d       Y qw xY w# t        $ r | j                  | j                          Y yw xY w)zcall sm.update_now like sm.sample would do.

        This avoids a bias when using
        `_random_rescaling_factor_to_mahalanobis_size` which was visible
        with TPA line samples.
        r   N)rj  r  r  r  last_update
count_tellrk  r   s    r-   _try_update_sm_nowz'CMAEvolutionStrategy._try_update_sm_now  s    	GG 	*ww""dgg&8&88$$TWW- 9  	GGNN1	
  	*  )	*s#   A' AB '$BB$B87B8c                     | j                          t        | j                  j                  t	        j
                  |      | j                  j                  z        | j                  z        S )aQ  return Mahalanobis norm based on the current sample
        distribution.

        The norm is based on Covariance matrix ``C`` times ``sigma**2``,
        and includes ``sigma_vec``. The expected Mahalanobis distance to
        the sample mean is about ``sqrt(dimension)``.

        Argument
        --------
        `dx`, a *genotype* difference to the distribution mean. As `dx` is
        interpreted as a difference to the mean, the return value does not
        depend on the current mean.

        Example
        -------
        >>> import cma, numpy
        >>> es = cma.CMAEvolutionStrategy(numpy.ones(10), 1)  #doctest: +ELLIPSIS
        (5_w,...
        >>> xx = numpy.random.randn(2, 10)
        >>> d = es.mahalanobis_norm(es.gp.geno(xx[0]-xx[1]))

        `d` is the distance "in" the true sample distribution,
        sampled points have a typical distance of ``sqrt(2*es.N)``,
        where ``es.N`` is the dimension, and an expected distance of
        close to ``sqrt(N)`` to the sample mean. In the example,
        `d` is the Euclidean distance, because C = I and sigma = 1.

        )	r\  r  rj  r  r   r  rf  r  r:  )rA   r0  s     r-   r  z%CMAEvolutionStrategy.mahalanobis_norm  sH    : 	!TWW\\"**R.4>>3I3I"IJTZZWXXr,   c                    | j                   | j                  k7  r| j                  j                  | j                  | j
                  z
  | j                  j                  z        | _        | xj                  | j                  j                  j                  dz  | j                  z  | j                  j                  z  z  c_        | j                  | _         | j                  S )a  normalized last mean shift, under random selection N(0,I)

        distributed.

        Caveat: while it is finite and close to sqrt(n) under random
        selection, the length of the normalized mean shift under
        *systematic* selection (e.g. on a linear function) tends to
        infinity for mueff -> infty. Hence it must be used with great
        care for large mueff.
        rG   )r\  r   rj  r  r   rO  rf  r  _isotropic_mean_shiftr   rX  r  r:  r  r   s    r-   r  z)CMAEvolutionStrategy.isotropic_mean_shift  s     //4>>A)-)B)BYY.$..2H2HH*JD&&&477??+@+@#+E

+R-1WW]],; <&37>>D0 )))r,   c                 V    t        d       t        j                  j                          y)z#print annotation line for `disp` ()zGIterat #Fevals   function value  axis ratio  sigma  min&max std  t[m:s]N)r  sysstdoutflushr   s    r-   disp_annotationz$CMAEvolutionStrategy.disp_annotation0  s    WX

r,   c                 2    | j                   d   } fd}|r j                  dz
  d|z  z  dk  r |       s j                          t         d      sd _        d _         j                  dkD  r j                         sR j                  dk  sC j                  |z  dk  s1 j                  j                   j                  z
   j
                  kD  r? j                  j                   _         xj
                  dz  c_         j                   d   rJ j                  j                  }t        t        |d	z              d
z   d|d	z  z  j                  dd      z   }nd}t        dj                  t         j                        j                  d      t         j                        j                  d      dt!         j"                  j"                        z  d j                   d   r j                   j                   d   kD  r5 j$                  j'                          j$                  j!                         z  n0t'         j(                  dz        t!         j(                  dz        z  z  d j*                  z  d j*                  t!         j(                   j,                  dz  z        z  z  d j*                  t'         j(                   j,                  dz  z        z  z  |f       |       rdnd       t.        j0                  j3                           S )zprint current state variables in a single-line.

        Prints only if ``iteration_counter % modulo == 0``.
        Overwrites the line after iteration `overwrite`.

        :See also: `disp_annotation`.
        r   c                      &j                   j                  dt        d            } n} j                          xr | dkD  xr j                  | kD  S )Nverb_disp_overwriter   r   )r   rN   r  rl   r   )iters	overwriterA   s    r-   do_overwritez/CMAEvolutionStrategy.disp.<locals>.do_overwrite@  sL     		&;U5\J!yy{?KuqyKT^^e5KKr,   r   rD   times_displayedr   r   	verb_time<   :z%2.1f0r'  r   r   r#   z%.15ez%4.1er   z%6.2ez%6.0erG   
)end)r   r   rd  ro  time_last_displayedrk  rl   r  elapsedr   rB  rjustr  r   r   r   rs  r  rx  r^  rf  r:  rw  ra  rb  rc  )rA   r$  ri  rj  tocstimes   ` `   r-   dispzCMAEvolutionStrategy.disp5  s    >YY{+F	L "rF{3a7$$&4!23+,('($~~!tyy{dnnq6H!%&!81!<!%!3!3d6N6N!NQUQeQe!e+/::+=+=($$)$99[)**,,CC2I/#5C"H9M8T8TUVX[8\\EEchhT^^ 4 : :1 = $T__ 5 ; ;A > '3txx||+< = '26))N2Kt~~`d`i`ijx`yOy ,066::<$&&**,+F03DNN14D0EDNN[\L\H]0]!_ !($** 4 '4::DNNTWWVY\<Y8Z+Z [ '4::DNNTWWVY\<Y8Z+Z [ %	 ' 	( #/.$d
< 

  "r,   c                 z   t        | j                  d      r| j                  j                  | | j                  _        	  | j                  j                  |i | | S # t        $ r t        j                  d       Y | S  t        j                  dj                  t        j                               dd       Y | S xY w)zplot current state variables using `matplotlib`.

        This calls `self.logger.plot`, see `cma.CMADataLogger.plot` to see all
        valid keyword arguments.
        r  z*plotting failed, no logger attribute foundzplotting failed with: {0}plotr   )
ro  r  r  rz  r  r   r   r   ra  exc_inforX   s      r-   rz  zCMAEvolutionStrategy.ploth  s     t{{D)T[[^^-C!DKKN	;DKKd-f-   	N LM 	; ; B B3<<> R!#9;s   A B:>9B:)Tr+   FN)NN)FT)NNr   Nr+   )NNr   FrW   TN)NFN)NNF)r   NN)g      ?rG   )g    חA)g   mB)9r'   r(   r)   r*   r   r   rl   r?   r4  ru  r  r  r  r  r+  r  r1  r   r  r4  rM  rQ  r`  r   r.  rm  rj  r  r  r  r  r  r  rk   r  r  r  r  r  r  r  r2  r  r7  r<  r  rE  rH  r  rk  rX  r\  r  r  rd  rx  rz  r+   r,   r-   r   r     s   n^	   HM0dV>p5n'HR#J< 67]D +/7<EN[*^ ')TYZ!"		RWl\&P0 ;?EI"H[$N =A,0N%b "&ZKx LLEM0d]'(KT$L4 G G R R   
 
, #
 #
J <@ $!F2jV#J@$< 2 2.2-1L\*BHF\*"Y@ * *0
2fr,   r   c                   F    e Zd ZdZddZd	dZd Zed        Zed        Z	y)
r  af  Provide a termination signal depending on how much a vector has changed,

    typically applied to the distribution mean over several iterations.

    The `stop` property is the boolean termination signal, the `update`
    method needs to be called in each iteration with the (changing) vector.

    ``self.stop is True`` iff
    - ``delta t > threshold`` and
    - ``Delta x < delta * max(1, sqrt(delta t / threshold))`` for at least delta t iterations.

    The (iteration) threshold is computed in property `time_threshold`
    based on the iteration count and three parameters as ``p1 + p2 * count**p3``.

    Nc                     t               j                  d      }|d   | _        |d   | _        |d   | _        d| _        d| _        d| _        || _        y)zR`x` is the initial vector (optional), default settings are taken from `CMAOptions`r  r   r   r"   N)	r   r2  deltatime_delta_offsettime_delta_fractime_delta_expor  count_xr   )rA   r   r  s      r-   r?   z_StopTolXStagnation.__init__  sU    |  !12!W
!%a#Aw 
r,   c                     |dv r| S |du r	d| _         | S t        |       t        ||      D ](  \  }}t	        | |      sJ |       |t        | ||       * | S # t        $ r || _         | cY S w xY w)a  `param_values` is a `list` conforming to ``CMAOptions['tolxstagnation']``.

        Do nothing if ``param_values in (None, True)``, set ``delta = -1``
        if ``param_values is False``.

        `None` entries in `param_values` don't change the respective
        parameter and ``[0.12]`` is the same as ``[0.12, None, None, None]``.

        Details: In principle, `'delta'` should be propto sqrt(mu/dimension).
        r[  Fr   )r  iterr  r]  ro  rz   )rA   param_valuesr   rr   rP   s        r-   r  z_StopTolXStagnation.set_params  s     <'K5 DJK, ul3KD%4&,,& dE* 4   	%DJK	s   A A-,A-c                    | xj                   dz  c_         | j                  t        d| j                   | j                  z
  | j                  z  f      dz  z  }|dk  s7| j
                  +t        j                  | j
                  |z
  dz        dz  |kD  r+t        j                  |      | _        | j                   | _        | S )z$caveat: this stores x as a referencer   rG   r   r"   )	r  r  r^  r  time_thresholdr   r   r  r  )rA   r   r  s      r-   r  z_StopTolXStagnation.update  s    

a


S!djj4<<&?4CVCV%V!WXZ]]]19"&&$&&1*q*A3*F*NZZ]DF::DLr,   c                 h    | j                   | j                  | j                  | j                  z  z  z   S rW   )r  r  r  r  r   s    r-   r  z"_StopTolXStagnation.time_threshold  s4    &&$$tzz43G3G'GGH 	Ir,   c                 N    | j                   | j                  z
  | j                  kD  S rW   )r  r  r  r   s    r-   rl   z_StopTolXStagnation.stop  s     zzDLL(4+>+>>>r,   rW   ))r  r  r  r  )
r'   r(   r)   r*   r?   r  r  r   r  rl   r+   r,   r-   r  r  y  s@    	4	 I I ? ?r,   r  c                   B     e Zd ZdZi f fd	ZddZd ZddZd Z xZ	S )	r  a  keep and update a termination condition dictionary.

    The dictionary is "usually" empty and returned by
    `CMAEvolutionStrategy.stop()`. The class methods entirely depend on
    `CMAEvolutionStrategy` class attributes.

    Details
    -------
    This class is not relevant for the end-user and could be a nested
    class, but nested classes cannot be serialized.

    Example
    -------
    >>> import cma
    >>> es = cma.CMAEvolutionStrategy(4 * [1], 1, {'verbose':-9})  #doctest: +ELLIPSIS
    >>> print(es.stop())
    {}
    >>> es.optimize(cma.ff.sphere, verb_disp=0)  #doctest: +ELLIPSIS
    <...
    >>> es.stop()['tolfun'] == 1e-11
    True

    :See: `OOOptimizer.stop()`, `CMAEvolutionStrategy.stop()`

    c                    t        |t              }t        t        |   |ri n|       g | _        d| _        d | _        d | _        	 |j
                  | _        	 |j                  | _        |r| j                  |       y y #  Y +xY w#  Y  xY wr=   )
r   r   r>   r  r?   stoplistr   r   r   _update)rA   r  r  rB   s      r-   r?   z_CMAStopDict.__init__  s    A34lD*2Q?	JJDM	JJDM LLO 		s   A> B >BB	c                 b    |s| S || j                   t        d      | j                  |       | S )zAupdate and return the termination conditions dictionary

        z4termination conditions need an optimizer to act upon)r  r  r  )rA   r  r   s      r-   r  z_CMAStopDict.__call__  s6     K:$''/STTRr,   c                 &   || j                   }|J |j                  dk(  r3| j                  rt        j                  d       | j                          | S ddk  r,|j                  | j                  k(  r	 || j                   k(  r| S 	 |j                  | _        || _         | j                  xs | j                          |j                  }|j                  }|| _	        |d   dk\  r|d   rt        j                  j                  | j                  d         rt        |d   d	      5 }|j                         }ddd       	 t        t!        j"                  j%                                     }t'        |      D ]O  }||j)                         vst+        j,                  d
|d| j                  d   d       |j/                  |       Q |j1                  |       |D ]  }|j3                  |||d        	 | j9                  d|j:                  j<                  |d   k         | j9                  d|j>                  dz
  |d   k\         | j9                  d|j                  d|d   z  k\         |j@                  |jB                  jD                  tG        jH                  |jJ                        z  z  }| j9                  dtM        ||jN                  |jP                  z  |d   z  kD               | j9                  dtS        ||d   k        xr? tS        |j@                  |jB                  jD                  |jT                  z  z  |d   k        | j                  rtW        |      nd       tW        |jX                  jX                        t[        |jX                  jX                        z
  }	tW        |jX                  j\                        t[        |jX                  j\                        z
  }
| j9                  d|	|d   k  xr |
|d   k         | j9                  d|	|d   |jX                  j^                  |jX                  j`                  z
  z  k  | j                  r|	nd       | j9                  dtc        |jX                  j\                        dkD  xr |
|d   k         |d   rtW        d|d   z  dz  dz  tc        |jX                  jd                        dz  f      }ddk  rtg        |j                  |d   |j                  |d d!|jh                  z  z   z  kD  tc        |jX                  jd                        d!kD  tG        jj                  |jX                  jl                  d|       tG        jj                  |jX                  jl                  |d|z         k\  tG        jj                  |jX                  jd                  d|       tG        jj                  |jX                  jd                  |d|z         k\  f       ||j                  k  rto        |      }| j9                  dddk  xrx |d   xrp |j                  |d d!|jh                  z  z   z  kD  xrK |j>                  |j:                  jp                  z
  |jh                  z  |j                  d   dz  kD  xr tc        |jX                  jd                        d!kD  xr d|z  tc        |jX                  jd                        k  xr tG        jj                  |jX                  jl                  d|       tG        jj                  |jX                  jl                  |d|z         k\  xr\ tG        jj                  |jX                  jd                  d|       tG        jj                  |jX                  jd                  |d|z         k\         | j9                  d"|jr                  jt                         tw        |j@                  |jx                  jW                         z        }| j9                  d#|d#   xr ||jN                  |d#   z  kD  | j                  r|nd       	 | j9                  d$|jz                  j|                  |d$   kD  | j                  r|jz                  j|                  nd       ddk  rdz  tc        |jX                  jd                        k  rtG        jj                  |jX                  jl                  d|        tG        jj                  |jX                  jl                  |d|z         z   tG        jj                  |jX                  jd                  d|        tG        jj                  |jX                  jd                  |d|z         z   f}|xj                  |D cg c]  }|dk  rd|z  n|dz    c}z  c_@        ddk  r|j                  |j                  d%|z  z   k(  j                         d   }| j9                  d&tM        |      |D cg c]  }to        |       c}       |d'   d(ur
|j                  |d'   kD  r|j                  dz  dk(  r|j                  |z  }	 | j9                  d)tS        |j                  |j                  d*|j@                  z  |j                  jx                  |   z  |jB                  jD                  z  tc        |j                  j                  j                        dkD  r|j                  j                  dd|f   n|j                  j                  d   z  z   k(               | j9                  d+|d+   xr( |jx                  d,   |d+   d-z  |jx                  d   z  kD  |d+          | j9                  d.tM        |j                        |j                         ddk  stc        |       r9ddk  rl|jX                  jX                  d   |jX                  jX                  to        d/tc        |jX                  jX                        z           k  rd|jX                  _G        n|jX                  xj                  dz  c_G        |jX                  j                  |d0   kD  r| j9                  d0       ddk  rtW        |jX                  jX                        t[        |jX                  jX                        cxk(  r#|j:                  j                  j<                  k(  rJn nGt+        j,                  d1|jX                  jX                  d   |j@                  fz  |j                  2       ddk  r| j9                  d3tc        |jX                  j\                        dkD  xr tW        |jX                  j\                        t[        |jX                  j\                        k(  xr? tW        |jX                  jX                        t[        |jX                  jX                        k(  d4|j@                  z         ddk  r6|d5   d6k(  r.| j9                  d7t        |j                  dz        |d   k         | S #  Y xY w# 1 sw Y   xY w# t4        $ r6 t        j                  ddt7        | j                  d         d       Y _w xY w# t~        $ r |j                  dk  r	 Y w xY wc c}w c c}w # t~        $ r Y w xY w)8z9Test termination criteria and update dictionary

        Nr   z0Cannot get stop value before the first iterationr  rE   r   isignals_filenamerz(        unkown or non-versatile option 'z' found in file z>.
        Check out the #v annotation in ``cma.CMAOptions()``.)r   dimzLSyntaxError when parsing the following expression with `ast.literal_eval`:

z
(contents of file r+  ftarget	maxfevalsr   maxiterr   	tolfacupxtolxtolfun	tolfunrel
tolfunhistro  tolstagnationg      @r"   rD   r   r*  r  r  timeoutg?noeffectcoordr   Tnoeffectaxisg?tolconditioncovr   rG   callbackg      ?tolflatfitnesszflat fitness (f=%f, sigma=%.2e). For small sigma, this could indicate numerical convergence. 
Otherwise, please (re)consider how to compute the fitness more elaborately.r   zflat fitnesszVplease (re)consider how to compute the fitness more elaborately if sigma=%.2e is larger  iA  z||xmean||^2<ftarget)Jr  r   r   rG  r   r?   r   r  r   r   ospathisfileopenreadrv   r;  r<  stripr  versatile_optionsr   r   r   r  r2  SyntaxErrorr   _addstopr   r9  r   r:  rf  r  r   r\  rw  r~  r9  rc  r  r`  r^  r  rs  r  r  r  r   r  r  r   r  r  rB  r  r  rl   r  rx  r  rt  r  r  r   r  rj  r  r8  r   r  r  r  )rA   r  r   r   r9  r  r  rO   sigma_x_sigma_vec_x_sqrtdCcurrent_fitness_rangehistoric_fitness_rangeltmptr  r   s                   r-   r  z_CMAStopDict._update  s    :B~~<<1PQMMOK6||t}},TWW}# %
 '4::<DDww	 	?b T*<%="''..QUQZQZ[mQnBod-.4FFH 57))!'')45
  7C$"8"8"::++/2DII>P4Q-S T c
 # ACIIc1#56  	iggii4	?2	4 	kmma'4+<<	>illcDO&;;	= &(XX1E1EPRPUPU1V%W"k4))bmm3d;6GGH I	J 	f4tF|CD T"((bll&:&:RUU&BCd6lRS9=c45d	T !$BFFJJ#bffjj/ A!$RVV[[!1C4D!Dh+d8n< >,tH~=	? 	k+d;.?266>>TVTZTZTeTeCe.ff/3+D	J 	l"&&++&* B,tL/AA	C   cD11B6:C<PSU<UVWA AvbllT/%:BLL1PQTWZ\ZdZdTdPdKe<e(3.IIbff//34		"&&BSBSTUVWZ[V[B\8]]IIbffoobq12biiPQRSVWRW@X6YY%[ \
 BLL FoA ^$"7 ^BLL1PQTWZ\ZdZdTdPdKe<e ^6"**DrwwG_bcGcc^BFFOO,s2^781us266???S7S^ 		"&&"3"3BQ"78BIIbffFWFWXYZ[^_Z_F`<aa^ 		"&&//"1"56"))BFFOOTUVWZ[V[D\:]]_ 	&(>(>(C(CD"((RTTXXZ'(lD$6 %9"))d<&888??a	6	MM)((**T)_<.2oo"((**4I 6a!ec"&&//22IIbff//344ryyARARSTUVYZUZA[7\\YYrvvr233biiPQRSVWRW@X6YY[Cc Jc1q5"a%a!e";c JJq5 77bgg.H(HHHQQSTUVCMM/3s8c5Jcc!fc5JK ^$D0R\\DDX5X!a'LL1$MM."%bgg3>%'UUWWQZ<024,,2F2F<G7:25577==7IA7MbeeggadmSUSXSXSZSZ[\S]<_ 2_ '_ #`a MM+01 L$$r(T*;%<c%ABDDG%KKTRcMdf MM*c"//&:BOOLq5CI1u66::a=266::c$RVVZZ2H.I#JJ01BFF- FF--2-11D9I4JJ &676c"&&**oRVVZZ&ZBGGLLNN&Z!//!n "$A 9!: FH\\	S
 AvnRVV[[)A- ARVV[[)S-==A!"&&**oRVVZZ@qtvt|t||	~
 6d4jC'MM/RWWaZDO1STM" 54  g?@#diiPbFcBdf ggb  	||q 	 !K 6K & s\   4x %x
?,x )Ay -y9y>2Cz x
x;yyy65y6	zzc                     || j                   k(  r|| _        d | _         y |r?| j                  j                  |       ||n| j                  j                  |d       | |<   y y rW   )r   r   r  r  r   rN   )rA   rO   condru  s       r-   r  z_CMAStopDict._addstop  sX    $//!DK"DOMM  %"!%sD!9 I r,   c                 T    t        |       D ]  }| j                  |        g | _        y)zempty the stopdictN)r  r   r  )rA   r{   s     r-   r  z_CMAStopDict.clear  s"    dAHHQK r,   r[  r}  )
r'   r(   r)   r*   r?   r  r  r  r  rS   rT   s   @r-   r  r    s(    2  $	yv:r,   r  c                 
  	 t        j                  |       		fdfd}t        d||f|	d ||      \  }}	|_        	j                  j
                  t        j                  	j                  j                           |fS )a  minimize `objective_function` with lq-CMA-ES.

    See ``help(cma.fmin)`` for the input parameter descriptions where
    `parallel_objective` is not available and noise-related options may
    fail.

    Returns the tuple ``xbest, es`` similar to `fmin2`, however `xbest`
    takes into account only some of the recent history and not all
    evaluations. `es.result` is partly based on surrogate f-values and may
    hence be confusing. In particular, `es.best` contains the solution with
    the best _surrogate_ value (which is usually of little interest). See
    `fmin_lq_surr2` for a fix.

    As in general, `es.result.xfavorite` is considered the best available
    estimate of the optimal solution.

    Example code
    ------------

    >>> import cma
    >>> x, es = cma.fmin_lq_surr(cma.ff.rosen, 2 * [0], 0.1,
    ...                          {'verbose':-9,  # verbosity for doctesting
    ...                           'ftarget':1e-2, 'seed':11})
    >>> assert 'ftarget' in es.stop(), (es.stop(), es.result_pretty())
    >>> assert es.result.evaluations < 90, es.result.evaluations  # can be 137 depending on seed

    Details
    -------
    lq-CMA-ES builds a linear or quadratic (global) model as a surrogate to
    try to circumvent evaluations of the objective function, see link below.

    This function calls `fmin2` with a surrogate as ``parallel_objective``
    argument. The model is kept the same for each restart. Use
    `fmin_lq_surr2` if this is not desirable.

    ``kwargs['callback']`` is modified by appending a callable that injects
    ``model.xopt``. This can be prevented by passing `callback=False` or
    adding `False` as an element of the callback list (see also `cma.fmin`).

    ``parallel_objective`` is assigned to a surrogate model instance of
    ``cma.fitness_models.SurrogatePopulation``.

    `es.countevals` is updated from the `evaluations` attribute of the
    constructed surrogate to count only "true" evaluations.

    See https://cma-es.github.io/lq-cma for references and details about
    the algorithm.
    c                 R    | j                  j                  j                  g       y rW   )r  modelxopt)r  	surrogates    r-   inject_xoptz!fmin_lq_surr.<locals>.inject_xopt  s    
		9??''()r,   c                     t        | j                  dd            }|du rg | d<   | S |vr|j                         || d<   | S )z*append `inject_xopt` to kwargs['callback']r  NF)r1   rN   r  )r4   cbr  s     r-   callback_in_kwargsz(fmin_lq_surr.<locals>.callback_in_kwargs  sU    vzz*d;<;!#F:  "IIk"!#F:r,   N)r  parallel_objective)	_fitness_modelsSurrogatePopulationfmin2r  r  rF  r   r  r  )
r0  r5  r9  r  r4   r  _r  r  r  s
           @@r-   fmin_lq_surrr    s    b  334FGI* $F 0G	 0&v.0EArBL??RYYy'8'89:B>>r,   r"   c
                    |i }t        j                         }
t        j                  |      }t	        d|d   z         D ]q  }|dk(  s|st        j                  |       }|dkD  r(t        j                  j                  |z  dz         |d<   t        |||      }|_        |dkD  r3|
j                  |_        |
j                  |_        d|j                  _        |j#                         s$|j%                         } ||      }|j'                  ||       |j                  |_        t)        |j*                  j,                  |j*                  j.                        D ])  \  }} ||      r|
j1                  t3        |      |       + |r&|j5                  |j6                  j8                  g       |	r#t;        |	      r	 |	|       n|	D ]
  } ||        |j                  j=                          |j?                          |j#                         s$|j@                  d   dkD  rB|jC                  |tE        jF                  tE        jH                               |
jJ                         |j                  |d	   k\  s>d
|j#                  d      v s*d	|j#                  d      v sd|j#                  d      v sr n 	 tM        jN                  j*                  j,                        }|j*                  j,                  |   jP                  jR                  _%        |j*                  j.                  |   |jP                  jR                  _*        |
jJ                  jP                  _%        |
jT                  |jP                  _*        |j^                  ja                  |
jT                        |jP                  _1        |
jd                  |jP                  _        |
j                  |jP                  _3        |
|_4        |
jT                  |fS # tV        $ r+}tY        jZ                  t]        |      dz          Y d}~d}~ww xY w#  d|jP                  _1        Y xY w)a  minimize `objective_function` with lq-CMA-ES.

    `x0` is the initial solution or can be a callable that returns an
    initial solution (different for each restarted run). See ``cma.fmin``
    for further input documentations and ``cma.CMAOptions()`` for the
    available options.

    `inject` determines whether the best solution of the model is
    reinjected in each iteration. By default, a new surrogate model is used
    after each restart (``keep_model=False``) and the population size is
    multiplied by a factor of two (``incpopsize=2``) like in IPOP-CMA-ES
    (see also ``help(cma.fmin)``).

    Returns the tuple ``xbest, es`` like `fmin2`. As in general,
    `es.result.xfavorite` (and `es.mean` as genotype) is considered the
    best available estimate of the optimal solution.

    Example code
    ------------

    >>> import cma
    >>> x, es = cma.fmin_lq_surr2(cma.ff.rosen, 2 * [0], 0.1,
    ...                           {'verbose':-9,  # verbosity for doctesting
    ...                            'ftarget':1e-2, 'seed':3})
    >>> assert 'ftarget' in es.stop(), (es.stop(), es.result_pretty())
    >>> assert es.result.evaluations < 90, es.result.evaluations  # can be >130? depending on seed
    >>> assert es.countiter < 60, es.countiter

    Details
    -------
    lq-CMA-ES builds a linear or quadratic (global) model as a surrogate to
    circumvent evaluations of the objective function, see link below.

    This code uses the ask-and-tell interface to CMA-ES via the class
    `CMAEvolutionStrategy` to the `options` `dict` is passed.

    To pass additional arguments to the objective function use
    `functools.partial`.

    `not_evaluated` must return `True` if a value indicates (by convention
    of `cma.fitness_models.SurrogatePopulation.EvaluationManager.fvalues`)
    a missing "true" evaluation of the `objective_function`.

    See https://cma-es.github.io/lq-cma for references and details about
    the algorithm.
Nr   maxrestartsr   rG   r   Tr   r  r  Fr   r  zN
  Valid assignment of `es.best.last` (best of last/current iteration) failed.)5r  BestSolution2r   amend_restarts_parameterr   r  r  rB  r   r   r   r  r  rh   r   r  r  rl   r  rm  r]  r  fvaluesrF  r  _ifloatr  r  r  r/   addrx  r   r  r   r  	localtimer9  r   	nanargminr   r  r   r  rG  r   r   rE  rN  r  count_savedcomparedbest_fmin_lq_surr2)r0  r5  r9  r  r  r   
incpopsize
keep_modelnot_evaluatedr  r   irunr  r  rF  r  r9  r   r0   r   r  s                        r-   fmin_lq_surr2r    s;   d D!::8DHa(=11219J';;<NOI!8!$RUU]]Z%?#%E!FGI!"fg6 !8$(JJI! JJBM#BII'')A!AGGAqM%11BMIOO33Y__5F5FG1 #GAJ* H 		9??//01H%RL%" &IIMMOGGI% '')& 77;!#T4<<0@#A!VV%MMXk22u--2777//"'''..K 3P.LL001 #003"**1-BGGIBGGI%%--/$$BGGMzzBGG B662:  rc!fppqqr "TBGGNs$   5)O7 84P. 7	P+ !P&&P+.Qc                 P    t        | |||||||||	|
|||||||      }|d   |d   fS )a-  functional interface to the stochastic optimizer CMA-ES
    for non-convex function minimization.

    Return the `tuple` ``(xbest, es)`` where ``es`` is a
    `CMAEvolutionStrategy` instance, see in particular ``es.result`` and
    ``es.result_pretty()`` for detailed results.


    Calling Sequences
    =================
    ``x, es = fmin2(objective_function, x0, sigma0)``
        minimizes ``objective_function`` starting at ``x0`` and with
        standard deviation ``sigma0`` (step-size)
    ``x, es = fmin2(objective_function, x0, sigma0, options={'ftarget': 1e-5})``
        minimizes ``objective_function`` up to target function value 1e-5,
        which is typically useful for benchmarking.
    ``x, es = fmin2(objective_function, x0, sigma0, args=('f',))``
        minimizes ``objective_function`` called with an additional
        argument ``'f'``.
    ``x, es = fmin2(objective_function, x0, sigma0, options={'ftarget':1e-5, 'popsize':40})``
        uses additional options ``ftarget`` and ``popsize``
    ``x, es = fmin2(objective_function, esobj, None, options={'maxfevals': 1e5})``
        uses the `CMAEvolutionStrategy` object instance ``esobj`` to
        optimize ``objective_function``, similar to ``esobj.optimize()``.

    Less recommended calling patterns are::

        es = cma.fmin2(...)[1]  # `es` contains all available information
        x = cma.fmin2(...)[0]   # keep only the best evaluated solution

    Arguments
    =========
    The order of arguments is kept for historical reasons.

    ``objective_function``
        called as ``objective_function(x, *args)`` to be minimized. ``x``
        is a one-dimensional `numpy.ndarray`. See also the
        `parallel_objective` argument. ``objective_function`` can return
        `numpy.NaN`, which is interpreted as outright rejection of solution
        ``x`` and invokes an immediate resampling and (re-)evaluation of a
        new solution not counting as function evaluation. The attribute
        ``variable_annotations`` is passed into the
        ``CMADataLogger.persistent_communication_dict``. See also
        ``constraints`` below.
    ``x0``
        list or `numpy.ndarray`, initial guess of minimum solution
        before the application of the geno-phenotype transformation
        according to the ``transformation`` option.  It can also be a
        callable that is called (without input argument) before each
        restart to yield the initial guess such that each restart may start
        from a different place. Otherwise, ``x0`` can also be a
        `cma.CMAEvolutionStrategy` object instance, in that case ``sigma0``
        can be ``None``.
    ``sigma0``
        scalar, initial standard deviation in each coordinate.
        ``sigma0`` should be about 1/4th of the search domain width
        (where the optimum is to be expected). The variables in
        ``objective_function`` should be scaled such that they
        presumably have similar sensitivity.
        See also `ScaleCoordinates`.
    ``options``
        a dictionary with additional options passed to the constructor
        of class ``CMAEvolutionStrategy``, see ``cma.CMAOptions`` ()
        for a list of available options.
    ``args=()``
        arguments to be used to call the ``objective_function``
    ``gradf=None``
        gradient of f, where ``len(gradf(x, *args)) == len(x)``.
        ``gradf`` is called once in each iteration if
        ``gradf is not None``.
    ``restarts=0``
        number of restarts with increasing population size, see also
        parameter ``incpopsize``. For the time being (this may change in
        future) ``restarts`` can also be a `dict` where the keys
        ``maxrestarts=9`` and ``maxfevals=np.inf`` are interpreted. An
        empty `dict` is interpreted as ``restarts=0``. An IPOP-CMA-ES
        restart is invoked if ``restarts > 0`` or ``restarts['maxrestarts']
        > 0`` and if ``current_evals < min((restarts['maxfevals'],
        options['maxfevals']))`` and neither the ``'ftarget'`` nor the
        ``termination_callback`` option was triggered;
        ``restarts['maxfevals']`` does not terminate *during* the run or
        restart; to restart from different points (recommended), pass
        ``x0`` as a `callable`; see also parameter ``bipop``.
    ``restart_from_best=False``
        which point to restart from
    ``incpopsize=2``
        multiplier for increasing the population size ``popsize`` before
        each restart
    ``parallel_objective``
        an objective function that accepts a list of `numpy.ndarray` as
        input and returns a `list`, which is mostly used instead of
        `objective_function`, but for the initial (also initial
        elitist) and the final evaluations unless
        ``not callable(objective_function)``. If ``parallel_objective``
        is given, the ``objective_function`` (first argument) may be
        ``None``.
    ``eval_initial_x=None``
        evaluate initial solution, for ``None`` only with elitist option
    ``noise_handler=None``
        must be `True` or a `cma.NoiseHandler` class or instance to invoke
        noise handling. The latter gives control over the specific settings
        for the noise handling, see ``help(cma.NoiseHandler)``.
    ``noise_change_sigma_exponent=1``
        exponent for the sigma increment provided by the noise handler for
        additional noise treatment. 0 means no sigma change.
    ``noise_evaluations_as_kappa=0``
        instead of applying reevaluations, the "number of evaluations"
        is (ab)used as scaling factor kappa (experimental).
    ``bipop=False``
        if ``bool(bipop) is True``, run as BIPOP-CMA-ES; BIPOP is a special
        restart strategy switching between two population sizings - small
        (relative to the large population size and with varying initial
        sigma, the first run is accounted on the "small" budget) and large
        (progressively increased as in IPOP). This makes the algorithm
        potentially solve both, functions with many regularly or
        irregularly arranged local optima (the latter by frequently
        restarting with small populations). Small populations are
        (re-)started as long as the cumulated budget_small is smaller than
        `bipop` x max(1, budget_large). For the `bipop` parameter to
        actually conduct restarts also with the larger population size,
        select a non-zero number of (IPOP) restarts; the recommended
        setting is ``restarts <= 9`` and `x0` passed as a `callable`
        that generates randomized initial solutions. Small-population
        restarts do not count into the total restart count.
    ``callback=None``
        `callable` or list of callables called at the end of each
        iteration with the current `CMAEvolutionStrategy` instance
        as argument.
    ``init_callback=None``
        `callable` or list of callables called at the end of initialization
        of the `CMAEvolutionStrategy` instance with this instance as
        argument (like `callback`). This allows to reassign attributes
        without a corresponding `CMAOption`. For example,
        ``es.integer_centering = lambda *args: None`` disables integer
        centering (which is enabled by default when ``integer_variables``
        are given in the `options`) or ``es.integer_centering =
        cma.integer_centering.IntCentering(es, correct_bias=False)``
        disables its bias correction.
    ``constraints``
        A function that takes a solution `x` as input and returns a list of
        constraint values desired to become <= 0.

    Optional Arguments
    ==================
    All values in the `options` dictionary are evaluated if they are of
    type `str`, besides `verb_filenameprefix`, see class `CMAOptions` for
    details. The full list is available by calling ``cma.CMAOptions()``.

    >>> import cma
    >>> cma.CMAOptions()  #doctest: +ELLIPSIS
    {...

    Subsets of options can be displayed, for example like
    ``cma.CMAOptions('tol')``, or ``cma.CMAOptions('bound')``,
    see also class `CMAOptions`.

    Details
    =======
    This function is an interface to the class `CMAEvolutionStrategy`. The
    latter class should be used when full control over the iteration loop
    of the optimizer is desired.

    Examples
    ========
    The following example calls `fmin2` optimizing the Rosenbrock function
    in 10-D with initial solution 0.1 and initial step-size 0.5. The
    options are specified for the usage with the `doctest` module.

    >>> import cma
    >>> # cma.CMAOptions()  # returns all possible options
    >>> options = {'CMA_diagonal':100, 'seed':1234, 'verb_time':0}
    >>>
    >>> x, es = cma.fmin2(cma.ff.rosen, [0.1] * 10, 0.3, options)  #doctest: +ELLIPSIS
    (5_w,10)-aCMA-ES (mu_w=3.2,w_1=45%) in dimension 10 (seed=1234...)
       Covariance matrix is diagonal for 100 iterations (1/ccov=26...
    Iterat #Fevals   function value  axis ratio  sigma ...
        1     10 ...
    termination on {'tolfun': 1e-11} ...
    final/bestever f-value = ...
    >>> assert es.result.fbest < 1e-12  # f-value of best found solution
    >>> assert es.result.evaluations < 8000  # evaluations

    The above call is pretty much equivalent with the slightly more
    verbose call::

        es = cma.CMAEvolutionStrategy([0.1] * 10, 0.3,
                    options=options).optimize(cma.ff.rosen)
        x = es.result.xbest

    where `optimize` returns the `CMAEvolutionStrategy` instance. The
    following example calls `fmin2` optimizing the Rastrigin function
    in 3-D with random initial solution in [-2,2], initial step-size 0.5
    and the BIPOP restart strategy (that progressively increases population).
    The options are specified for the usage with the `doctest` module.

    >>> import cma
    >>> # cma.CMAOptions()  # returns all possible options
    >>> options = {'seed':12345, 'verb_time':0, 'ftarget': 1e-8}
    >>>
    >>> x, es = cma.fmin2(cma.ff.rastrigin, lambda : 2. * np.random.rand(3) - 1, 0.5,
    ...                   options, restarts=9, bipop=True)  #doctest: +ELLIPSIS
    (3_w,7)-aCMA-ES (mu_w=2.3,w_1=58%) in dimension 3 (seed=12345...

    In either case, the method::

        cma.plot();

    (based on `matplotlib.pyplot`) produces a plot of the run and, if
    necessary::

        cma.s.figshow()

    shows the plot in a window. Finally::

        cma.s.figsave('myfirstrun')  # figsave from matplotlib.pyplot

    will save the figure in a png. The figure data can be saved like::

        es.logger.zip()

    We can use the gradient like

    >>> import cma, warnings
    >>> with warnings.catch_warnings():
    ...     warnings.simplefilter('ignore', category=cma.warnings_and_exceptions.NeverTestedWarning)
    ...     x, es = cma.fmin2(cma.ff.rosen, np.zeros(10), 0.1,
    ...             options = {'ftarget':1e-8,},
    ...             gradf=cma.ff.grad_rosen,
    ...         )  #doctest: +ELLIPSIS
    (5_w,...
    >>> assert cma.ff.rosen(es.result.xbest) < 1e-8
    >>> assert es.result.evals_best < 3600  # 1% are > 3300
    >>> assert es.result.evaluations < 3600  # 1% are > 3300

    If solutions can only be comparatively ranked, either use
    `CMAEvolutionStrategy` directly via `ask` and `tell` or a "parallel"
    objective function accepting a list of solutions as input which
    returns, for example, the solution ranks:

    >>> def parallel_sphere(X): return [cma.ff.sphere(x) for x in X]
    >>> x, es = cma.fmin2(None, 3 * [0], 0.1, {'verbose': -9},
    ...                   parallel_objective=parallel_sphere)
    >>> assert es.result.fbest < 1e-9

    :See also: `CMAEvolutionStrategy`, `OOOptimizer.optimize`, `plot`,
        `CMAOptions`, `scipy.optimize.fmin`
)constraintsr   r   )fmin)r0  r5  r9  r  r3   r  r   restart_from_bestr  eval_initial_xr  noise_handlernoise_change_sigma_exponentnoise_kappa_exponentbipopr  init_callbackr  r   s                      r-   r  r  r  sW    N !2v										$				 "C  q63r7?r,   c           
        . ddk  rZfd} |ddd      } |ddd      } |d	d
d      } |ddd      }	 |ddd      }
 |ddd	      } |ddd      } |ddd      . |ddd      } |ddd      } |ddd      } |ddd      } |ddd      } |dd d      }| s.s
t               S t               j                         }|d!= |d"= |d#= |d= |d= |t        }t               j	                  |       t        |j                               j                         }t        |      }d}g }g }d}d}d}d}t        j                         }g t        dd 	 d}|s|dkD  r|d   ||z
  z  }||z  |d%<   n|dk(  rd&}nt        |      |t        dt        |      f      z  k  rd&}ddk  r|	dz  }	|dz  }d't        j                  j                         z  }|d   ||z
  z  }t        ||t        j                  j                         d	z  z  z        |d%<   t!        |d(t        |      z  |d%   z        |d)<   nd*}|d   ||z
  z  }||z  |d%<   ||d)<   t#        |       st#        .      r.fd+} |dk(  rt%        |t&              r|} | j(                  d"   }t        j*                  |      r*t        j,                  |      r|dkD  rt/        |      | _        t/        | j(                  d#         }|t        urtt3        d, |D              r$t5        j6                  d-j9                  |             | j:                  j=                  |       n!|rB|d   d.k7  r:|d   r5t?        j@                  d/|d0   1       t'        |jB                  ||z  |      } nt'        |||z  |      } t#        |       r|s#| j:                  d2   d3k(  s| j:                  d2   r|| jE                  | jF                  d$| jH                  jJ                  | jL                  4      }!tO         | |!g|       | _(        | jR                  jU                  |!g| jL                  | jP                  gd       | xjV                  dz  c_+        | | _,        .| _-        | j:                  }t        dNi |j                         }"|"D ]&  }#|"j]                  |#| j^                  |d%   d5d6       ( ta        jb                  |"d         |"d<   |d7   xs | jd                  dkD  xs |dkD  | jf                  _4        | jf                  }$	 |$jj                  jU                  d8| jl                  i       ddk  rw| jd                  dk(  rX| j:                  d9   dkD  rF| j:                  d7   s7tq        | j:                  d:         js                  |       }$|$ju                          | jw                          |rgt%        |tx              r || j^                        }%n&|d$u r t        jz                  | j^                        }%n|}%d$}&|"d   dkD  r6t|        | j:                  d;<   n"t        jz                  | j^                  d      }%d}&|%| _?        t        |      D ]  }'|'du xs  |'|         ddk  rn| j                         s]| j                  .xs | |||%j                  t        j                  .<      \  }(})ddk  r|d=   rdt        j                  j                         z  dk\  r]d|d=   | j0                  dz  z  t        j                  j                  | j^                        z  z   |(d<   tO         | |(d   g|       |)d<   | j:                  d0   dkD  rl| jd                  d	k  s,t!        |)      | jR                  j                  j                  k  rd}*n.*dz  }*|*dkD  r$t?        j                  d>|*z  | jd                  ?       j                  d@d      +| j                  |(|)|(D !cg c]  }! d@   |!       c}!       n| j                  |(|)       |&r| xj0                   |%|(|)| | j                  |A      |"d   z  z  c_        | xjV                  |%j                  z  c_+        |%j                  |%j                  kD  r%| j                  ji                  |%j                         ddk  r| j                  xj                  t/        t        j                  | t        j                  |%j                        z              z  c_Q        | j                  j                  dkD  rdB| j                  _Q        |D ]  }'|'du xs  |'|         | j                          |$ju                  | j                         r|$j                  rdndC       |d9   rH|dD   rC| jd                  t        |dD   |d9         z  dk(  s| j                         r|$j                  dE       | j                         s]|dF   rt#        |       r| jE                  | jF                  d$| jH                  jJ                  | jL                  4      }+tO         | |+g|       },| xjV                  dz  c_+        | jR                  jU                  |+g| jL                  |,g| jV                         n|dF   rt5        j6                  dG       |jU                  | jR                  | jL                         | jV                  |z
  }-| jV                  }|dk(  r
|d%   }|d)   }|r(d&k(  r|ji                  |-       n|ji                  |-       |dH   rB| j                  |t        j                  t        j                               |j                         |dz  }t        ji                  t        | j                  dI                   ||z
  |"d   dJ   kD  sO| jV                  |"d   dK   k\  s:dL| j                         v s(dK| j                  dI      v sd| j                  dI      v rn>| jV                  |d7<   |"d   | j                  j                  z  |d%<   	 |dMxx   dz  cc<   
|r| jR                  jU                  |       | j                  | j                         | |$fz   S t        # tn        $ r Y Bw xY wc c}!w # t        $ r Y ew xY w)Oa  DEPRECATED: use `fmin2` instead.

    `fmin` will remain fully functional and be maintained in the foreseeable future.

    Return
    ======
    Return the list provided in `CMAEvolutionStrategy.result` appended
    with termination conditions, an `OOOptimizer` and a `BaseDataLogger`::

        res = es.result + (es.stop(), es, logger)

    where
        - ``res[0]`` (``xbest``) -- best evaluated solution
        - ``res[1]`` (``fbest``) -- respective function value
        - ``res[2]`` (``evals_best``) -- respective number of function evaluations
        - ``res[3]`` (``evaluations``) -- number of overall conducted objective function evaluations
        - ``res[4]`` (``iterations``) -- number of overall conducted iterations
        - ``res[5]`` (``xfavorite``) -- mean of the final sample distribution
        - ``res[6]`` (``stds``) -- effective stds of the final sample distribution
        - ``res[-3]`` (``stop``) -- termination condition(s) in a dictionary
        - ``res[-2]`` (``es``) -- class `CMAEvolutionStrategy` instance
        - ``res[-1]`` (``logger``) -- class `CMADataLogger` instance == es.logger

    The successor `fmin2` is an alias for::

        res = fmin(...)
        return res[0], res[-2]

    For descriptions of the input arguments see `fmin2`.

    For completness, recovering the output of `fmin` from `fmin2`::

        es = fmin2(...)[1]  # fmin2(...)[0] is es.result.xbest
        return es.result + (es.stop(), es, es.logger)

    The best found solution is equally available under::

        fmin(...)[0]
        fmin2(...)[0]
        fmin2(...)[1].result[0]
        fmin2(...)[1].result.xbest
        fmin2(...)[1].best.x

    The incumbent, current estimate for the optimum is available under::

        fmin(...)[5]
        fmin2(...)[1].result[5]
        fmin2(...)[1].result.xfavorite

    Examples
    ========
    The following example calls `fmin` optimizing the Rosenbrock function
    in 10-D with initial solution 0.1 and initial step-size 0.5. The
    options are specified for the usage with the `doctest` module.

    >>> import cma
    >>> # cma.CMAOptions()  # returns all possible options
    >>> options = {'CMA_diagonal':100, 'seed':1234, 'verb_time':0}
    >>>
    >>> res = cma.fmin(cma.ff.rosen, [0.1] * 10, 0.3, options)  #doctest: +ELLIPSIS
    (5_w,10)-aCMA-ES (mu_w=3.2,w_1=45%) in dimension 10 (seed=1234...)
       Covariance matrix is diagonal for 100 iterations (1/ccov=26...
    Iterat #Fevals   function value  axis ratio  sigma ...
        1     10 ...
    termination on {'tolfun': 1e-11} ...
    final/bestever f-value = ...
    >>> assert res[1] < 1e-12  # f-value of best found solution
    >>> assert res[2] < 8000  # evaluations

    The above call is pretty much equivalent with the slightly more
    verbose call::

        res = cma.CMAEvolutionStrategy([0.1] * 10, 0.3,
                    options=options).optimize(cma.ff.rosen).result

    where `optimize` returns a `CMAEvolutionStrategy` instance. The
    following example calls `fmin` optimizing the Rastrigin function
    in 3-D with random initial solution in [-2,2], initial step-size 0.5
    and the BIPOP restart strategy (that progressively increases population).
    The options are specified for the usage with the `doctest` module.

    >>> import cma
    >>> # cma.CMAOptions()  # returns all possible options
    >>> options = {'seed':12345, 'verb_time':0, 'ftarget': 1e-8}
    >>>
    >>> res = cma.fmin(cma.ff.rastrigin, lambda : 2. * np.random.rand(3) - 1, 0.5,
    ...                options, restarts=9, bipop=True)  #doctest: +ELLIPSIS
    (3_w,7)-aCMA-ES (mu_w=2.3,w_1=58%) in dimension 3 (seed=12345...

    In either case, the method::

        cma.plot();

    (based on `matplotlib.pyplot`) produces a plot of the run and, if
    necessary::

        cma.s.figshow()

    shows the plot in a window. Finally::

        cma.s.figsave('myfirstrun')  # figsave from matplotlib.pyplot

    will save the figure in a png.

    We can use the gradient like

    >>> import cma, warnings
    >>> with warnings.catch_warnings():
    ...     warnings.simplefilter('ignore', category=cma.warnings_and_exceptions.NeverTestedWarning)
    ...     res = cma.fmin(cma.ff.rosen, np.zeros(10), 0.1,
    ...             options = {'ftarget':1e-8,},
    ...             gradf=cma.ff.grad_rosen,
    ...         )  #doctest: +ELLIPSIS
    (5_w,...
    >>> assert cma.ff.rosen(res[0]) < 1e-8
    >>> assert res[2] < 3600  # 1% are > 3300
    >>> assert res[3] < 3600  # 1% are > 3300

    If solution can only be comparatively ranked, either use
    `CMAEvolutionStrategy` directly or the objective accepts a list
    of solutions as input:

    >>> def parallel_sphere(X): return [cma.ff.sphere(x) for x in X]
    >>> x, es = cma.fmin2(None, 3 * [0], 0.1, {'verbose': -9},
    ...                   parallel_objective=parallel_sphere)
    >>> assert es.result[1] < 1e-9

    :See also: `CMAEvolutionStrategy`, `OOOptimizer.optimize`, `plot`,
        `CMAOptions`, `scipy.optimize.fmin`
r   rE   c                     t              | kD  r+|v r"t        dj                  ||    |               |    S |v r|   S |S )z4check posargs and kwargs for i and key, respectivelyz{0} given as positional and keyword argument with values {1} and {2}.
Only either positional or keyword is allowed, see also `cma.fmin2`.)r   r  r   )r   rO   defaultr4   posargss      r-   r   zfmin.<locals>._get_value  sa    7|a&=$`WQZ=? ? qz!f}c{"Nr,   r   r  Nr3   r+   r"   r  r   r   r  Fr   r  r#   r  r   r  r   r  ro  r  rD   r  r  r     r     r  r0  r5  r9  Tr   smallg{Gz?rG   r  largec                      | gg| d   S )z*created from `parallel_objective` argumentr   r+   )r   r3   r  s     r-   r0  z fmin.<locals>.objective_functions  s    -qc9D9!<<r,   c              3   8   K   | ]  }t        |      |k(    y wrW   )r   )rq   r|   s     r-   rt   zfmin.<locals>.<genexpr>  s     813q6Q;s   zOptions must have explicit ("process") values in this 
usecase. The passed options are likely to lead to an error 
later. Passed options={0}Falsez+CAVE: restart_from_best is often not usefulr   r   rx  ry  )r   r   r  )r   r   )loccorrect_keyr
  variable_annotationsr   r"  r  )r  rh   rA  rC  r  z6%d f-degrading iterations (set verbose<=4 to suppress)r   r  )r3   r   )r$  r   iD  eval_final_meana  The final mean was not evaluated (probably due to a
 parallel evaluation setup). Consider checking out
 ``es.result.xfavorite`` which is likely to be better
 than ``es.result.xbest`` (on the sphere function with >= 90%
 for dimension >= 10 or population size >= 2e3/dimension**3)r   r  r  r  r  r   )	unchecked)ar   rw   r   r   check_attributesr1  r1   r  r  all_stoppingsr  r^  r   r@  uniformrB  rs  r/   r   r   r/  rh  rg  r  r:  r  rG  r   r   r   r  r   r   r   r   r   r   r   r  r  rz  r   r  r   r0  r  r2  r   r   r  r   r  r  persistent_communication_dictr  r  r   r  r  writeOutputr   NoiseHandlerr   r  rl   r4  rh   r  r   r  r9  r!  rN   rj  rm  r  evaluations_just_donemaxevalsminevalsr  r   r  r  r4  r  rx  r$  rz  r  r   r  r  rv   r   r  r  KeyboardInterrupt)/r0  r5  r9  r  r4   r   r  r3   r  r   r  r  r  r  r  r  r  r  r  fmin_optionsr   runs_with_smallsmall_ilarge_ipopsize0maxiter0
base_evalsr  r   sigma_factorpopsize_multiplierpoptyper  r   	fmin_optsr{   r  noisehandlerr   r9  rF  r  degrading_iterations_count
mean_phenofmean
this_evalsr  s/      ``                                         @r-   r  r    s   F 	1u	 Q	40!VR(1gt,aQ/&q*=uE<3
#A'7?'+?F"1ot<&04QST&U#)".DaH2w.b*d3"2=!*<<x}}-."# ?)G%%g.',,.)446$X. 
 aL  !8)5l)Cd_F\)]&&.1C&CDO
 "WQG,=(> >>!6MH1$#RYY%6%6%88%1,%?$BX%Y""%h1CbiiFWFWFY[\F\1]&]"^Y"%hc'l0BT)_0T"UY "%1,%?$BX%Y""*-?"?Y"*Y ./H=O4P=
 qyZ,@A\\$';;v&2;;v+>6A:$V}BHr||H56"55888 88>wI GGKK( \*=>'I!-.A!B''(U04YA-dfflV6KTRB-b,2GNB./&77=1Y>GGM2$2$:d464G4G4N4N020A0A ( CA $$6q$@4$@ABEGGNNA3(9(9$&EE7A/MMQ&M$6B!$6B!77D"F,2C2C2EFI qBDD26y/'C+0  2  %7$O$Oj)%+Ij!  $M2RbllQ6FR$QR(BII YYF44;;+&;;=> Av<<1$)<q)@GGM2)"''2G*H ..6hrl ::< mT2#0#6L"d*#%??244#8L#0L!%:;a?+.BGGK(!rttQ7!&+B&}5T	"QrU 6
 1u'')__-?-UCU-19E9Q9Q9;;M	 - OFAs Av$t*ryy00A5#$tDzBHHaK'?"))//RTRVRVBW'W#WAaD%,-?!-Lt-L%MCFwwy)A-<<!+s3x277<<>>/I9:66!;69A= % 3 34l6P5Q>@ll!L zz-6BCA)NAq*?&*?*BA)NO3%LC9KRVV6:%<=FGd=e%f f )K)KK'00<3H3HH,,33L4L4LMq5
 EEKK59M8M:<'',BUBU:V9W 2X ,Y YK!uu{{Q.1%T	*QrU &GGIJJ+-779aD  RZ(T+-><<#d;.?jAQ*RRVWW[][b[b[dC(k '')p %&84F+G__RWW49;9L9L9S9S575F5F - H
   2: E EF"
|R->->W'( U V KK!2!23 3JJ qy	?	? g%NN:.NN:. K   t||DNN4D'E!%) AID   bggEg&:!;<&:)>})MM}}	*(=k(JJ BGGI-"bggEg&::!RWW5W%99"$--D'5EDOV!m z GGNN4 {{bggiV444
  w " r *Oh  s*   'q* q:q? *	q76q7?	r
rc                     g S rW   r+   r   s    r-   no_constraintsr  P  s    Ir,   c                     d fd}t        |      }|D ]  }|j                  |         ||      }|	| || _        |S )zAtry to figure a good logging value from various verbosity optionsc                     | |   }|j                  d      d   }t        j                  |      }|S # t        t        f$ r Y (w xY w# t
        $ r Y |S w xY w)N#r   )r  r  r  r;  r<  r  )r  rO   r|   s      r-   rN   z_al_set_logging.<locals>.getU  sX    cFaQ!!!$Q 	*0D04 	 s    1 A AA	AAc                     d| v r| d   S d| v r | d      dk  ryd| v r%| d   }d|v r	 |d      S d|v r |d      dk  ryy y y )Nr  r   r   Fr  r   r+   )r4   korN   s     r-   extract_logging_valuez._al_set_logging.<locals>.extract_logging_value\  sz    )$$3vy#9R#?	"BR2z**B3r9#5#; $<	 r,   )rv   r  r  )alr4   more_kwargsr  r'  r  rN   s         @r-   _al_set_loggingr  S  sN    
 &\Fa #F+Gr~
Nr,   c                 J    d|v rt        d      r)t        k7  r t        t              rdk  rt        d      t	        |j                  dg             r	|d   g|d<   g g t        j                  t        |            a	t        t        |       t        j                         |rit        j                  t        j                        t        j                  t        j                        t        j                  t        j                         gng  fdfdfd}fd	}	fd
}
|d   j#                  |	|
g       |j                  di       j                  dd       t%        |||fi |\  }}t        g|_        t        |_        |_        rՈfd}|j-                         }d|j                  di       d<   t%        ||j.                  j0                  |j2                  fi |\  }}|j4                  j6                  dk(  rt9          |j4                  j:                              |j*                  j=                  dgd|j4                  j:                  |j4                  j:                  dd       |j*                  j:                  |fS |j.                  j0                  } |       |      }}t?        |D cg c]  }|dk  	 c}      rqt?        |D cg c]  }|dz  dz  k   c}      rOt9          |            }|j*                  j=                  ||d|||tA        |      tA        |      z   |d       ||fS tC        jD                  d|jF                  d          |_$        |j.                  j0                  |fS c c}w c c}w )a7  DEPRECATED: use `cma.ConstrainedFitnessAL` or `cma.fmin_con2` instead.

    Optimize f with constraints g (inequalities) and h (equalities).

    Construct an Augmented Lagrangian instance ``f_aug_lag`` of the type
    `cma.constraints_handler.AugmentedLagrangian` from `objective_function`
    and `g` and `h`.

    Equality constraints should preferably be passed as two inequality
    constraints like ``[h - eps, -h - eps]``, with eps >= 0. When eps > 0,
    also feasible solution tracking can succeed.

    Return a `tuple` ``es.results.xfavorite:numpy.array, es:CMAEvolutionStrategy``,
    where ``es == cma.fmin2(f_aug_lag, x0, sigma0, **kwargs)[1]``.

    Depending on ``kwargs['logging']`` and on the verbosity settings in
    ``kwargs['options']``, the `AugmentedLagrangian` writes (hidden)
    logging files.

    The second return value:`CMAEvolutionStrategy` has an (additional)
    attribute ``best_feasible`` which contains the information about the
    best feasible solution in the ``best_feasible.info`` dictionary, given
    any feasible solution was found. This only works with inequality
    constraints (equality constraints are wrongly interpreted as inequality
    constraints).

    If `post_optimization` is set to True, then the attribute ``best_feasible``
    of the second return value will be updated with the best feasible solution obtained by
    optimizing the sum of the positive constraints squared starting from
    the point ``es.results.xfavorite``. Additionally, the first return value will
    be the best feasible solution obtained in post-optimization.

    In case when equality constraints are present and a "feasible" solution is requested,
    then `post_optimization` must be a strictly positive float indicating the error
    on the inequality constraints.

    The second return value:`CMAEvolutionStrategy` has also a
    `con_archives` attribute which is nonempty if `archiving`. The last
    element of each archive is the best feasible solution if there was any.

    See `cma.fmin2` for the further parameters ``**kwargs``.

    >>> import cma
    >>> x, es = cma.evolution_strategy.fmin_con(
    ...             cma.ff.sphere, 3 * [0], 1, g=lambda x: [1 - x[0]**2, -(1 - x[0]**2) - 1e-6],
    ...             options={'termination_callback': lambda es: -1e-5 < sum(es.mean**2) - 1 < 1e-5,
    ...                      'verbose':-9})
    >>> assert 'callback' in es.stop()
    >>> assert es.result.evaluations < 1500  # 10%-ish above 1000, 1%-ish above 1300
    >>> assert (sum(es.mean**2) - 1)**2 < 1e-9, es.mean

    >>> x, es = cma.evolution_strategy.fmin_con(
    ...             cma.ff.sphere, 2 * [0], 1, g=lambda x: [1 - x[0]**2],
    ...             options={'termination_callback': lambda es: -1e-8 < sum(es.mean**2) - 1 < 1e-8,
    ...                      'seed':1, 'verbose':-9})
    >>> assert es.best_feasible.f < 1 + 1e-5, es.best_feasible.f
    >>> ".info attribute dictionary keys: {0}".format(sorted(es.best_feasible.info))
    ".info attribute dictionary keys: ['f', 'g', 'g_al', 'x']"

    Details: this is a versatile function subject to changes. It is possible to access
    the `AugmentedLagrangian` instance like

    >>> al = es.augmented_lagrangian
    >>> isinstance(al, cma.constraints_handler.AugmentedLagrangian)
    True
    >>> # al.logger.plot()  # plots the evolution of AL coefficients

    >>> x, es = cma.evolution_strategy.fmin_con(
    ...             cma.ff.sphere, 2 * [0], 1, g=lambda x: [y+1 for y in x],
    ...             post_optimization=True, options={"verbose": -9})
    >>> assert all(y <= -1 for y in x)  # assert feasibility of x

r  z?`parallel_objective` parameter is not supported by cma.fmin_conr   zWhen equality constraints are given, the argument``post_optimization`` must be a strictly positive float indicating the error on the inequality constraintsr  c                 N    j                  t         |                    d   S )Nr   )r  r  )r   r  r0  s    r-   r9  zfmin_con.<locals>.f  s#    	+A./0ur,   c                 h    |        |       }}t         j                  gt         j                  t        |      t        |      z          t	        j
                  t        |      dgz  t        |      dgz  z   d      t         _        j                  t        |      t        |      z          d   S )NFTr]  r   r   )	_alr  set_mr   r   r  	_equalityr  r  )r   r+  hvalsr  r  hs      r-   r  zfmin_con.<locals>.constraints  s    tQqTu77?IIc%j3u:-.JJs5zUG';c%jD6>Q'Q-35CM	etE{*+ur,   c                 b   t         
|              	|       }}t        |      }t        |D cg c]  }|dk  	 c}      rj                  |||| | |||d       t	        j
                  t        j                  | |||      }D ]  }|j                  |||        |t        |      z   S c c}w )Nr   )r   r9  r  g_alr  )r  r  r  r  r  r"  r#  r  )r   r*  r+  r,  r  r  r)  archivesbest_feasible_solutionr  r9  s          r-   auglagzfmin_con.<locals>.auglag  s    adm[^eU%(%Ba%()"))$vq$E&B * C $99OOQeV=AHHT5$' c&k!! )s   B,c                 H    t         j                         g g cd d  d d  y rW   )r  r  )r  r  r  s    r-   r  z"fmin_con.<locals>.set_coefficients  s&    Q"
!adr,   c                 v    | j                  dd      d   }t        j                   |       |             y )Nr   r   )r  )r  r  r  )r  r   r  r9  s     r-   r  zfmin_con.<locals>.update  s0    FF1F"1%

1Q4Q(r,   r  r  c           	      |    t        t        d  |       D              t        fd |       D              z         S )Nc              3   2   K   | ]  }|d kD  s	|dz    ywr  r+   r  s     r-   rt   z+fmin_con.<locals>.f_post.<locals>.<genexpr>  s     @2arQwr  c              3   @   K   | ]  }|d z  d z  kD  s|d z    yw)r"   Nr+   )rq   hipost_optimizations     r-   rt   z+fmin_con.<locals>.f_post.<locals>.<genexpr>  s-      GW-1rR1W?PTU?U5U27Ts   
)r  r  )r   r  r  r)  s    r-   f_postzfmin_con.<locals>.f_post  sG    3@1@@3 GW-.qTGW DW W X Xr,   r  r   N)r   r9  r  )r   r  r"   )r   r9  r  r  z"Post optimization was unsuccessfulr   r   )%r  r  r   r  r/   
setdefaultr  r  r   r  r  r  r  r  r  r  r  extendr  objective_function_complementsr  ru   r   r  rj   r:  r   r9  r  r   r  r  r  r   r   r   con_archives)r0  r5  r9  r  r  r)  	archivingr4   r"  r  r  r  r  r*  kwargs_postes_postx_postg_x_posth_x_postr  r(  f_x_postr  r  r   r!  r  r9  s   `  ```                @@@@@@r-   fmin_conr6  o  s_   \ v%Z[[Q.0,e48IQ8N T U 	U !!*b12$Z01z 	A
A

2
23r7
;CC 
  446 <<=Q=\=\] <<=Q=\=\] <<=Q=d=de
 ") :/89 i$//C&"f//EAr),B%!B-B	X kkm;<y"-i86299#6#6 *(*
7<<>>Q*7<<>>:;A ##AtTW\\^^!(!"!% $  ##%%r))))vY&	((+(Ba(+,J2R1W 1Q 66JK1&9:H##Hh%+%-%)(^d8n%D%-	 $  2: D(*	(:< BO99""! ,Js   N0N c                    t        |t              st        |t              rt        d      |i }|j                  di       j                  dd       t	        d||      }|||d<   t        j                  | |fd|i|}	d|vs|d   |	j                  g|d<   nt        |d         |	j                  gz   |d<   t        |	||fi |\  }
}|j                  |	u sJ |r|	j                  |      }|d   j                  d	d      r{ ||j                  j                        }|	j                  |t!         | |            ||	j#                  |             |	j$                  j&                  }n|j                  j                  }|	j$                  |_        |	j*                  |_        ||fS #  |d   g|	j                  gz   |d<   Y xY w)
a  optimize f with inequality constraints g.

    `constraints` is a function that returns a list of constraints values,
    where feasibility means <= 0. An equality constraint ``h(x) == 0`` can
    be expressed as two inequality constraints like ``[h(x) - eps, -h(x) -
    eps]`` with ``eps >= 0``.

    `find_feasible_...` arguments toggle to search for a feasible solution
    before and after the constrained problem is optimized. Because this can
    not work with equality constraints, where the feasible domain has zero
    volume, find-feasible arguments are `False` by default.

    `kwargs_confit` are keyword arguments to instantiate
    `constraints_handler.ConstrainedFitnessAL` which is optimized and
    returned as `objective_function` attribute in the second return
    argument (type `CMAEvolutionStrategy`).

    Other and further keyword arguments are passed (in ``**kwargs_fmin``)
    to `cma.fmin2`.

    Consider using `ConstrainedFitnessAL` directly instead of `fmin_con2`.

zFound an unexected `dict` as argument. Recheck the calling signature.
Use the keyword `options={...}` to pass an options argument for `fmin2`.
Use the keyword syntax also for any further arguments passed to `fmin2`.Nr  r  r   r  find_feasible_firstr  r  )r   rv   r  r+  r  r  ConstrainedFitnessALr  r  r  r0  find_feasiblerN   r  rj   _update_bestr  r  r  r   ru   r   r.  )r0  r5  r9  r  r8  find_feasible_finalkwargs_confitkwargs_fminr  r1  r  r  r   r  s                 r-   	fmin_con2r?  -  s   8 %t,
;NPT0U f g 	g 9b)44_aHdK?G#*i  
3
3 3 C $J(?(G#&::,J'+K
,C'D

|'S[$ #r61[1EAr  C''' b!y!%%&7>BII//0AQ(:1(= >366!9MAII}}BllBOb5L' 	S;z+B*Cszzl*RJ's   F" "F>r|  rW   )Nr+   Nr   Fr"   FNNr   r   FNNN)hr*   
__future__r   r   r   collectionsutilities.python3for2r   ra  r  r   rG  r;  numpyr   r   r	   r'  r
   r   r   r   r  r   	utilitiesr   r   r   r   r,  r   r  cmar   r  r   r   r   r   rY  r   r  r   utilities.utilsr   r  r   r   r  utilities.mathr   r   r  sigma_adaptationr    rQ  r  r!  r$  r   r  r  _wherer  use_archivesversion_infor  r  r  r  r  UserWarningr%   r1   r5   r:   r7   rv   r8   
_debuggingr  _assertions_quadratic_assertions_cubic_depreciated
namedtuplerd   objectrn   rx   r   OOOptimizerr   r  r  r  isnanr  r  r  r  r  r  r6  r?  r+   r,   r-   <module>rU     ss  V   ( 
 	   
       &   ? 6 9 1 E E / ! 6 " : 1  1$( ! [%( ",  \  [   [	no&))U2 I   U**e3 K *. &;    e@{ @	%Q
3- 3jT * 
  *!7!7!7  	#
" *XYe& Yev-% -^S3:11 S3jfD?& D?L4 BA?F ;?a""((m`   %&Wt A F: 5|#~ (!&!&	Fr,   