
    J-jH              N       n   d Z ddlZddlmZ ddlZddl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Z	 dZ	 d
ZeZ	 dZ	 dZ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/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSej*                  dTz   dUdVdWdXdYfNdZZ e       Z e ed[ ej5                         D                    Z ed\ eD              Zdid]Zd^ Zd_ Z d` Z!da Z"dbD  ci c]  } |  e#e|        c} Z$ G dc dde      Z% e% e             Z G de dfe&      Z' G dg dhe&      Z(yc c} w )jz#Parameters and Options for CMA-ES.
    N)inf   )boundary_handler)	utilities)utils)CMADataLogger)RecombinationWeightsg?	   zWTrue  # or False or any CMAAdaptSigmaBase class e.g. CMAAdaptSigmaTPA, CMAAdaptSigmaCSAz<True  # negative update, conducted after the original updatezB0  #v weight multiplier for negative weights of injected solutionsz%1  # learning rate for the mean valuezMFalse  # normalize trace, 1, True, "arithm", "geom", "aeig", "geig" are validzY0*100*N/popsize**0.5  # nb of iterations with diagonal covariance matrix, True for alwaysz<0  # learning rate multiplier for additional diagonal updatezGnp.linalg.eigh  # or cma.utilities.math.eig or pygsl.eigen.eigenvectorszPFalse  #v or "initial" or True, elitism likely impairs global search performancezM1  #v keep length if Mahalanobis length is below the given relative thresholdzupopsize < 6  # values <0.5 are interpreted as fraction, values >1 as numbers (rounded), for `True` about 0.16 is usedz92  # 0=unconditional, 1=selective, 2=selective with delayz<None  # parents selection parameter, default is popsize // 2z11  # multiplier for all covariance matrix updateszzNone  # a class or instance that implements the interface of `cma.interfaces.StatisticalModelSamplerWithZeroMeanBaseClass`zE{}  # options passed to `CMA_sampler` class init as keyword argumentszG1.0  # multiplier for rank-mu update learning rate of covariance matrixzH1.0  # multiplier for rank-one update learning rate of covariance matrixzUNone  # a list, see class RecombinationWeights, overwrites CMA_mu and popsize optionszdnp.inf  # tentative and subject to changes, 0.5 would be a "default" damping for sigma vector updatez=0.1  # tentative fading out parameter for sigma vector updatezkNone  # factors for non-isotropic initial distr. of C, mainly for test purpose, see CMA_stds for productionzoNone  # multipliers for sigma0 in each coordinate (not represented in C), or use `cma.ScaleCoordinates` insteadzV1  #v positive multiplier for step-size damping, 0.3 is close to optimal on the spherezNone  # exponent for mueff/N, by default 0.5 and 1 if CSA_squared, zero means no dependency of damping on mueff, useful with CSA_disregard_length optionz>False  #v True is untested, also changes respective parameterszhNone  #v poorly tested, [0, 0] means const length N**0.5, [-1, 1] allows a variation of +- N/(N+2), etc.z2False  #v use squared length for sigma-adaptation z6False  #v pc is invariant and ps (default) is unbiasedz81  #v positive multiplier for step-size damping with TPAz|False  #v number of iterations of median worsenings threshold at which the sigma change is stalled; the default may become 2zQBoundTransform  # or BoundPenalty, unused when ``bounds in (None, [None, None])``z^[None, None]  # lower (=bounds[0]) and upper domain boundaries, each a scalar or a list/vectorzR[1e8, 1e12]  # when to alleviate the condition in the coordinates and in main axeszETrue  # evaluate the final mean, which is a favorite return candidatezTNone  # dictionary with index-value pairs like {0:1.1, 2:0.1} that are not optimizedz,-inf  #v target function value, minimizationz[]  # index list, invokes basic integer handling by setting minstd of integer variables if it was not given and by integer centeringzeis_feasible  #v a function that computes feasibility, by default lambda x, f: f not in (None, np.nan)z.inf  #v maximum number of function evaluationszE100 + 150 * (N+3)**2 // popsize**0.5  #v maximum number of iterationszAFalse #v sample two new solutions colinear to previous mean shiftzI0  #v minimal std in any arbitrary direction, cave interference with tol*z]0  #v minimal std (scalar or vector) in any coordinate direction, cave interference with tol*zCNone  #v maximal std (scalar or vector) in any coordinate directionzN1/3  # maximal std relative to bound_range per coordinate, overruled by maxstdz4False #v one line sample along the evolution path pczl4 + 3 * math.log(N)  # population size, AKA lambda, int(popsize) is the number of new solution per iterationzK1  # multiplier for popsize, convenience option to increase default popsizezpnp.random.randn  #v randn(lam, N) must return an np.array of shape (lam, N), see also cma.utilities.math.randhssa  None  # deprecated, rather use fitness_transformations.ScaleCoordinates instead (or CMA_stds). WAS: Scale for each variable in that effective_sigma0 = sigma0*scaling. Internally the variables are divided by scaling_of_variables and sigma is unchanged, default is `np.ones(N)`ztime  # random number seed for `numpy.random`; `None` and `0` equate to `time`, `np.nan` means "do nothing", see also option "randn"zcma_signals.in  # read versatile options from this file which contains a single options dict, e.g. ``{"timeout": 0}`` to stop right away, some string-values are recognized, e.g. "np.inf" is valid, use `None` or `""` for no filez[]  #v a function or list of functions returning True for termination, called in `stop` with `self` as argument, could be abused for side effectszjinf  #v stop if timeout seconds are exceeded, the string "2.5 * 60**2" evaluates to 2 hours and 30 minuteszR1e14  #v stop if the condition of the covariance matrix is above `tolconditioncov`z1e3  #v termination when step-size increases by tolfacupx (diverges). That is, the initial step-size was chosen far too small and better solutions were found far away from the initial solution x0zy1e20  #v sigma/sigma0 > tolupsigma * max(eivenvals(C)**0.5) indicates "creeping behavior" with usually minor improvementsz?1  #v iterations tolerated with flat fitness before terminationzJ1e-11  #v termination criterion: tolerance in function value, quite usefulzD1e-12  #v termination criterion: tolerance in function value historyzw0  #v termination criterion: relative tolerance in function value: Delta f current < tolfunrel * (median0 - median_min)zaint(100 + 100 * N**1.5 / popsize)  #v termination if no improvement over tolstagnation iterationsa  [1e-9, 20, 0.1]  #v termination thresholds for Delta of [mean, iterations, iterations fraction], the latter two are summed; trigger termination if Dmean stays below the threshold over Diter iterations, pass `False` or a negative value to turn off tolxstagnationz71e-11  #v termination criterion: tolerance in x-changeszTNone  # deprecated, use a wrapper like those in cma.fitness_transformations instead.zENone  # deprecated, use `cma.fitness_transformations.Shifted` insteadz\None  #v number of iterations without distribution update, name is subject to future changesz3  #v verbosity e.g. of initial/final message and logging,
 -1 is very quiet, <=-9 is maximally quiet, <=-10 ignores the signals_filenamezI0  # initial evaluation counter, if append, do not overwrite output fileszC100  #v verbosity: display console output every verb_disp iterationz/inf  #v start overwriting after given iterationz-  # output path (folder) and filenames prefixzy1  #v verbosity: write data to files every verb_log iteration, writing can be time critical on fast to evaluate functionszyN * (N <= 50)  # allow to execute eigendecomposition for logging every verb_log_expensive iteration, 0 or False for neverz<0  #v in fmin2(): plot() is called every verb_plot iterationz"True  #v output timings on consolezW{}  #? versatile set or dictionary for hacking purposes, value found in self.opts["vv"]cN                 (    t        t                     S )zuse this function to get keyword completion for `CMAOptions`.

    ``cma.CMAOptions('substr')`` provides even substring search.

    returns default options as a `dict` (not a `cma.CMAOptions` `dict`).
    )dictlocals)N
AdaptSigma
CMA_activeCMA_active_injected	CMA_cmeanCMA_const_traceCMA_diagonalCMA_diagonal_decodingCMA_eigenmethodCMA_elitist!CMA_injections_threshold_keep_lenCMA_mirrorsCMA_mirrormethodCMA_muCMA_onCMA_samplerCMA_sampler_options
CMA_rankmuCMA_rankoneCMA_recombination_weightsCMA_dampsvec_facCMA_dampsvec_fadeCMA_teststdsCMA_stdsCSA_dampfacCSA_damp_mueff_exponentCSA_disregard_lengthCSA_clip_length_valueCSA_squaredCSA_invariant_pathTPA_dampfac+stall_sigma_change_on_divergence_iterationsBoundaryHandlerboundsconditioncov_alleviateeval_final_meanfixed_variablesftargetinteger_variablesis_feasible	maxfevalsmaxitermean_shift_line_samplesmindxminstdmaxstdmaxstd_boundrangepc_line_samplespopsizepopsize_factorrandnscaling_of_variablesseedsignals_filenametermination_callbacktimeouttolconditioncov	tolfacupx
tolupsigmatolflatfitnesstolfun
tolfunhist	tolfunreltolstagnationtolxstagnationtolxtransformation	typical_xupdatecovwaitverboseverb_append	verb_dispverb_disp_overwriteverb_filenameprefixverb_logverb_log_expensive	verb_plot	verb_timevvsN                                                                                 d/Users/jameslopez/projects/TradingBot25/.venv/lib/python3.12/site-packages/cma/options_parameters.pycma_default_options_r]      s    b >    c              #   N   K   | ]  \  }}|j                  d       dkD  r|  yw)z #v r   N)find).0kvs      r\   	<genexpr>rd      s,      %<5P6Aq()v(: &'5Ps   #%c              #   @   K   | ]  }|j                         |g  y wN)lower)ra   ss     r\   rd   rd      s     L8K1A8Ks   c                     t        | |r|n|       }t        j                  j                  ||rdndz        }t	        t
        t        |z  | z  t        dz  | z  f      S )a  can be reassigned/overwritten like a global "parameter setting"

    This function returns the minimum of three bounds, an absolute bound
    (default 0.2), mueff / N, and a bound computed from the normal quantile
    (when the mean is assumed to be in the domain middle) which takes
    ``ptarget=integer_lower_bound_target_probability(N, N_int)`` (which
    should be roughly 1/N) as input. This bound becomes < 0.2 only when
    ptarget < 1/152 (==> < -2.5-sigma).
    r            ?)&integer_lower_bound_target_probabilityr   math
normal_ppfmininteger_std_lower_bound_limitinteger_std_lower_bound_factor1integer_std_lower_bound_factor2)NmueffN_intbinaryptargetppfs         r\   integer_std_lower_boundry      sb     5QANG
..
#
#GFq$B
CC-/%7!;/#5<  r^   c                 X    || kD  rt        dj                  ||             dd| z   |z   z  S )a  target probability for an integer mutation assuming a centered mean

    and no boundaries (two-tailed).

    ``2 / (N + N_int)`` should keep at least 37% of the solutions unaffected.

    Details: from ``ptarget`` we can compute ``sigma = 1 / PPF(ptarget/2) /
    2`` where ``PPF`` is the quantile function of the standard normal
    distribution and the first ``2`` accounts for two-sided sampling of the
    tails and the second ``2`` is needed because the distance to the value
    domain bound is 1/2.
    z({0}=N_int > N = {1} is not a valid casesrj   )
ValueErrorformat)rs   ru   s     r\   rl   rl      s8     qyCJJ5RSTUUAr^   c                     | du r	dt         i} n| sddi} t        | t              sd| i} | j                  dt                | j                  dt        j
                         | S )zreturn a `dict` with ``'maxrestarts'`` and ``'maxfevals'`` as keys.

    `restarts` is a parameter to ``cma.fmin*``, see `cma.fmin`.
    Tmaxrestartsr   r5   )"default_restart_number_if_not_zero
isinstancer   
setdefaultnpr   )restartss    r\   amend_restarts_parameterr      sb    
 4!#EF!1%h%!8,'IJRVV,Or^   c                 :    |duxr t        j                  |       S )zdefault to check feasibility of f-values.

    Used for rejection sampling in method `ask_and_eval`.

    :See also: CMAOptions, ``CMAOptions('feas')``.
    N)r   is_nan)xfs     r\   r4   r4      s     D=0a00r^   c                     ddl m} |j                  | j                  d      d   t	        d dD                    j                  dd      j                  d	d
      S )a  return a string safe to `eval` or raise an exception.

    Selected words and chars are considered safe such that all default
    string-type option values from `CMAOptions()` pass. This function is
    implemented for convenience, to keep the default option format
    backwards compatible, and to be able to pass, for example, `3 * N`.
    Function or class names other than those from the default values cannot
    be passed as strings (any more) but only as the function or class
    themselves.
    r   )purecma#r   c              3   $   K   | ]  }||g 
 y wrf    )ra   rb   s     r\   rd   zsafe_str.<locals>.<genexpr>   s       	!-", -.!Q",s   )TrueFalseNoners   dimr=   intzmath.logznp.infr   znp.logznp.random.randntimeBoundTransformr4   znp.linalg.eighz{}/zN oner   z/  /z//) r   safe_strsplitr   replace)rh   r   s     r\   r   r      s[     AGGCLO  	!-",	!- 	- &ggv ((/(=>r^   )	BoundNoneBoundPenaltyr   c                        e Zd ZdZdZdZdZed        Zed        Z	ddZ
ddZddZd fd		Zdd
ZddZd Zed        ZddZd ZddZddZddZd Zd Zd Zed        Zd ZddZ xZS ) 
CMAOptionsaZ  a dictionary with the available options and their default values
    for class `CMAEvolutionStrategy`.

    ``CMAOptions()`` returns a `dict` with all available options and their
    default values with a comment string.

    ``CMAOptions('verb')`` returns a subset of recognized options that
    contain 'verb' in there keyword name or (default) value or
    description.

    ``CMAOptions(opts)`` returns the subset of recognized options in
    ``dict(opts)``.

    Option values can be "written" in a string and, when passed to `fmin2`
    or `CMAEvolutionStrategy`, are evaluated using "N" and "popsize" as
    known values for dimension and population size (sample size, number
    of new solutions per iteration). All default option values are given
    as such a string.

    Details
    -------
    `CMAOptions` entries starting with ``tol`` are termination
    "tolerances".

    For `tolstagnation`, the median over the first and the second half
    of at least `tolstagnation` iterations are compared for both, the
    per-iteration best and per-iteration median function value.

    Example
    -------
    ::

        import cma
        cma.CMAOptions('tol')

    is a shortcut for ``cma.CMAOptions().match('tol')`` that returns all
    options that contain 'tol' in their name or description.

    To set an option::

        import cma
        opts = cma.CMAOptions()
        opts.set('tolfun', 1e-12)
        opts['tolx'] = 1e-11

    todo: this class is overly complex and should be re-written, possibly
    with reduced functionality.

    :See also: `fmin2` (), `CMAEvolutionStrategy`, `CMAParameters`

    FTc                      t         S )z>return a dictionary with default option values and description)cma_default_optionsr   r^   r\   defaultszCMAOptions.defaults*  s
     #"r^   c                      t         S )ac  return list of options that can be changed at any time (not
        only be initialized).

        Consider that this list might not be entirely up
        to date.

        The string ' #v ' in the default value indicates a versatile
        option that can be changed any time, however a string will not
        necessarily be evaluated again.

        )cma_versatile_optionsr   r^   r\   versatile_optionszCMAOptions.versatile_options2  s
     %$r^   c                 l    | j                  |       | j                  |       | j                  |       | S )z6check for ambiguous keys and move attributes into dict)check_valuescheck_attributes)selfoptionss     r\   checkzCMAOptions.checkA  s1    '"g&'"r^   c                    t               j                  }g }g }|| }|D ]  } ||      }|Dt        |dt        t	        t        |                  dt        t	        t
                          ||v r*||k(  r||j                  |         }t        |d|d      |j                  |       |j                  |        |S )Nz2 is not a valid option.
Similar valid options are z
Valid options are z was not a unique key for z option)r   corrected_keyr{   strlistr   indexappend)r   r   r   validated_keysoriginal_keyskeycorrect_keys          r\   r   zCMAOptions.check_valuesG  s    "22?GC',K"  "%c$/B3/G*H&I!$T*=%>!?	"A B B
 n,+%'(<(<S(ABC K") * *!!+.  %  r^   c           
         || }ddk  rut        |d      rg|j                  D ]X  }|| j                  vst        d|j                  j	                         d   d|j                  j	                         d   d       | S t        |d      rht        |j                        D ]P  }|| j                  v rt        j                  d|d	|d
|ddd       |j                  |   ||<   t        ||       R |S )z7check for attributes and moves them into the dictionary      __dict__z5
                        Assign options with ``opts['r   z/']``
                        instead of ``opts.z``
                        z
        An option attribute has been merged into the dictionary,
        thereby possibly overwriting the dictionary value, and the
        attribute has been removed. Assign options with

            ``opts['zO'] = value``  # dictionary assignment

        or use

            ``opts.set('zW', value)  # here isinstance(opts, CMAOptions)

        instead of

            ``opts.z; = value``  # attribute assignment
                        r   r   )	hasattrr   _attributesr{   keysr   r   print_warningdelattr)r   optsr   s      r\   r   zCMAOptions.check_attributes]  s    <D6tZ(==C$"2"22(  $}}113A6#}}113A6	*8 9 9 ) K
 tZ(.Cd... ''  #C. 07F" !%c 2DID#&+ /0 Kr^   c                    |*|s(t         t        |   t        j                                d}nt	        j
                  |      r>|j                  d      s-t         t        |   t               j                  |             d}net        |t              r!|rt        d      t         t        |   |       n4|r'||j                  d      rt         t        |   |       nt        d      t	        j
                  |      r|j                  d      s| j                          t        | j                               D ]{  }| j                  |      }|t        j                         vr8t	        j                  dt!        |      z   dz   d	d
       | j#                  |       b||k7  sh| j#                  |      | |<   } d| _        | j&                  j)                         | _        t-        | j*                        | j*                  d<   y)aI  return an `CMAOptions` instance.

        Return default options if ``s is None and not kwargs``,
        or all options whose name or description contains `s`, if
        `s` is a (search) string (case is disregarded in the match),
        or with entries from dictionary `s` as options,
        or with kwargs as options if ``s is None``,
        in any of the latter cases not complemented with default options
        or settings.

        Returns: see above.

        Details: as several options start with ``'s'``, ``s=value`` is
        not valid as an option setting.

        Nnocheck	uncheckedz-Dictionary argument must be the only argumentzMThe first argument must be a string or a dict or a keyword argument or `None`)r   r   zinvalid key ``z
`` removed__init__r   Fr   )superr   r   r   r   is_str
startswithmatchr   r   r{   r   r   r   r   r   r   pop_lock_settingr   copyr   len)r   rh   kwargsr   r   	__class__s        r\   r   zCMAOptions.__init__  s   & 9V*d,Z-@-@-BCA\\!_Q\\+%>*d,Z\-?-?-BCA4  !PQQ*d,Q/all;&?*d,V4lmm||Aall3K&LJJLDIIK("005j&9&9&;;''(83s8(C#/)01;\KHHSMK'(,D% ) #==--/*-d.>.>*?'r^   c                     | j                  |       |}|||i}|j                         D ]O  \  }}| j                  |      }|t        j	                         vr|s0t        dt        |      z   dz          K|| |<   Q | S )a  initialize one or several options.

        Arguments
        ---------
            `dict_or_str`
                a dictionary if ``val is None``, otherwise a key.
                If `val` is provided `dict_or_str` must be a valid key.
            `val`
                value for key

        Details
        -------
        Only known keys are accepted. Known keys are in `CMAOptions.defaults()`

        z&Warning in cma.CMAOptions.init(): key z ignored)r   itemsr   r   r   printr   )r   dict_or_strvalwarndicr   s         r\   initzCMAOptions.init  s    " 	

;?s#C		HC$$S)C*--//BC!#-. /  S	 $ r^   c                 (   |||i}t        t        |      j                               D ]f  \  }}| j                  |      }| j                  r|t
        j                         v s|r|| |<   At        j                  dt        |      z   dz   dd       h | S )ad  assign versatile options.

        Method `CMAOptions.versatile_options` () gives the versatile
        options, use `init()` to set the others.

        Arguments
        ---------
            `dic`
                either a dictionary or a key. In the latter
                case, `val` must be provided
            `val`
                value for `key`, approximate match is sufficient
            `force`
                force setting of non-versatile options, use with caution

        This method will be most probably used with the ``opts`` attribute of
        a `CMAEvolutionStrategy` instance.

        zkey z& ignored (not recognized as versatile)setr   )
r   r   r   r   r   r   r   r   r   r   )r   r   r   forcekey_originalr   s         r\   r   zCMAOptions.set  s    ( ?s)C!%d3ioo&7!8L#$$\2C&&z3355S	##FS->$>>%?$l4 "9 r^   c                     | j                          t        j                         D ]!  }|| vst        j                         |   | |<   # | S )z1add all missing options with their default values)r   r   r   )r   r   s     r\   
complementzCMAOptions.complement  sE     	

&&(C$&//1#6S	 ) r^   c           	      f    t        t        d t        | j                               D                    S )zreturn the subset of those options that are settable at any
        time.

        Settable options are in `versatile_options` (), but the
        list might be incomplete.

        c              3   R   K   | ]  }|d    t         j                         v r| ! ywr   N)r   r   )ra   is     r\   rd   z&CMAOptions.settable.<locals>.<genexpr>  s.      K*<Q#$Q4:+G+G+I#I  !*<s   %')r   r   r   r   r   s    r\   settablezCMAOptions.settable  s4     $ K$tzz|*< K K L 	Lr^   c                    t        t                     }|j                  t               	 | |   }|| }	 t        j                  |      r|j                  d      d   j                         }|dk(  r	 t        t        |      ||      }|S |j                  d      dk  rI|dk(  r|j                  d      s3t        t        |      ||      }	 |S ||t        t        |      ||      }|S # t        $ r | j                  |      cY S w xY w# t        $ r Y |S w xY w# t        $ rC}t        |      j                  d      st!        j"                  t        |             Y d}~|S d}~ww xY w)	a  evaluate and return the value of option `key` on the fly, or
        return those options whose name or description contains `key`,
        case disregarded.

        Details
        -------
        Keys that contain `filename` are not evaluated.
        For ``loc==None``, `self` is used as environment
        but this does not define ``N``.

        :See: `eval()`, `evalall()`

        Nr   r   r   filenamerA   r   z	"initial")r   globalsupdateoptions_environment	Exceptionr   r   r   r   stripevalr   r{   r`   r   r   	_warningsr   )r   r   defaultloc
