
    J-jC                        d Z ddlmZmZmZ ddlZddlZddlZ[[[dddddd	d
dddddddddddej                  j                  dd      ej                  j                  dd      ej                  j                  dd      gZ
g dZ	 d Zd Ze
fdZd Zd  Zed!k(  r	  e eej&                  d"d  dkD         yy# e$ r  eej&                  d"d   Y yw xY w)#a}  test module of `cma` package.

Usage::

    python -m cma.test -h    # print this docstring
    python -m cma.test       # doctest all (listed) files
    python -m cma.test list  # list files to be doctested
    python -m cma.test interfaces.py [file2 [file3 [...]]] # doctest only these

or possibly by executing this file as a script::

    python cma/test.py  # same options as above work

or equivalently by passing Python code::

    python -c "import cma.test; cma.test.main()"  # doctest all (listed) files
    python -c "import cma.test; cma.test.main('list')"  # show files in doctest list
    python -c "import cma.test; cma.test.main('interfaces.py [file2 [file3 [...]]]')"
    python -c "import cma.test; help(cma.test)"  # print this docstring

File(name)s are interpreted within the package. Without a filename
argument, all files from attribute `files_for_doc_test` are tested.
    )absolute_importdivisionprint_functionNzbbobbenchmarks.pyzboundary_handler.pyzconstraints_handler.pyzevolution_strategy.pyzfitness_functions.pyzfitness_models.pyzfitness_transformations.pyzinteger_centering.pyzinterfaces.pyz	logger.pyzoptimization_tools.pyzoptions_parameters.pyzrecombination_weights.pyzrestricted_gaussian_sampler.pyz
sampler.pyzsigma_adaptation.pyztest.pyztransformations.pymore_algorithmsz
purecma.py	utilitieszmath.pyzutils.py)z_saved-cma-object.pklzoutcmaesaxlen.datzoutcmaesaxlencorr.datzoutcmaesfit.datzoutcmaesstddev.datzoutcmaesxmean.datzoutcmaesxrecentbest.datc                 b   t         j                  j                  |       sy|sd|v rt        d      |dgz   }t        j                  |       D ]_  t        fd|D              st        fd|D              r-t        j                  t         j                  j                  |              a y)a#  (permanently) remove entries in ``folder`` which begin with any of
    ``start_matches``, where ``""`` matches any string, and which are not
    in ``protected``.

    CAVEAT: use with care, as with ``"", ""`` as second and third
    arguments this could delete all files in ``folder``.
    N z\_clean_up(folder, [..., "", ...], []) is not permitted as it
               resembles "rm *"/c              3   @   K   | ]  }j                  |        y wN
