
    -jim2                       S SK Jr  S SKJr  S SKJr  S SKJr  S SKJr  S SKJ	r	  S SK
Jr  S SKJr  S S	KJr  S S
KJr  S SKJr  S SKJr  S SKJr  S SKJr  S SKJr  S SKJr  S SKJr  S SKJ r   \(       a  S SK!J"r"   " S S\5      r#g)    )annotations)Callable)Sequence)Any)TYPE_CHECKING)warn_experimental_argument)BaseDistribution)BaseGASampler)LazyRandomState)RandomSampler)NSGAIIAfterTrialStrategy)NSGAIIChildGenerationStrategy)BaseCrossover)UniformCrossover)&NSGAIIElitePopulationSelectionStrategy)IntersectionSearchSpace)FrozenTrial)
TrialState)Studyc                     ^  \ rS rSrSrSSSSSSSSSSS.
                     SU 4S jjjrSS	 jr      SS
 jrSS jr        SS jr	          SS jr
SS jr          SS jrSrU =r$ )NSGAIISampler   a  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       
   	       > US:  a  [        S5      eUb  [        S5        U
b  [        S5        U	b  [        S5        Ub  [        S5        Uc  [        U5      n[        U[        5      (       d  [        SU S35      eXR
                  :  a  [        S	U S
UR
                   SU S35      e[        TU ]  US9  [        US9U l	        [        U5      U l        Xpl        [        5       U l        U=(       d	    [        XS9U l        U	=(       d    [#        UUUUUU R                  S9U l        U
=(       d	    ['        US9U l        g )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              Y/home/james-whalen/.local/lib/python3.13/site-packages/optuna/samplers/nsgaii/_sampler.pyr-   NSGAIISampler.__init__   s}   . QTUU'&'9:+&'=>$0&'BC.:&'LM(7I)]33I; T T  000 $KKTK^K^J_ `77F6GqJ  	9,$7#D)	!146 0 5 / 	1 & ,-++#!1II 	' &: &
=U->
"    c                    U R                   R                  5         U R                  R                  R	                  5         g N)r.   
reseed_rngr/   r(   r   )r5   s    r7   r<   NSGAIISampler.reseed_rng   s(    '')		r9   c                    0 nU R                   R                  U5      R                  5        H   u  pEUR                  5       (       a  M  XSU'   M"     U$ r;   )r1   	calculateitemssingle)r5   studytrialsearch_spacenamedistributions         r7   infer_relative_search_space)NSGAIISampler.infer_relative_search_space   sU     57"&"4"4">">u"E"K"K"MD""$$
 !- #N r9   c           	     t    U R                  UU R                  XS-
  5      U R                  XS-
  5      -   5      $ )N   )r2   get_populationget_parent_population)r5   rB   
generations      r7   select_parentNSGAIISampler.select_parent   sB    88A~6((Q?@
 	
r9   c                    U R                  X5      nU R                  X5      n[        U5      S:X  a  0 $ U R                  XU5      $ )Nr   )get_trial_generationrL   lenr3   )r5   rB   rC   rD   rM   parent_populations         r7   sample_relativeNSGAIISampler.sample_relative  sL     ..u<
 66uI !Q&I..uDUVVr9   c                :    U R                   R                  XX45      $ r;   )r.   sample_independent)r5   rB   rC   
param_nameparam_distributions        r7   rW    NSGAIISampler.sample_independent  s"     ##66*
 	
r9   c                :    U R                   R                  X5        g r;   )r.   before_trial)r5   rB   rC   s      r7   r\   NSGAIISampler.before_trial"  s    ))%7r9   c                    U[         R                  [         R                  [         R                  4;   d   eU R	                  XX45        U R
                  R                  XX45        g r;   )r   COMPLETEFAILPRUNEDr4   r.   after_trial)r5   rB   rC   statevaluess        r7   rb   NSGAIISampler.after_trial%  sO     ,,jooz?P?PQQQQ""5?((uEr9   )r4   r3   r0   r2   r.   r/   r1   )r   intr   zfloat | Noner   zBaseCrossover | Noner   floatr   rg   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)rh   ri   )rB   r   rC   r   rh   dict[str, BaseDistribution])rB   r   rM   rf   rh   zlist[FrozenTrial])rB   r   rC   r   rD   rj   rh   zdict[str, Any])
rB   r   rC   r   rX   strrY   r	   rh   r   )rB   r   rC   r   rh   ri   )
rB   r   rC   r   rc   r   rd   zSequence[float] | Nonerh   ri   )__name__
__module____qualname____firstlineno____doc__r-   r<   rG   rN   rT   rW   r\   rb   __static_attributes____classcell__)r6   s   @r7   r   r      s   |B  "&**. #"LP   'O
 O
 $	O

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

 -
 

 8	F	F 	F 		F
 '	F 
	F 	Fr9   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    r9   r7   <module>r      sW    " $ $    ; 1 - > 1 Q [ B H 8 $ # "QFM QFr9   