global_envr   es          r\   __call__zCMAOptions.__call__  sc    ')_
-.	#s)C ;C	||C iinQ'--/++"8C=*cB  
 XXj)A-v#..*@x}j#>C 
 !48G,j#>
 
5  	#::c?"	# &  
  	q6$$[1s1v&
		sS   C( <D 1D 	A D D (DD	DD DD 	E$!8EE$c                    |j                  d      r|S g }|j                         }|t        v r	t        |   S t        D ]5  }|j                  |      st        |      dkD  r y|j	                  |       7 t        |      dk(  r|d   S dS )zreturn the matching valid key, if ``key.lower()`` is a unique
        starting sequence to identify the valid key, ``else None``

        _r   Nr   )r   rg   cma_allowed_options_keysr   r   )r   r   matching_keysallowed_keys       r\   r   zCMAOptions.corrected_keyF  s    
 >>#Jiik**+C003K%%c*}%)$$[1	 4
 $'}#5#:}QDDr^   c                 L    |r| j                  |      } | |||      | |<   | |   S )ab  Evaluates and sets the specified option value in
        environment `loc`. Many options need ``N`` to be defined in
        `loc`, some need `popsize`.

        Details
        -------
        Keys that contain 'filename' are not evaluated.
        For `loc` is None, the self-dict is used as environment

        :See: `evalall()`, `__call__`

        )r   )r   r   r   r   r   s        r\   r   zCMAOptions.evalX  s3     $$S)Cgs+S	Cyr^   c                 (   | j                          |
t               }d|v rj | d|d   |      }t        | j                               D ]A  }| j	                  |      }|j                  d      r&| j                  |||   |d   |d       C d| _        | S )zSEvaluates all option values in environment `loc`.

        :See: `eval()`

        rs   r=   r   rs   r=   T)r   r]   r   r   r   r   r   r   )r   r   r   r=   rb   s        r\   evalallzCMAOptions.evalalll  s     	