startswith).0sfile_s     V/Users/jameslopez/projects/TradingBot25/.venv/lib/python3.12/site-packages/cma/test.py	<genexpr>z_clean_up.<locals>.<genexpr>V   s     :Mqu"M   c              3   @   K   | ]  }j                  |        y wr   r   )r   pr   s     r   r   z_clean_up.<locals>.<genexpr>W   s     CAE,,Q/r   )ospathisdir
ValueErrorlistdiranyremovejoin)folderstart_matches	protectedr   s      @r   	_clean_upr"   F   s     77== },#$ 	$ SE!IF#:M::CCCIIbggll6512 $    c                       y)aL*  various doc tests.

    This function describes test cases and might in future become
    helpful as an experimental tutorial as well. The main testing feature
    at the moment is by doctest with ``cma.test.main()`` in a Python shell
    or by ``python -m cma.test`` in a system shell.

    A simple first overall test:

    >>> import cma
    >>> res = cma.fmin(cma.ff.elli, 3*[1], 1,
    ...                {'CMA_diagonal':2, 'seed':1, 'verbose':-9})
    >>> assert res[1] < 1e-6
    >>> assert res[2] < 2000

    Testing `args` argument:

    >>> def maxcorr(m):
    ...     val = 0
    ...     for i in range(len(m)):
    ...         for j in range(i + 1, len(m)):
    ...             val = max((val, abs(m[i, j])))
    ...     return val
    >>> x, es = cma.fmin2(cma.ff.elli, [1, 0, 0, 0], 0.5, {'verbose':-9}, args=[True])  # rotated
    >>> assert maxcorr(es.sm.correlation_matrix) > 0.85, es.sm.correlation_matrix
    >>> es = cma.CMAEvolutionStrategy([1, 0, 0, 0], 0.5,
    ...                               {'verbose':-9}).optimize(cma.ff.elli, args=[1])
    >>> assert maxcorr(es.sm.correlation_matrix) > 0.85, es.sm.correlation_matrix

    Testing output file consistency with diagonal option:

    >>> import cma
    >>> for val in (0, True, 2, 3):
    ...     _ = cma.fmin(cma.ff.sphere, 3 * [1], 1,
    ...                  {'verb_disp':0, 'CMA_diagonal':val, 'maxiter':5})
    ...     _ = cma.CMADataLogger().load()

    Test on the Rosenbrock function with 3 restarts. The first trial only
    finds the local optimum, which happens in about 20% of the cases.

        >>> import cma
        >>> res = cma.fmin(cma.ff.rosen, 4 * [-1], 0.01,
        ...                options={'ftarget':1e-6,
        ...                     'verb_time':0, 'verb_disp':500,
        ...                     'seed':3},
        ...                restarts=3)
        ...                # doctest: +ELLIPSIS
        (4_w,8)-aCMA-ES (mu_w=2.6,w_1=52%) in dimension 4 (seed=3,...)
        Iterat #Fevals ...
        >>> assert res[1] <= 1e-6

    Notice the different termination conditions. Termination on the target
    function value ftarget prevents further restarts.

    Test of scaling_of_variables option

        >>> import cma
        >>> opts = cma.CMAOptions()
        >>> opts['seed'] = 4567
        >>> opts['verb_disp'] = 0
        >>> opts['CMA_const_trace'] = True
        >>> # rescaling of third variable: for searching in  roughly
        >>> #   x0 plus/minus 1e3*sigma0 (instead of plus/minus sigma0)
        >>> opts['scaling_of_variables'] = [1, 1, 1e3, 1]
        >>> res = cma.fmin(cma.ff.rosen, 4 * [0.1], 0.1, opts)
        >>> assert res[1] < 1e-9
        >>> es = res[-2]
        >>> es.result_pretty()  # doctest: +ELLIPSIS
        termination on {'tolfun': 1e-11}
        final/bestever f-value = ...

    The printed std deviations reflect the actual value in the
    parameters of the function (not the one in the internal
    representation which can be different).

    Test of CMA_stds scaling option.

        >>> import cma
        >>> opts = cma.CMAOptions()
        >>> s = 5 * [1]
        >>> s[0] = 1e3
        >>> opts.set('CMA_stds', s)  #doctest: +ELLIPSIS
        {'...
        >>> opts.set('verb_disp', 0)  #doctest: +ELLIPSIS
        {'...
        >>> res = cma.fmin(cma.ff.cigar, 5 * [0.1], 0.1, opts)
        >>> assert res[1] < 1800

    Testing combination of ``fixed_variables`` and ``CMA_stds`` options.

        >>> import cma
        >>> options = {
        ...     'fixed_variables':{1:2.345},
        ...     'CMA_stds': 4 * [1],
        ...     'minstd': 3 * [1]}
        >>> es = cma.CMAEvolutionStrategy(4 * [1], 1, options) #doctest: +ELLIPSIS
        (3_w,7)-aCMA-ES (mu_w=2.3,w_1=58%) in dimension 3 (seed=...

    Test of elitism:

        >>> import cma
        >>> res = cma.fmin(cma.ff.rastrigin, 10 * [0.1], 2,
        ...       {'CMA_elitist':'initial', 'ftarget':1e-3, 'verbose':-9})
        >>> assert 'ftarget' in res[7]

    Test CMA_on option and similar:

        >>> import cma
        >>> res = cma.fmin(cma.ff.sphere, 4 * [1], 2,
        ...      {'CMA_on':False, 'ftarget':1e-8, 'verbose':-9})
        >>> assert 'ftarget' in res[7] and res[2] < 1e3
        >>> res = cma.fmin(cma.ff.sphere, 3 * [1], 2,
        ...      {'CMA_rankone':0, 'CMA_rankmu':0, 'ftarget':1e-8,
        ...       'verbose':-9})
        >>> assert 'ftarget' in res[7] and res[2] < 1e3
        >>> res = cma.fmin(cma.ff.sphere, 2 * [1], 2,
        ...      {'CMA_rankone':0, 'ftarget':1e-8, 'verbose':-9})
        >>> assert 'ftarget' in res[7] and res[2] < 1e3
        >>> res = cma.fmin(cma.ff.sphere, 2 * [1], 2,
        ...      {'CMA_rankmu':0, 'ftarget':1e-8, 'verbose':-9})
        >>> assert 'ftarget' in res[7] and res[2] < 1e3

    Check rotational invariance:

        >>> import cma
        >>> felli = cma.s.ft.Shifted(cma.ff.elli)
        >>> frot = cma.s.ft.Rotated(felli)
        >>> res_elli = cma.CMAEvolutionStrategy(3 * [1], 1,
        ...           {'ftarget': 1e-8}).optimize(felli).result
        ...                  #doctest: +ELLIPSIS
        (3_w,7)-...
        >>> res_rot = cma.CMAEvolutionStrategy(3 * [1], 1,
        ...         {'ftarget': 1e-8}).optimize(frot).result
        ...                  #doctest: +ELLIPSIS
        (3_w,7)-...
        >>> assert res_rot[3] < 2 * res_elli[3]

    Both condition alleviation transformations are applied during this
    test, first in iteration 62ish, second in iteration 257ish:

    >>> import warnings
    >>> import cma
    >>> ftabletrot = cma.fitness_transformations.Rotated(cma.ff.tablet, seed=10)
    >>> es = cma.CMAEvolutionStrategy(4 * [1], 1, {
    ...                                   'tolconditioncov':False,
    ...                                   'seed': 8,
    ...                                   'CMA_mirrors': 0,
    ...                                   'CMA_diagonal_decoding': 0,
    ...                                   'ftarget': 1e-8,
    ...                                })  # doctest:+ELLIPSIS
    (4_w...
    >>> while not es.stop() and es.countiter < 90:
    ...     X = es.ask()
    ...     es.tell(X, [cma.ff.elli(x, cond=1e22) for x in X])  # doctest:+ELLIPSIS
    NOTE ...iteration=...
    >>> with warnings.catch_warnings(record=True) as warns:
    ...     while not es.stop():
    ...         X = es.ask()
    ...         es.tell(X, [ftabletrot(x) for x in X])  # doctest:+ELLIPSIS
    >>> assert not warns or isinstance(warns[0].message, UserWarning)
    >>> assert es.countiter <= 355 and 'ftarget' in es.stop(), (
    ...             "transformation bug in alleviate_condition?",
    ...             es.countiter, es.stop())

    Integer handling:

    >>> x, es = cma.fmin2(cma.ff.rosen, 2 * [-10], 1,
    ...                   {'integer_variables': [0, 1], 'verbose': -9})
    >>> idx = [0, 1, -1]
    >>> f = cma.s.ft.IntegerMixedFunction2(cma.ff.elli, idx)
    >>> for i, more_opts in enumerate(2 * [{}] +
    ...                               2 * [{'AdaptSigma': cma.sigma_adaptation.CMAAdaptSigmaTPA}]):
    ...     cma.evolution_strategy.round_integer_variables = i % 2
    ...     opts = dict(ftarget=1e-9, seed=5, verbose=-9, integer_variables=idx)
    ...     opts.update(more_opts)
    ...     es = cma.CMAEvolutionStrategy(4 * [5], 10, opts).optimize(f)
    ...     assert 'ftarget' in es.stop() and es.result[3] < 1800
    >>> # mixing integer and fixed variables
    >>> with warnings.catch_warnings():
    ...     warnings.simplefilter("ignore", category=UserWarning)
    ...     es = cma.CMA(5 * [1], 1, {'verbose':-9, 'integer_variables':[1,2,4],
    ...                               'fixed_variables':{1:0}})
    >>> assert es.opts['integer_variables'] == [1, 3], es.opts['integer_variables']
    >>> assert es.opts['_pheno_integer_variables'] == [2, 4], es.opts['_pheno_integer_variables']
    >>> # TODO: do more testing here or in the class

    >>> es = cma.CMA(3 * [-1], 2.21, {'integer_variables': [0, 2], 'verbose':-9})
    >>> s = es.ask()[:-1] + 2 * [[1, 2.2, 2]]  # nonconsumed and more solutions warnings
    >>> s[0][0] += 234  # warn that solution changed
    >>> with warnings.catch_warnings(record=True) as warns:
    ...     warnings.simplefilter("always")
    ...     es.tell(s, list(range(len(s))))
    ...     # [print(str(w.message)) for w in warns]
    ...     assert len(warns) == 3, [str(w.message) for w in warns]
    ...     assert 'solutions passed to' in str(warns[0].message), warns[0].message
    ...     assert 'solution with index 0' in str(warns[1].message), warns[1].message
    ...     assert '234' in str(warns[1].message), warns[1].message
    ...     assert '1 solution(s) of' in str(warns[2].message), warns[2].message

    Parallel objective:

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

    Some sort of interactive control via an options file:

    >>> es = cma.CMAEvolutionStrategy(4 * [2], 1, dict(
    ...                      signals_filename='cma_signals.in',
    ...                      verbose=-9))
    >>> s = es.stop()
    >>> es = es.optimize(cma.ff.sphere)

    Test of huge lambda:

    >>> es = cma.CMAEvolutionStrategy(3 * [0.91], 1, {
    ...     'verbose': -9,
    ...     'popsize': 200,
    ...     'ftarget': 1e-8 })
    >>> es = es.optimize(cma.ff.tablet)
    >>> if es.result.evaluations > 5000: print(es.result.evalutions, es.result)

    For VD- and VkD-CMA, see `cma.restricted_gaussian_sampler`.

    >>> import sys
    >>> import cma
    >>> assert cma.interfaces.EvalParallel2 is not None
    >>> try:
    ...     with warnings.catch_warnings(record=True) as warn:
    ...         with cma.optimization_tools.EvalParallel2(cma.ff.elli) as eval_all:
    ...             res = eval_all([[1,2], [3,4]])
    ... except:
    ...     assert sys.version_info[0] == 2

    Constraints:

    >>> import numpy as np
    >>> x, es = cma.fmin_con2(cma.ff.sphere, 3 * [1], 1,
    ...                       lambda x: [x[0] + 0.1],
    ...                       options={'verbose': -9})
    >>> assert np.all(es.result.xfavorite < 1e-6), es.result.xfavorite
    >>> assert np.all(es.result.xfavorite[1:] > -1e-6), es.result.xfavorite
    >>> assert np.all(es.result.xfavorite[0] < -0.1 + 1e-4), es.result.xfavorite
    >>> assert np.all(es.result.xfavorite[0] > -0.1 - 1e-4), es.result.xfavorite

    N r%   r#   r   various_doctestsr&   Z   s    r#   c           	         t        | t              st        | d      r| g} |j                  dd      }|dk  rd|d<   d}| D ]  }|j	                         j	                  t
        j                  j                        }|j                  dt
        j                  j                  z         r|dd }|dk\  rNt        d|z  dt        d	 | D              t        |      z
  z  d
       t        j                  j                          t        j                  d      }t!        j"                  |fdt$        i|}t'        dt(        |       ||d   z  }|dk\  st        |        |S )zdoctest all (listed) files of the `cma` package.

    Details: accepts ``verbose`` and all other keyword arguments that
    `doctest.testfile` would accept, while negative ``verbose`` values
    are passed as 0.
    r   verboser   cma   Nzdoctesting %s ... c              3   2   K   | ]  }t        |        y wr   )len)r   _files     r   r   z doctest_files.<locals>.<genexpr>m  s     ?YESZYs   r	   )end.package)
