o
    }oii                     @  s  d dl mZ d dlmZ d dl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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 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" d dl#m$Z$ d dl%m&Z& d dl'm(Z( d dl'm)Z) e
rd dl*Z*ee*j+e*j,e*j-f Z.nedZ*e/e0Z1dZ2dZ3G dd deZ4d%d#d$Z5dS )&    )annotations)SequenceN)Any)cast)TYPE_CHECKING)Union)_deprecated)logging)warn_experimental_argument)_LazyImport)_SearchSpaceTransform)optuna_warn)BaseDistribution)FloatDistribution)IntDistribution)BaseSampler)&_INDEPENDENT_SAMPLING_WARNING_TEMPLATE)LazyRandomState)IntersectionSearchSpace)StudyDirection)FrozenTrial)
TrialStatecmaesg|=i  c                
   @  s   e Zd ZdZ						d`ddddddddddad d!Zdbd"d#Zdcd)d*Zddd-d.Zeded0d1Z	eded2d3Z
dfd6d7Zdgd9d:Zdhd>d?ZdidEdFZdjdKdLZdkdNdOZdldQdRZdmdUdVZdndXdYZdod^d_ZdS )pCmaEsSampleruh'  A sampler using `cmaes <https://github.com/CyberAgentAILab/cmaes>`__ as the backend.

    Example:

        Optimize a simple quadratic function by using :class:`~optuna.samplers.CmaEsSampler`.

        .. code-block:: console

           $ pip install cmaes

        .. testcode::

            import optuna


            def objective(trial):
                x = trial.suggest_float("x", -1, 1)
                y = trial.suggest_int("y", -1, 1)
                return x**2 + y


            sampler = optuna.samplers.CmaEsSampler()
            study = optuna.create_study(sampler=sampler)
            study.optimize(objective, n_trials=20)

    Please note that this sampler does not support CategoricalDistribution.
    However, :class:`~optuna.distributions.FloatDistribution` with ``step``,
    (:func:`~optuna.trial.Trial.suggest_float`) and
    :class:`~optuna.distributions.IntDistribution` (:func:`~optuna.trial.Trial.suggest_int`)
    are supported.

    If your search space contains categorical parameters, I recommend you
    to use :class:`~optuna.samplers.TPESampler` instead.
    Furthermore, there is room for performance improvements in parallel
    optimization settings. This sampler cannot use some trials for updating
    the parameters of multivariate normal distribution.

    For further information about CMA-ES algorithm, please refer to the following papers:

    - `N. Hansen, The CMA Evolution Strategy: A Tutorial. arXiv:1604.00772, 2016.
      <https://arxiv.org/abs/1604.00772>`__
    - `A. Auger and N. Hansen. A restart CMA evolution strategy with increasing population
      size. In Proceedings of the IEEE Congress on Evolutionary Computation (CEC 2005),
      pages 1769–1776. IEEE Press, 2005. <https://doi.org/10.1109/CEC.2005.1554902>`__
    - `N. Hansen. Benchmarking a BI-Population CMA-ES on the BBOB-2009 Function Testbed.
      GECCO Workshop, 2009. <https://doi.org/10.1145/1570256.1570333>`__
    - `Raymond Ros, Nikolaus Hansen. A Simple Modification in CMA-ES Achieving Linear Time and
      Space Complexity. 10th International Conference on Parallel Problem Solving From Nature,
      Sep 2008, Dortmund, Germany. inria-00287367. <https://doi.org/10.1007/978-3-540-87700-4_30>`__
    - `Masahiro Nomura, Shuhei Watanabe, Youhei Akimoto, Yoshihiko Ozaki, Masaki Onishi.
      Warm Starting CMA-ES for Hyperparameter Optimization, AAAI. 2021.
      <https://doi.org/10.1609/aaai.v35i10.17109>`__
    - `R. Hamano, S. Saito, M. Nomura, S. Shirakawa. CMA-ES with Margin: Lower-Bounding Marginal
      Probability for Mixed-Integer Black-Box Optimization, GECCO. 2022.
      <https://doi.org/10.1145/3512290.3528827>`__
    - `M. Nomura, Y. Akimoto, I. Ono. CMA-ES with Learning Rate Adaptation: Can CMA-ES with
      Default Population Size Solve Multimodal and Noisy Problems?, GECCO. 2023.
      <https://doi.org/10.1145/3583131.3590358>`__

    .. seealso::
        You can also use `optuna_integration.PyCmaSampler <https://optuna-integration.readthedocs.io/en/stable/reference/generated/optuna_integration.PyCmaSampler.html#optuna_integration.PyCmaSampler>`__ which is a sampler using cma
        library as the backend.

    Args:

        x0:
            A dictionary of an initial parameter values for CMA-ES. By default, the mean of ``low``
            and ``high`` for each distribution is used. Note that ``x0`` is sampled uniformly
            within the search space domain for each restart if you specify ``restart_strategy``
            argument.

        sigma0:
            Initial standard deviation of CMA-ES. By default, ``sigma0`` is set to
            ``min_range / 6``, where ``min_range`` denotes the minimum range of the distributions
            in the search space.

        seed:
            A random seed for CMA-ES.

        n_startup_trials:
            The independent sampling is used instead of the CMA-ES algorithm until the given number
            of trials finish in the same study.

        independent_sampler:
            A :class:`~optuna.samplers.BaseSampler` instance that is used for independent
            sampling. The parameters not contained in the relative search space are sampled
            by this sampler.
            The search space for :class:`~optuna.samplers.CmaEsSampler` is determined by
            :func:`~optuna.search_space.intersection_search_space()`.

            If :obj:`None` is specified, :class:`~optuna.samplers.RandomSampler` is used
            as the default.

            .. seealso::
                :class:`optuna.samplers` module provides built-in independent samplers
                such as :class:`~optuna.samplers.RandomSampler` and
                :class:`~optuna.samplers.TPESampler`.

        warn_independent_sampling:
            If this is :obj:`True`, a warning message is emitted when
            the value of a parameter is sampled by using an independent sampler.

            Note that the parameters of the first trial in a study are always sampled
            via an independent sampler, so no warning messages are emitted in this case.

        restart_strategy:
            Strategy for restarting CMA-ES optimization when converges to a local minimum.
            If :obj:`None` is given, CMA-ES will not restart (default).
            If 'ipop' is given, CMA-ES will restart with increasing population size.
            if 'bipop' is given, CMA-ES will restart with the population size
            increased or decreased.
            Please see also ``inc_popsize`` parameter.

            .. warning::
                Deprecated in v4.4.0. ``restart_strategy`` argument will be removed in the future.
                The removal of this feature is currently scheduled for v6.0.0,
                but this schedule is subject to change.
                From v4.4.0 onward, ``restart_strategy`` automatically falls back to ``None``, and
                ``restart_strategy`` will be supported in OptunaHub.
                See https://github.com/optuna/optuna/releases/tag/v4.4.0.

        popsize:
            A population size of CMA-ES.

        inc_popsize:
            Multiplier for increasing population size before each restart.
            This argument will be used when ``restart_strategy = 'ipop'``
            or ``restart_strategy = 'bipop'`` is specified.

            .. warning::
                Deprecated in v4.4.0. ``inc_popsize`` argument will be removed in the future.
                The removal of this feature is currently scheduled for v6.0.0,
                but this schedule is subject to change.
                From v4.4.0 onward, ``inc_popsize`` is no longer utilized within Optuna, and
                ``inc_popsize`` will be supported in OptunaHub.
                See https://github.com/optuna/optuna/releases/tag/v4.4.0.

        consider_pruned_trials:
            If this is :obj:`True`, the PRUNED trials are considered for sampling.

            .. note::
                Added in v2.0.0 as an experimental feature. The interface may change in newer
                versions without prior notice. See
                https://github.com/optuna/optuna/releases/tag/v2.0.0.

            .. note::
                It is suggested to set this flag :obj:`False` when the
                :class:`~optuna.pruners.MedianPruner` is used. On the other hand, it is suggested
                to set this flag :obj:`True` when the :class:`~optuna.pruners.HyperbandPruner` is
                used. Please see `the benchmark result
                <https://github.com/optuna/optuna/pull/1229>`__ for the details.

        use_separable_cma:
            If this is :obj:`True`, the covariance matrix is constrained to be diagonal.
            Due to reduce the model complexity, the learning rate for the covariance matrix
            is increased. Consequently, this algorithm outperforms CMA-ES on separable functions.

            .. note::
                Added in v2.6.0 as an experimental feature. The interface may change in newer
                versions without prior notice. See
                https://github.com/optuna/optuna/releases/tag/v2.6.0.

        with_margin:
            If this is :obj:`True`, CMA-ES with margin is used. This algorithm prevents samples in
            each discrete distribution (:class:`~optuna.distributions.FloatDistribution` with
            ``step`` and :class:`~optuna.distributions.IntDistribution`) from being fixed to a single
            point.
            Currently, this option cannot be used with ``use_separable_cma=True``.

            .. note::
                Added in v3.1.0 as an experimental feature. The interface may change in newer
                versions without prior notice. See
                https://github.com/optuna/optuna/releases/tag/v3.1.0.

        lr_adapt:
            If this is :obj:`True`, CMA-ES with learning rate adaptation is used.
            This algorithm focuses on working well on multimodal and/or noisy problems
            with default settings.
            Currently, this option cannot be used with ``use_separable_cma=True`` or
            ``with_margin=True``.

            .. note::
                Added in v3.3.0 or later, as an experimental feature.
                The interface may change in newer versions without prior notice. See
                https://github.com/optuna/optuna/releases/tag/v3.3.0.

        source_trials:
            This option is for Warm Starting CMA-ES, a method to transfer prior knowledge on
            similar HPO tasks through the initialization of CMA-ES. This method estimates a
            promising distribution from ``source_trials`` and generates the parameter of
            multivariate gaussian distribution. Please note that it is prohibited to use
            ``x0``, ``sigma0``, or ``use_separable_cma`` argument together.

            .. note::
                Added in v2.6.0 as an experimental feature. The interface may change in newer
                versions without prior notice. See
                https://github.com/optuna/optuna/releases/tag/v2.6.0.

    N   TF)consider_pruned_trialsrestart_strategypopsizeinc_popsizeuse_separable_cmawith_marginlr_adaptsource_trialsx0dict[str, Any] | Nonesigma0float | Nonen_startup_trialsintindependent_samplerBaseSampler | Nonewarn_independent_samplingboolseed