+-H#:9hy&93?G$))+&&&q)<<$		!Xa["3x7;=	 ' "r^   c                     |j                         }i }t        |       D ]=  }t        |      dz   t        | |         z   dz   }||j                         v s6| |   ||<   ? t        |      S )zreturn all options that match, in the name or the description,
        with string `s`, case is disregarded.

        Example: ``cma.CMAOptions().match('verb')`` returns the verbosity
        options.

        ='')rg   sortedr   r   )r   rh   r   resrb   s        r\   r   zCMAOptions.match  sh     	AAT!W-4A	!aA  #r^   c           	      8   	 t        | d         | d<   | d   r| j                  |       | d   syt        | d         |kD  r't	        dj                  |t        | d                     | d   r&t        | d         dk(  r| d   d   dg| d<   d| d   d<   |j                  dd      dt        d   fv rCd	d
t        j                  |      t        j                  t        | d         dz         z   z  z   | d<   |j                  dd      dt        d   fv rd
dt        | d         |z  z  z   | d<   t        | d         |k(  rF|j                  dd      dt        d   fv rd| d<   |j                  dd      dt        d   fv rd| d<   yyy# t        $ r | d   r g | d<   Y w xY w)z;amend options when integer variables are indicated
        r3   NzP{0} = dimension < len(options['integer_variables']) = {1} is not a valid settingr/   r   r   r=      r           rH      rI   rJ   )
