o
    }oi                     @  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Zd dl	m
Z
 d dlmZ d dlmZ d ddZd!ddZd"ddZG dd de
ZdS )#    )annotations)KeysViewN)
BasePruner)StudyDirection)
TrialStatetrial'optuna.trial.FrozenTrial'	directionr   returnfloatc                 C  s6   t jt| j td}|tjkrt |S t 	|S )Ndtype)
npasarraylistintermediate_valuesvaluesr   r   MAXIMIZEnanmaxnanmin)r   r	   r    r   N/home/ubuntu/.local/lib/python3.10/site-packages/optuna/pruners/_percentile.py(_get_best_intermediate_result_over_steps   s   


r   completed_trials list['optuna.trial.FrozenTrial']stepint
percentilen_min_trialsc                   sd   t | dkr
td fdd| D }t ||k rtjS |tjkr%d| }tttj	|td|S )Nr   zNo trials have been completed.c                   s    g | ]} |j v r|j   qS r   )r   ).0tr   r   r   
<listcomp>"   s    zC_get_percentile_intermediate_result_over_trials.<locals>.<listcomp>d   r   )
len
ValueErrormathnanr   r   r   r   nanpercentilearray)r   r	   r   r   r   r   r   r!   r   /_get_percentile_intermediate_result_over_trials   s   

r*   intermediate_stepsKeysView[int]n_warmup_stepsinterval_stepsboolc                   s>    | | | | }|dksJ t  fdd|d}||k S )Nr   c                   s   || kr
| kr
|S | S )Nr   )second_last_stepsr!   r   r   <lambda>>   s    z,_is_first_in_interval_step.<locals>.<lambda>)	functoolsreduce)r   r+   r-   r.   nearest_lower_pruning_stepr0   r   r!   r   _is_first_in_interval_step4   s   
r7   c                   @  s2   e Zd ZdZ			ddddddZdddZdS )PercentilePruneraI
  Pruner to keep the specified percentile of the trials.

    Prune if the best intermediate value is in the bottom percentile among trials at the same step.

    Example:

        .. testcode::

            import numpy as np
            from sklearn.datasets import load_iris
            from sklearn.linear_model import SGDClassifier
            from sklearn.model_selection import train_test_split

            import optuna

            X, y = load_iris(return_X_y=True)
            X_train, X_valid, y_train, y_valid = train_test_split(X, y)
            classes = np.unique(y)


            def objective(trial):
                alpha = trial.suggest_float("alpha", 0.0, 1.0)
                clf = SGDClassifier(alpha=alpha)
                n_train_iter = 100

                for step in range(n_train_iter):
                    clf.partial_fit(X_train, y_train, classes=classes)

                    intermediate_value = clf.score(X_valid, y_valid)
                    trial.report(intermediate_value, step)

                    if trial.should_prune():
                        raise optuna.TrialPruned()

                return clf.score(X_valid, y_valid)


            study = optuna.create_study(
                direction="maximize",
                pruner=optuna.pruners.PercentilePruner(
                    25.0, n_startup_trials=5, n_warmup_steps=30, interval_steps=10
                ),
            )
            study.optimize(objective, n_trials=20)

    Args:
        percentile:
            Percentile which must be between 0 and 100 inclusive
            (e.g., When given 25.0, top of 25th percentile trials are kept).
        n_startup_trials:
            Pruning is disabled until the given number of trials finish in the same study.
        n_warmup_steps:
            Pruning is disabled until the trial exceeds the given number of step. Note that
            this feature assumes that ``step`` starts at zero.
        interval_steps:
            Interval in number of steps between the pruning checks, offset by the warmup steps.
            If no value has been reported at the time of a pruning check, that particular check
            will be postponed until a value is reported. Value must be at least 1.
        n_min_trials:
            Minimum number of reported trial results at a step to judge whether to prune.
            If the number of reported intermediate values from all trials at the current step
            is less than ``n_min_trials``, the trial will not be pruned. This can be used to ensure
            that a minimum number of trials are run to completion without being pruned.
       r      )r   r   r   n_startup_trialsr   r-   r.   r   r
   Nonec                C  s   d|  kr
dksn t d|d|dk rt d|d|dk r+t d|d|dk r7t d	|d|dk rCt d
|d|| _|| _|| _|| _|| _d S )Ng        r#   zCPercentile must be between 0 and 100 inclusive, but got percentile=.r   zFNumber of startup trials cannot be negative, but got n_startup_trials=zBNumber of warmup steps cannot be negative, but got n_warmup_steps=r:   zBPruning interval steps must be at least 1, but got interval_steps=zFNumber of trials for pruning must be at least 1, but got n_min_trials=)r%   _percentile_n_startup_trials_n_warmup_steps_interval_steps_n_min_trials)selfr   r;   r-   r.   r   r   r   r   __init__   s2   	





zPercentilePruner.__init__study'optuna.study.Study'r   r   r/   c           
      C  s   |j dtjfd}t|}|dkrdS || jk rdS |j}|d u r#dS | j}||k r,dS t||j	 || j
s9dS |j}t||}t|rHdS t|||| j| j}	t|	rYdS |tjkrb||	k S ||	kS )NF)deepcopystatesr   T)
get_trialsr   COMPLETEr$   r?   	last_stepr@   r7   r   keysrA   r	   r   r&   isnanr*   r>   rB   r   r   )
rC   rE   r   r   n_trialsr   r-   r	   best_intermediate_resultpr   r   r   prune   s8   




zPercentilePruner.pruneN)r9   r   r:   )r   r   r;   r   r-   r   r.   r   r   r   r
   r<   )rE   rF   r   r   r
   r/   )__name__
__module____qualname____doc__rD   rQ   r   r   r   r   r8   F   s    D$r8   )r   r   r	   r   r
   r   )r   r   r	   r   r   r   r   r   r   r   r
   r   )
r   r   r+   r,   r-   r   r.   r   r
   r/   )
__future__r   collections.abcr   r4   r&   numpyr   optunaoptuna.prunersr   optuna.study._study_directionr   optuna.trial._stater   r   r*   r7   r8   r   r   r   r   <module>   s    

	