int | Noner   r   
str | Noner   r   r    r!   r"   r#   list[FrozenTrial] | NonereturnNonec                C  sd  |d us|
dkrt jjdddd}t| dt || _|| _|p'tjj	|d| _
|| _|| _t|| _t | _|| _|	| _|| _|| _|| _|| _| jrQd| _n
| jrXd	| _nd
| _| jrbtd | jritd | jd urrtd | jrytd | jrtd |d ur|d us|d urtd|d ur|rtd|r|s|rtd| jr| jrtdd S d S )Nr   z`restart_strategy`z4.4.0z6.0.0)named_verr_verz~ From v4.4.0 onward, `restart_strategy` automatically falls back to `None`. `restart_strategy` will be supported in OptunaHub.)r.   zsepcma:zcmawm:zcma:r   r    r#   r!   r"   zQIt is prohibited to pass `source_trials` argument when x0 or sigma0 is specified.zNIt is prohibited to pass `source_trials` argument when using separable CMA-ES.z]It is prohibited to pass `use_separable_cma` or `with_margin` argument when using `lr_adapt`.zMCurrently, we do not support `use_separable_cma=True` and `with_margin=True`.)r   _DEPRECATION_WARNING_TEMPLATEformatr   FutureWarning_x0_sigma0optunasamplersRandomSampler_independent_sampler_n_startup_trials_warn_independent_samplingr   _cma_rngr   _search_space_consider_pruned_trials_popsize_use_separable_cma_with_margin	_lr_adapt_source_trials_attr_prefixr
   