r   r   amend_integer_variablesr   r{   r|   getr   rm   log)r   	dimensioninoptss      r\   amend_integer_optionsz CMAOptions.amend_integer_options  s   	+(,T2E-F(GD$% #$((3'(t'()I5 7$fYD9L4M0NOQ Q ()4012a7267O2PQR2SUV1W-.12D)*2.::i&41DY1O*PP!txx	':'+xxD9L4M0NQT0T'U(V #W WDO ::&--.>?2A A%&D,-.:*< &<D!"t'()Y6zz(D)d4G4Q-RR!"Xzz,-$8KL8Y1ZZ%&\" [ 7O  	+'((*D$%	+s   F FFc                    | d   syg }t        | d         | d<   t        t        |            D ]  }|| d   v s| d   j                  |       | d   j                  |       ddk  r2|j	                  |       || d   v rt        dj                  |            t        | d         D ]  \  }}||kD  s| d   |xx   dz  cc<     | d   d	k\  r%t        j                  d
j                  |             yy)zremove fixed variables from the integer variable index list

        and change the index values accordingly to refer to a genotype.
        Create an `'_pheno_integer_variables'` entry of the same length but
        with the unchanged index values.
    r1   Nr3   _pheno_integer_variablesr   r   zAindex {0} appeared more than once in `'integer_variables'` optionrR   r   zHandling integer variables when some variables are fixed.
  This code is poorly tested and may fail for negative indices.
  Variables {0} are fixed integer variables but are now dropped and discarded for integer handling.)
