
    ,YHhm2                       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 d dlmZ d dlm Z  erd dl!m"Z"  G d de      Z#y)    )annotations)Callable)Sequence)Any)TYPE_CHECKING)warn_experimental_argument)BaseDistribution)BaseGASampler)LazyRandomState)RandomSampler)NSGAIIAfterTrialStrategy)NSGAIIChildGenerationStrategy)BaseCrossover)UniformCrossover)&NSGAIIElitePopulationSelectionStrategy)IntersectionSearchSpace)FrozenTrial)
TrialState)Studyc                       e Zd ZdZddddddddddd
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZ	 	 	 	 	 	 dd	Zdd
Z	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 	 	 ddZ	ddZ
	 	 	 	 	 	 	 	 	 	 ddZ xZS )NSGAIISamplerak  Multi-objective sampler using the NSGA-II algorithm.

    NSGA-II stands for "Nondominated Sorting Genetic Algorithm II",
    which is a well known, fast and elitist multi-objective genetic algorithm.

    For further information about NSGA-II, please refer to the following paper:

    - `A fast and elitist multiobjective genetic algorithm: NSGA-II
      <https://doi.org/10.1109/4235.996017>`__

    .. note::
        :class:`~optuna.samplers.TPESampler` became much faster in v4.0.0 and supports several
        features not supported by ``NSGAIISampler`` such as handling of dynamic search
        space and categorical distance. To use :class:`~optuna.samplers.TPESampler`, you need to
        explicitly specify the sampler as follows:

        .. testcode::

            import optuna


            def objective(trial):
                x = trial.suggest_float("x", -100, 100)
                y = trial.suggest_categorical("y", [-1, 0, 1])
                f1 = x**2 + y
                f2 = -((x - 2) ** 2 + y)
                return f1, f2


            # We minimize the first objective and maximize the second objective.
            sampler = optuna.samplers.TPESampler()
            study = optuna.create_study(directions=["minimize", "maximize"], sampler=sampler)
            study.optimize(objective, n_trials=100)

        Please also check `our article
        <https://medium.com/optuna/significant-speed-up-of-multi-objective-tpesampler-in-optuna-v4-0-0-2bacdcd1d99b>`__
        for more details of the speedup in v4.0.0.

    Args:
        population_size:
            Number of individuals (trials) in a generation.
            ``population_size`` must be greater than or equal to ``crossover.n_parents``.
            For :class:`~optuna.samplers.nsgaii.UNDXCrossover` and
            :class:`~optuna.samplers.nsgaii.SPXCrossover`, ``n_parents=3``, and for the other
            algorithms, ``n_parents=2``.

        mutation_prob:
            Probability of mutating each parameter when creating a new individual.
            If :obj:`None` is specified, the value ``1.0 / len(parent_trial.params)`` is used
            where ``parent_trial`` is the parent trial of the target individual.

        crossover:
            Crossover to be applied when creating child individuals.
            The available crossovers are listed here:
            https://optuna.readthedocs.io/en/stable/reference/samplers/nsgaii.html.

            :class:`~optuna.samplers.nsgaii.UniformCrossover` is always applied to parameters
            sampled from :class:`~optuna.distributions.CategoricalDistribution`, and by
            default for parameters sampled from other distributions unless this argument
            is specified.

            For more information on each of the crossover method, please refer to
            specific crossover documentation.

        crossover_prob:
            Probability that a crossover (parameters swapping between parents) will occur
            when creating a new individual.

        swapping_prob:
            Probability of swapping each parameter of the parents during crossover.

        seed:
            Seed for random number generator.

        constraints_func:
            An optional function that computes the objective constraints. It must take a
            :class:`~optuna.trial.FrozenTrial` and return the constraints. The return value must
            be a sequence of :obj:`float` s. A value strictly larger than 0 means that a
            constraints is violated. A value equal to or smaller than 0 is considered feasible.
            If ``constraints_func`` returns more than one value for a trial, that trial is
            considered feasible if and only if all values are equal to 0 or smaller.

            The ``constraints_func`` will be evaluated after each successful trial.
            The function won't be called when trials fail or they are pruned, but this behavior is
            subject to change in the future releases.

            The constraints are handled by the constrained domination. A trial x is said to
            constrained-dominate a trial y, if any of the following conditions is true:

            1. Trial x is feasible and trial y is not.
            2. Trial x and y are both infeasible, but trial x has a smaller overall violation.
            3. Trial x and y are feasible and trial x dominates trial y.

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

        elite_population_selection_strategy:
            The selection strategy for determining the individuals to survive from the current
            population pool. Default to :obj:`None`.

            .. note::
                The arguments ``elite_population_selection_strategy`` was added in v3.3.0 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.

        child_generation_strategy:
            The strategy for generating child parameters from parent trials. Defaults to
            :obj:`None`.

            .. note::
                The arguments ``child_generation_strategy`` was added in v3.3.0 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.

        after_trial_strategy:
            A set of procedure to be conducted after each trial. Defaults to :obj:`None`.

            .. note::
                The arguments ``after_trial_strategy`` was added in v3.3.0 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.
    2   Ng?g      ?)
population_sizemutation_prob	crossovercrossover_probswapping_probseedconstraints_func#elite_population_selection_strategychild_generation_strategyafter_trial_strategyc       
   	     n   |dk  rt        d      |t        d       |
t        d       |	t        d       |t        d       |t        |      }t        |t              st        d| d      ||j
                  k  rt        d	| d