ValueError)selfr$   r&   r(   r*   r,   r.   r   r   r   r   r    r!   r"   r#   msg rN   J/home/ubuntu/.local/lib/python3.10/site-packages/optuna/samplers/_cmaes.py__init__   sj   

zCmaEsSampler.__init__c                 C  s   | j   d S N)r?   
reseed_rngrL   rN   rN   rO   rR   O  s   zCmaEsSampler.reseed_rngstudy'optuna.Study'trial'optuna.trial.FrozenTrial'dict[str, BaseDistribution]c                 C  sD   i }| j | D ]\}}| rq
t|ttfsq
|||< q
|S rQ   )rC   	calculateitemssingle
isinstancer   r   )rL   rT   rV   search_spacer4   distributionrN   rN   rO   infer_relative_search_spaceS  s   
z(CmaEsSampler.infer_relative_search_spacer]   dict[str, Any]c                 C  s   |  | t|dkri S | |}t|| jk ri S t|| j dd}| |}|d u r4| ||j}|j	t|j
krR| jrP| jjj}td| d d| _i S | ||j}t||jkrg }	|d |j D ]4}
|
jd ustJ dt|tjrt|
jd }n||
j}|jtjkr|
jn|
j }|	||f qi| |	 t!"|# }| $|}|D ]}|j%&|j'|||  q| j(j)*d	d
|j+ }|j,-| t|tjr|. \}}|j%&|j'd|/  n|. }| j0}|j%&|j'||j |1|}|S )Nr   T)transform_steptransform_0_1z7`CmaEsSampler` does not support dynamic search space. `z$` is used instead of `CmaEsSampler`.Fz"completed trials must have a value
x_for_tellr   i   )2_raise_error_if_multi_objectivelen_get_trialsr@   r   rG   _restore_optimizer_init_optimizer	directiondimboundsrA   r?   	__class____name___loggerwarning_get_solution_trials
generationpopulation_sizevaluer\   r   CMAwMnparraysystem_attrs	transformparamsr   MINIMIZEappendtellpickledumpshex_split_optimizer_str_storageset_trial_system_attr	_trial_idrB   rngrandintnumber_rngr.   asktolist_attr_key_generationuntransform)rL   rT   rV   r]   completed_trialstrans	optimizerind_sampler_namesolution_trials	solutionstxyoptimizer_stroptimizer_attrskeyr.   ry   rc   generation_attr_keyexternal_valuesrN   rN   rO   sample_relativee  sf   