r   reversedrangeremover   r{   r|   	enumerater   r   )r   r  poppedr   jidxs         r\   r  z"CMAOptions.amend_integer_variables  s    %& +/5H0I+J'(%	*+AD*++()003/077:q5MM!$D!455()l)s)stu)vww'-@(ABFAsQw01!494 C , 	?aNN K  	)  r^   c           	         | d   syt        j                  | d         r&| d   dk(  r| d   t        j                  |      z  | d<   t        j                  | d         s| d   D ]}  }| |cxk  r|k  r/n n,| d   |   dk(  st        ||t	        | d               | d   |<   >t        j                  d||fz         | d   j                  | d   j                  |              yy)zset lower std bounds for integer variables.

        Uses the above defined `integer_std_lower_bound` function which can
        be reassigned.
        r3   Nr9   r   z?dropping integer index %d as it is not in range of dimension %d)	r   isscalaronesry   r   r   r   r   r   )r   rs   rt   r   s       r\   set_integer_min_stdzCMAOptions.set_integer_min_std  s     '(;;tH~&4>Q+>!(^bggaj8DN {{4>*-.2;Q;H~a(A-,C !5#d3F.G*H-JXq) ''Y !f%& ,-11$7J2K2Q2QRS2TU / +r^   c                     t         )z_return options as const attributes of the returned object,
        only useful for inspection. )NotImplementedErrorr   s    r\   to_namedtuplezCMAOptions.to_namedtuple  s
     "!r^   c                 @    | j                  |j                               S )z[update options from a `collections.namedtuple`.
        :See also: `to_namedtuple`
        )r   _asdict)r   ts     r\   from_namedtuplezCMAOptions.from_namedtuple  s     {{199;''r^   c                 ~   t        | j                               D ]  }t        |d         dz   t        |d         z   dz   }|j                  d      }d}|s<|rTt	        |      t	        |d         z   |k  r7|d|j                  d      z   z  }|rt	        |      t	        |d         z   |k  r7t        |       d}|rf y )Nr   r   r   r    r   z        )r   r   r   r   r   r   r   )r   	linebreakr   rh   alines         r\   pprintzCMAOptions.pprint  s    

