L im2ddlmZddlmZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z dd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlm Z erddl!m"Z"Gdde Z#y)) annotations)Callable)Sequence)Any) TYPE_CHECKING)warn_experimental_argument)BaseDistribution) BaseGASampler)LazyRandomState) RandomSampler)NSGAIIAfterTrialStrategy)NSGAIIChildGenerationStrategy) BaseCrossover)UniformCrossover)&NSGAIIElitePopulationSelectionStrategy)IntersectionSearchSpace) FrozenTrial) TrialState)Studyc eZdZdZddddddddddd dfdZddZ dd Zdd Z dd Z dd Z dd Z ddZ xZ S) NSGAIISamplerakMulti-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 `__ .. 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 `__ 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. 2Ng?g?) population_size mutation_prob crossovercrossover_prob swapping_probseedconstraints_func#elite_population_selection_strategychild_generation_strategyafter_trial_strategyc n|dkr td| td| td| td| td| t|}t|tstd|d||j krtd |d |j d |d t || t||_ t||_ ||_ t|_|xs t|||_| xst#||||||j|_| xs t'||_y)Nz5`population_size` must be greater than or equal to 2.rr"r!r 'zu' is not a valid crossover. For valid crossovers see https://optuna.readthedocs.io/en/stable/reference/samplers.html.zUsing z9, the population size should be greater than or equal to z%. The specified `population_size` is .)r)r)rr)rrrrrrng)r) ValueErrorrr isinstancer n_parentssuper__init__r _random_samplerr _rng_constraints_funcr _search_spacer$_elite_population_selection_strategyr_child_generation_strategyr _after_trial_strategy) selfrrrrrrrr r!r" __class__s e/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/optuna/samplers/nsgaii/_sampler.pyr,zNSGAIISampler.__init__s. Q TU U  ' &'9 :  + &'= > $ 0 &'B C . : &'L M  (7I)]3I;TT  Y00 0 $KKTK^K^J_`77F6GqJ  9,$7#D) !146 0 5 /BR 1 & ,-++#!1II  '&:& =U-> "c|jj|jjj yN)r- reseed_rngr.r'r)r4s r6r:zNSGAIISampler.reseed_rngs( '') r7ci}|jj|jD]\}}|jr|||<|Sr9)r0 calculateitemssingle)r4studytrial search_spacename distributions r6infer_relative_search_spacez)NSGAIISampler.infer_relative_search_spacesZ57 "&"4"4">">u"E"K"K"M . D,""$ !-L  .r7c x|j||j||dz |j||dz zS)N)r1get_populationget_parent_population)r4r? generations r6 select_parentzNSGAIISampler.select_parentsF88    zA~ 6(( Q? @  r7c|j||}|j||}t|dk(riS|j|||S)Nr)get_trial_generationrHlenr2)r4r?r@rArIparent_populations r6sample_relativezNSGAIISampler.sample_relativesR ..ue<  66ujI  !Q &I..ulDUVVr7c>|jj||||Sr9)r-sample_independent)r4r?r@ param_nameparam_distributions r6rQz NSGAIISampler.sample_independents'##66 5*&8  r7c<|jj||yr9)r- before_trial)r4r?r@s r6rUzNSGAIISampler.before_trial"s ))%7r7c|tjtjtjfvsJ|j |||||j j ||||yr9)rCOMPLETEFAILPRUNEDr3r- after_trial)r4r?r@statevaluess r6rZzNSGAIISampler.after_trial%sW,,jooz?P?PQQQQ ""5%? ((ufEr7)rintrz float | NonerzBaseCrossover | Nonerfloatrr^rz int | Nonerz/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] | NonereturnNone)r_r`)r?rr@rr_dict[str, BaseDistribution])r?rrIr]r_zlist[FrozenTrial])r?rr@rrArar_zdict[str, Any]) r?rr@rrRstrrSr r_r)r?rr@rr_r`) r?rr@rr[rr\zSequence[float] | Noner_r`) __name__ __module__ __qualname____doc__r,r:rDrJrOrQrUrZ __classcell__)r5s@r6rrs|B "&**. #"LP   'O O $ O ( O  O O O JO  KO  O $ \%O ( )O b  #.  $   W W W2 W  W     -   8 F F F F ' F  Fr7rN)$ __future__rcollections.abcrrtypingrroptuna._experimentalroptuna.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_strategyroptuna.search_spacer optuna.trialrr optuna.studyrrr7r6rysW"$$ ;1->1Q[BH8$#"QFMQFr7