|j
                   d| d      t        |   |       t        |      | _	        t        |      | _        || _        t               | _        |xs t        ||      | _        |	xs t#        |||||| j                        | _        |
xs t'        |      | _        y )N   z5`population_size` must be greater than or equal to 2.r   r"   r!   r    'zu' is not a valid crossover. For valid crossovers see https://optuna.readthedocs.io/en/stable/reference/samplers.html.zUsing z9, the population size should be greater than or equal to z%. The specified `population_size` is .)r   )r   )r   r   )r   r   r   r   r   rng)r   )
ValueErrorr   r   
isinstancer   	n_parentssuper__init__r   _random_samplerr   _rng_constraints_funcr   _search_spacer   $_elite_population_selection_strategyr   _child_generation_strategyr   _after_trial_strategy)selfr   r   r   r   r   r   r   r    r!   r"   	__class__s              X/var/www/html/planif/env/lib/python3.12/site-packages/optuna/samplers/nsgaii/_sampler.pyr,   zNSGAIISampler.__init__   s   . QTUU'&'9:+&'=>$0&'BC.:&'LM(7I)]3I; T T  Y000 $KKTK^K^J_ `77F6GqJ  	9,$7#D)	!146 0 5 /BR 	1 & ,-++#!1II 	' &: &
=U->
"    c                    | j                   j                          | j                  j                  j	                          y N)r-   
reseed_rngr.   r'   r   )r4   s    r6   r:   zNSGAIISampler.reseed_rng   s(    '')		r7   c                    i }| j                   j                  |      j                         D ]  \  }}|j                         r|||<    |S r9   )r0   	calculateitemssingle)r4   studytrialsearch_spacenamedistributions         r6   infer_relative_search_spacez)NSGAIISampler.infer_relative_search_space   sZ     57"&"4"4">">u"E"K"K"M 	.D,""$
 !-L	. r7   c           	     x    | j                  || j                  ||dz
        | j                  ||dz
        z         S )N   )r1   get_populationget_parent_population)r4   r?   
generations      r6   select_parentzNSGAIISampler.select_parent   sF    88zA~6((
Q?@
 	
r7   c                    | j                  ||      }| j                  ||      }t        |      dk(  ri S | j                  |||      S )Nr   )get_trial_generationrH   lenr2   )r4   r?   r@   rA   rI   parent_populations         r6   sample_relativezNSGAIISampler.sample_relative  sR     ..ue<
 66ujI !Q&I..ulDUVVr7   c                >    | j                   j                  ||||      S r9   )r-   sample_independent)r4   r?   r@   
param_nameparam_distributions        r6   rQ   z NSGAIISampler.sample_independent  s'     ##665*&8
 	
r7   c                <    | j                   j                  ||       y r9   )r-   before_trial)r4   r?   r@   s      r6   rU   zNSGAIISampler.before_trial"  s    ))%7r7   c                    |t         j                  t         j                  t         j                  fv sJ | j	                  ||||       | j
                  j                  ||||       y r9   )r   COMPLETEFAILPRUNEDr3   r-   after_trial)r4   r?   r@   statevaluess        r6   rZ   zNSGAIISampler.after_trial%  sW     ,,jooz?P?PQQQQ""5%?((ufEr7   )r   intr   zfloat | Noner   zBaseCrossover | Noner   floatr   r^   r   z
int | Noner   z/Callable[[FrozenTrial], Sequence[float]] | Noner    z>Callable[[Study, list[FrozenTrial]], list[FrozenTrial]] | Noner!   zXCallable[[Study, dict[str, BaseDistribution], list[FrozenTrial]], dict[str, Any]] | Noner"   zOCallable[[Study, FrozenTrial, TrialState, Sequence[float] | None], None] | NonereturnNone)r_   r`   )r?   r   r@   r   r_   dict[str, BaseDistribution])r?   r   rI   r]   r_   zlist[FrozenTrial])r?   r   r@   r   rA   ra   r_   zdict[str, Any])
r?   r   r@   r   rR   strrS   r	   r_   r   )r?   r   r@   r   r_   r`   )
r?   r   r@   r   r[   r   r\   zSequence[float] | Noner_   r`   )__name__
__module____qualname____doc__r,   r:   rD   rJ   rO   rQ   rU   rZ   __classcell__)r5   s   @r6   r   r      s   |B  "&**. #"LP   'O
 O
 $	O

 (O
 O
 O
 O
 JO
 KO
O
$ \%O
( 
)O
b#.	$

W
W 
W 2	
W
 

W

 
 	

 -
 

 8	F	F 	F 		F
 '	F 
	Fr7   r   N)$
__future__r   collections.abcr   r   typingr   r   optuna._experimentalr   optuna.distributionsr	   optuna.samplers._gar
   "optuna.samplers._lazy_random_stater   optuna.samplers._randomr   ,optuna.samplers.nsgaii._after_trial_strategyr   1optuna.samplers.nsgaii._child_generation_strategyr   (optuna.samplers.nsgaii._crossovers._baser   +optuna.samplers.nsgaii._crossovers._uniformr   ;optuna.samplers.nsgaii._elite_population_selection_strategyr   optuna.search_spacer   optuna.trialr   r   optuna.studyr   r    r7   r6   <module>ry      sW    " $ $    ; 1 - > 1 Q [ B H 8 $ # "QFM QFr7   