%AAaD	D 3qt9,s2AA DCIAaD	1I=C!%%(N*D CIAaD	1I=d!	  &r^   rf   )NTNF)NN)NNT)r   )P   )__name__
__module____qualname____doc__
_ps_for_pc_hsig_stationary_spherestaticmethodr   r   r   r   r   r   r   r   r   propertyr   r   r   r   r   r   r  r  r  r  r  r   __classcell__)r   s   @r\   r   r      s    2f JE # # % %,+Z1@f D D 	L 	L-^E$(* 0'd)@V4 " "("r^   r   c                   &    e Zd ZdZddZddZd Zy)CMAParametersaM  strategy parameters like population size and learning rates.

    Note:
        contrary to `CMAOptions`, `CMAParameters` is not (yet) part of the
        "user-interface" and subject to future changes (it might become
        a `collections.namedtuple`)

    Example
    -------
    >>> import cma
    >>> es = cma.CMAEvolutionStrategy(20 * [0.1], 1)  #doctest: +ELLIPSIS
    (6_w,12)-aCMA-ES (mu_w=3.7,w_1=40%) in dimension 20 (seed=...)
    >>>
    >>> type(es.sp)  # sp contains the strategy parameters
    <class 'cma.options_parameters.CMAParameters'>
    >>> es.sp.disp()  #doctest: +ELLIPSIS
    {'CMA_on': True,
     'N': 20,
     'c1': 0.00437235...,
     'c1_sep': ...0.0343279...,
     'cc': 0.171767...,
     'cc_sep': 0.252594...,
     'cmean': 1.0,
     'cmu': 0.00921656...,
     'cmu_sep': ...0.0565385...,
     'lam_mirr': 0,
     'mu': 6,
     'popsize': 12,
     'weights': [0.4024029428...,
                 0.2533890840...,
                 0.1662215645...,
                 0.1043752252...,
                 0.05640347757...,
                 0.01720770576...,
                 -0.05018713636...,
                 -0.1406167894...,
                 -0.2203813963...,
                 -0.2917332686...,
                 -0.3562788884...,
                 -0.4152044225...]}
    >>>

    :See: `CMAOptions`, `CMAEvolutionStrategy`

    c                 ^    || _         |dk(  r|d   }d| _        	 | j                  |||       y)zCompute strategy parameters, mainly depending on
        dimension and population size, by calling `set`.

        When ``ccovfac == 1``, we use ``ccovfac=opts['CMA_on']``.
        r   r   N)ccovfacrR   )rs   r=   r   )r   rs   r   r0  rR   s        r\   r   zCMAParameters.__init__H  s7     a<8nGPw8r^   Nc                    d}d }d }| }|j                   }	|r|j                  |	|d       n|j                  d|	i      d   }||d   z  }t        ||	dz  z   d	z
        }t        j                  |d
         r)t        |d
         |_        t        |j                        }n|d   rxt        d|d   z        |_        t        |j                        |k  rZ|j                  j                  |j                  j                  d       t        |j                        |k  rInt        |      |_        ||_
        |j                  j                  |_	        |d   dk  rt        d|d   |z  z         |_        nI|d   d	kD  rt        d|d   z         |_        n*t        ddt        |d|	z  dz   f      z  z   dz         |_        |j                  dz  |j                  d|j                  z  z
  d	z   kD  r]t        j                  dd|j                  dz  |j                  d|j                  z  z
  d	z   |j                  |j                  fz  z          |j                  |j                  dz  kD  rt        d      |j                  j                  }