zCmaEsSampler.sample_relativestrc                 C  
   | j d S )Nrq   rJ   rS   rN   rN   rO   r        
z!CmaEsSampler._attr_key_generationc                 C  r   )Nr   r   rS   rN   rN   rO   _attr_key_optimizer  r   z CmaEsSampler._attr_key_optimizerr   dict[str, str]c                   s"   d  fddtt D S )N c                 3  s$    | ]} j  d |  V  qdS ):N)r   ).0ir   rL   rN   rO   	<genexpr>  s    
z7CmaEsSampler._concat_optimizer_attrs.<locals>.<genexpr>)joinrangere   )rL   r   rN   r   rO   _concat_optimizer_attrs  s   
z$CmaEsSampler._concat_optimizer_attrsr   c                 C  s^   t |}i }tt|t D ]}|t }t|d t |}||| || j d| < q|S )Nr   r   )re   r   mathceil_SYSTEM_ATTR_MAX_LENGTHminr   )rL   r   optimizer_lenattrsr   startendrN   rN   rO   r     s   z!CmaEsSampler._split_optimizer_strr    'list[optuna.trial.FrozenTrial]''CmaClass' | Nonec                   sT   t |D ]#} fdd|j D }t|dkrq |}tt|  S d S )Nc                   s"   i | ]\}}|  jr||qS rN   )
startswithr   )r   r   rs   rS   rN   rO   
<dictcomp>  s    
z3CmaEsSampler._restore_optimizer.<locals>.<dictcomp>r   )	reversedrw   rZ   re   r   r}   loadsbytesfromhex)rL   r   rV   r   r   rN   rS   rO   rg     s   

zCmaEsSampler._restore_optimizerr   r   ri   r   
'CmaClass'c              
     s.  j d d df }j d d df }tj }| jd u rE| jd u r*||| d  }n| j}| jd u r?t|| d }n| j}d }n4tj	g | j
rR tj |tjkrYdnd fdd| jD }	t|	dkrqtdt|	\}}}t|t}| jrtj dkrtd	t ntj||j | jjdd
d| | jdS | jrtjtjtd}
t j! D ]0\}}t"|t#t$fsJ |j%d u s|j&rd|
|< q|j'|j(krd|
|< q|j%|j(|j'  |
|< qtj)||j |
|| jjdd
d| | jdS tj*|||j | jjdd
d| | j| j+dS )Nr   r         r   c                   s>   g | ]}|j  v rt|jr|jtt|j fqS rN   )state_is_compatible_search_spacedistributionsrx   ry   r   floatrs   r   r   expected_statessignr   rN   rO   
<listcomp>  s    