isinstancelisthasattrgetstripr   r   sepr   printmaxr-   sysstdoutflushr   doctesttestfile__package__r"   _files_written)	file_listkwargsverbosity_herefailuresr   protected_filesreports          r   doctest_filesrG   X  sB    i&79l+KK	ZZ	1-NyH##BGGKK0EBGGKK/0!"IEQ%-?Y??U$ % JJ**S/!!% ,*5,$*, 	#~7F1IQ&M# $ Or#   c                      	 t        t        d d dz   d      5 } | j                         D ]4  }|j                  d      s|dd  j	                         d   c cd d d        S  	 d d d        y # 1 sw Y   y xY w#  Y yxY w)Niz__init__.pyr__version__   r   r	   )open__file__	readlinesr   splitr8   )flines     r   get_versionrR   {  sm    (3B--/5??=19??,Q// 65% 655s9   A6 %A*A*	A6 A*!A6 *A3/A6 3A6 6A:c                  N   t        |       dkD  re| d   j                  d      rt        t               t	        d       nU| d   j                  d      rAt
        D ]  }t        |        t	        d       nt               }t        d|rd|z  ndz         t        | r| nt
        fi |S )a  test the `cma` package.

    The first argument can be '-h' or '--help' or 'list' to list all
    files to be tested. Otherwise, arguments can be file(name)s to be
    tested, where names are interpreted relative to the package root
    and a leading 'cma' + path separator is ignored.

    By default all files are tested.

    :See also: ``python -c "import cma.test; help(cma.test)"``
    r   )z-hz--hr3   z6doctesting `cma` package%s by calling `doctest_files`:z (v%s)r	   )r-   r   r8   __doc__exitfiles_for_doctestrR   rG   )argsrB   r   vs       r   mainrY     s     4y1}7m,'NG!W'*e +GMF#$(Q,". 	/+<GGGr#   __main__   )rT   
__future__r   r   r   r   r:   r=   r   r   rV   r@   r"   r&   rG   rR   rY   __name__rU   argv	NameErrorr%   r#   r   <module>r`      s  <   X~(*-,+(1+$ ,,/5!*)WW\\"3LAWW\\+y9WW\\+z:) , G3(|| . !F	H4 zT388AB< 1$%   chhqrls   B: :CC