d}d||
|	z  z   |z  z  |	|z  |d|
z  |	z  z   |z  z   z  |_        d	d	|	z  z   |
|	z  z   |	dz  d	|	z  z   d|
z  |	z  z   z  |_        t%        |d   d      rld|d   v r(dd|
|	z  z   dz  z  |	dz   dz  d|
z  |	z  dz  z   z  |_        d|d   v r6|d   d   |_        |j                   |_        t'        d|j                   z         d|d   z  |z  t        d	|j                  dz        z  dz  |	dz   dz  |
z   z  |_        t+        |d   |z   ||	|
|	      z        |_        dd k  rd|_        t'        d!       t        j                  |d"         rd}d#}t%        |d   d      rd$|d   v r|d   d$   }t'        d%|z         |
}t        d	|j(                  z
  |d"   |z  |z  ||z   d	|z  z   dz
  z  |	dz   dz  ||z  dz  z   z        |_        t%        |d   d      rd&|d   v r|d   d&   |_        t+        t        d	|j,                  z
  | ||	|
|      z              |_        nd'x|_        |_        t%        |d   d      rd|d   v r|d   d   |_        t3        d( |j                  D              r[|d)   r<|d*   r7|d"   r2|j                  j5                  |	|j(                  |j.                         n|j                  j7                          |j(                  |j.                  z   d'kD  |_        |d*   s|d*   d+g d,d-fvrd.|_        dd k  rAd/dt;        |
|j                  z  |
d	z
  |	d	z   z  dz  d	z
  g      z  z   |j<                  z   |_        dd k  r`|d0   dd'|j                  z  |j                  z  z
  z  |
z  |j                  z  d/z   |j<                  z   |_        t'        d1|j>                         dd k  r,d2|j>                  z  |_        t'        d3|j>                  z         t+        |d4         |_         dd k  rCtC        j2                  |j@                  d	k7        r!t'        d5tE        |j@                        z          |r@|j8                  st'        d6       |d   #t'        d7|j                  j                  z         y+y+y+)8zSCompute strategy parameters as a function
        of dimension and population size g      @c                 N    dt        | d| dz  z  z   t        |      |z  z         z  S )*used for computing separable learning rate      ?       @rk   float)dfmurs   s      r\   conedfz!CMAParameters.set.<locals>.conedf[  s,    b2C</%)a-?@@@r^   c                 T    t        ||z   d|z  z   dz
  | d| dz  z  z   |dz  z   z        S )r3  r4  rj      rk   r5  r6  )r8  r9  alphamus      r\   cmudfz CMAParameters.set.<locals>.cmudf_  s;    'B,b014a"c'k9IBQSG9STUUr^   r   rs   r=   r>   r   r   r    r   rj   r   rk   g{Gz?g(\?z1pairwise selection is not implemented, therefore zG mu = %d > %d = %d - 2*%d + 1 = popsize - 2*mirr + 1 can produce a biaszzfraction of mirrors in the population as read from option CMA_mirrors cannot be larger 0.5, theoretically optimal is 0.159r4  r[   __getitem__sweep_ccov1r<  sweep_cczcc is %fr   r   g?r5  r   r   z
c1 is zeror   g      ?sweep_rankmu_offsetzrankmu_offset = %.2f
sweep_ccovr   c              3   &   K   | ]	  }|d k    ywr   r   )ra   ws     r\   rd   z$CMAParameters.set.<locals>.<genexpr>  s     )jq1ujs   r   r   Nr   r   Fg333333?r%   zdamps =
   zdamps is %fr   z
  cmean = z'covariance matrix adaptation turned offzmu = %d)#rs   r   r   r   is_r	   weightsr   insertr9  r=   lam_mirrro   r   r{   rt   cccc_sepr   r   c1r7  c1_sepcmucmu_sepanyfinalize_negative_weightszero_negative_weightsr   maxcsdampscmeanr   r   )r   r   r=   r0  rR   limit_fac_ccr:  r>  sprs   rt   balphacovrankmu_offsetr9  s                  r\   r   zCMAParameters.setU  s#    	A	V DDLLa734llC7+I6Gt,--GgC'!+, 99T567-d3N.OPBJ"**oG(^-a$x..@ABJbjj/G+

!!"**--5 bjj/G+ .g6BJ


$cD$7'$AABBK- 1$cD$778BKcD3Q/C+D$DDtKLBK ::?RZZ!bkk/9A== S[JJ!ORZZ!bkk/%AA%ErzzSUS^S^_` `!` a ;;q( : ; ; 

   |eai/!33AE	A599;QY*Va!e^a%i!m35	4:}-T
*q519}s22q1usl56Y]S4H7I JT$Z'T
:.EE	j255() tM**W4s1bjj1n7MM3w#o-/ $}-7&E1:MMN	6BE,99T,'(H M tDz=16KtTXz6Y $T
+@ A,}<=BRUUl+g5@'",q2v59; q5C-(R-!*;;	=>BF tDz=1ld4j6PdL1s1ryy='E!UM<Z2Z[\BJ"##BFRZ4:}--4:2MJ}-BE)bjj))L!d8nl9K

44QrvvF 

002 EEBFFNQ&	 H~$x.r2r8J"JBI 6Qebjj&8EAI!a%;PSV:VYZ:Z%[!\\\_a_d_ddBH6M*a!bkk/BJJ2N.NORWWZ\ZdZddgjjmomrmrrBH)RXX&6BHH}BH-288,-k*+ 6bffRXX]+,RXX./99?@H~)i2::==12 * r^   c                 B    t        j                  | j                         y rf   )r   r   r   r   s    r\   dispzCMAParameters.disp  s    T]]#r^   )r   T)Nr   T)r#  r$  r%  r&  r   r   r^  r   r^   r\   r.  r.    s    ,Z9^3D$r^   r.  c                       e Zd ZdZd Zy)MetaParametersaT  collection of many meta parameters.

    Meta parameters are either annotated constants or refer to
    options from `CMAOptions` or are arguments to `fmin` or to the
    `NoiseHandler` class constructor.

    `MetaParameters` take only effect if the source code is modified by
    a meta parameter weaver module searching for ## meta_parameters....
    and modifying the next line.

    Details
    -------
    This code contains a single class instance `meta_parameters`

    Some interfaces rely on parameters being either `int` or
    `float` only. More sophisticated choices are implemented via
    ``choice_value = {1: 'this', 2: 'or that'}[int_param_value]`` here.

    CAVEAT
    ------
    `meta_parameters` should not be used to determine default
    arguments, because these are assigned only once and for all during
    module import.

    c                 z   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| _*        d| _+        d| _,        y)zassign settings to be usedNr4  r5  g?g      ?r   r   rk   r   g      пg     @@g@xDgdy=g-q=)-sigma0r   c1_multipliercmu_multiplierr   cc_multipliercs_multiplierr%   r!   r"   c1_exponentcmu_exponentcact_exponentcc_exponentcs_exponentlambda_exponentr   r   r7   r<   r&   r'   r)   r(   noise_reeval_multipliernoise_choose_reevalnoise_thetanoise_alphasigmanoise_alphaevalsnoise_alphaevalsdown_exponentnoise_aggregater   restart_from_best