z0CmaEsSampler._init_optimizer.<locals>.<listcomp>zNo compatible source_trialszSeparable CMA-ES does not operate meaningfully on single-dimensional search spaces. The setting `use_separable_cma=True` will be ignored.i
   )meansigmark   r.   n_max_resamplingrr   )dtypeg        g      ?)r   r   rk   stepscovr.   r   rr   )r   r   r   rk   r.   r   rr   r"   ),rk   re   rI   r:   rx   r;   ru   r   r   COMPLETErD   r{   PRUNEDr   rz   rK   r   get_warm_start_mgdmax_EPSrF   r   UserWarningSepCMArB   r   r   rE   rG   emptyrC   r   	enumeratevaluesr\   r   r   steploglowhighrt   CMArH   )rL   r   ri   lower_boundsupper_boundsn_dimensionr   r&   r   source_solutionsr   r   distrN   r   rO   rh     s   




	

zCmaEsSampler._init_optimizer
param_nameparam_distributionr   r   c                 C  sF   |  | | jr| |}t|| jkr| || | j||||S rQ   )rd   rA   rf   re   r@   _log_independent_samplingr?   sample_independent)rL   rT   rV   r   r   complete_trialsrN   rN   rO   r   9  s   

zCmaEsSampler.sample_independentr   c              	   C  s*   t tj||j| jjj| jjdd d S )NzVdynamic search space and `CategoricalDistribution` are not supported by `CmaEsSampler`)r   trial_numberindependent_sampler_namesampler_namefallback_reason)rn   ro   r   r8   r   r?   rl   rm   )rL   rV   r   rN   rN   rO   r   K  s   z&CmaEsSampler._log_independent_samplinglist[FrozenTrial]c                 C  s   g }|j dddD ]9}|jtjkr|| q	|jtjkrBt|jdkrB| jrBt	|j
 \}}|d u r5q	t|}||_|| q	|S )NFT)deepcopy	use_cacher   )rf   r   r   r   r{   r   re   intermediate_valuesrD   r   rZ   copyr   rs   )rL   rT   r   r   _rs   copied_trN   rN   rO   rf   Y  s    

zCmaEsSampler._get_trialstrialsrq   c                   s   | j  fdd|D S )Nc                   s"   g | ]} |j d kr|qS )r   )rw   getr   rq   r   rN   rO   r   p  s   " z5CmaEsSampler._get_solution_trials.<locals>.<listcomp>)r   )rL   r   rq   rN   r   rO   rp   l  s   z!CmaEsSampler._get_solution_trialsoptuna.Studyc                 C  s   | j || d S rQ   )r?   before_trial)rL   rT   rV   rN   rN   rO   r   r  s   zCmaEsSampler.before_trialr   r   r   Sequence[float] | Nonec                 C  s   | j |||| d S rQ   )r?   after_trial)rL   rT   rV   r   r   rN   rN   rO   r   u  s   zCmaEsSampler.after_trial)NNr   NTN)r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r   r-   r   r0   r   r/   r   r)   r    r-   r!   r-   r"   r-   r#   r1   r2   r3   )r2   r3   )rT   rU   rV   rW   r2   rX   )rT   rU   rV   rW   r]   rX   r2   r`   )r2   r   )r   r   r2   r   )r   r   r2   r   )r   r   r2   r   )r   r   ri   r   r2   r   )
rT   rU   rV   rW   r   r   r   r   r2   r   )rV   r   r   r   r2   r3   )rT   rU   r2   r   )r   r   rq   r)   r2   r   )rT   r   rV   r   r2   r3   )
rT   rU   rV   rW   r   r   r   r   r2   r3   )rm   
__module____qualname____doc__rP   rR   r_   r   propertyr   r   r   r   rg   rh   r   r   rf   rp   r   r   rN   rN   rN   rO   r   /   sH     K	
W

M


	

_



r   r   r   r]   rX   r2   r-   c                 C  s>   t t| j | }|t | j  kot |kS   S rQ   )re   setrC   keysintersection)r   r]   intersection_sizerN   rN   rO   r     s   "r   )r   r   r]   rX   r2   r-   )6
__future__r   collections.abcr   r   r   r}   typingr   r   r   r   numpyru   r<   r   r	   optuna._experimentalr
   optuna._importsr   optuna._transformr   optuna._warningsr   optuna.distributionsr   r   r   optuna.samplersr   optuna.samplers._baser   "optuna.samplers._lazy_random_stater   optuna.search_spacer   optuna.study._study_directionr   optuna.trialr   r   r   r   r   rt   CmaClass
get_loggerrm   rn   r   r   r   r   rN   rN   rN   rO   <module>   sP    
    T