incpopsizemaxiter_multiplierr8   r9   r:   rF   rG   rN   rI   rK   rJ   tolstagnation_multiplierr   s    r\   r   zMetaParameters.__init__  sl     !   $!$    # ()$  (+$$%!%)" (+$#$  # #-2*# !" #&
	(+%r^   N)r#  r$  r%  r&  r   r   r^   r\   r`  r`    s    2@,r^   r`  r!  ))r&  rm   r   warningsr   numpyr   r   r   r   r   loggerr   recombination_weightsr	   rq   rr   rp   integer_active_limit_std3integer_active_limit_recombination_weight_conditionr   default_prefixr]   r   tupler   r   r   r   r   ry   rl   r   r4   r   getattrr   r   objectr.  r`  )names   0r\   <module>r     sd          ! 7"#  K"# 7 #   Q6: 3 Q%& " iM\5c;X]b&u?PI>X_XZu{U~~haY EDOJ1_gk p[j: ]w>S_
UjPfJz`
| o
H8bxhA-TWUKuQ 
Ci Vp`[SI%447ffA?L2`Sqf +, f %<5H5N5N5P %< < = L8KLL ""1>8	
	 /3D'"D
))	
 
i" i"V !!5!78 ^$F ^$BZ,V Z,g
s   /D2