
    (^i                        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Z	 	 	 	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 	 	 dd	Z G d
 de
      Zy)    )annotations)KeysViewN)
BasePruner)StudyDirection)
TrialStatec                    t        j                  t        | j                  j	                               t
              }|t        j                  k(  rt        j                  |      S t        j                  |      S )Ndtype)
npasarraylistintermediate_valuesvaluesfloatr   MAXIMIZEnanmaxnanmin)trial	directionr   s      [/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/optuna/pruners/_percentile.py(_get_best_intermediate_result_over_stepsr      sT     ZZU66==?@NFN+++yy  99V    c                p   t        |       dk(  rt        d      | D cg c]   }||j                  v s|j                  |   " }}t        |      |k  rt        j                  S |t
        j                  k(  rd|z
  }t        t        j                  t        j                  |t              |            S c c}w )Nr   zNo trials have been completed.d   r	   )len
ValueErrorr   mathnanr   r   r   r   nanpercentilearray)completed_trialsr   step
percentilen_min_trialstr   s          r   /_get_percentile_intermediate_result_over_trialsr&      s     !9:: .>()I^I^A^d#  ,.xxN+++:%

HH(6	
 s
   B3B3c                l      |z
  |z  |z  |z   }|dk\  sJ t        j                   fd|d      }||k  S )Nr   c                     || kD  r|k7  r|S | S )N )second_last_stepsr"   s     r   <lambda>z,_is_first_in_interval_step.<locals>.<lambda>>   s    -=)=!t)A Qa r   )	functoolsreduce)r"   intermediate_stepsn_warmup_stepsinterval_stepsnearest_lower_pruning_stepr*   s   `     r   _is_first_in_interval_stepr4   4   sb     	~	"(")+9": &*** !''a
 888r   c                  D    e Zd ZdZ	 	 	 ddd	 	 	 	 	 	 	 	 	 	 	 ddZd	dZy)
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$   c               "   d|cxk  rdk  sn t        d|d      |dk  rt        d|d      |dk  rt        d|d      |dk  rt        d	|d      |dk  rt        d
|d      || _        || _        || _        || _        || _        y )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=r7   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#   n_startup_trialsr1   r2   r$   s         r   __init__zPercentilePruner.__init__   s     j'C'V:-WXY  aYHXGZZ[\  AUnEVVWX  AUnEVVWX  !YL?Z[\  &!1--)r   c                4   |j                  dt        j                  f      }t        |      }|dk(  ry|| j                  k  ry|j
                  }|y| j                  }||k  ryt        ||j                  j                         || j                        sy|j                  }t        ||      }t        j                  |      ryt        |||| j                   | j"                        }	t        j                  |	      ry|t$        j&                  k(  r||	k  S ||	kD  S )NF)deepcopystatesr   T)
get_trialsr   COMPLETEr   r;   	last_stepr<   r4   r   keysr=   r   r   r   isnanr&   r:   r>   r   r   )
r?   studyr   r!   n_trialsr"   r1   r   best_intermediate_resultps
             r   prunezPercentilePruner.prune   s    ++UJDWDWCY+Z'(q=d,,,<--. )%++002NDDXDX
 OO	#KES\#] ::./;it/?/?ASAS
 ::a=///+a//'!++r   N)   r   r7   )r#   r   r@   intr1   rP   r2   rP   r$   rP   returnNone)rJ   z'optuna.study.Study'r   'optuna.trial.FrozenTrial'rQ   bool)__name__
__module____qualname____doc__rA   rN   r)   r   r   r6   r6   F   sb    ?H !""* "*"* "* 	"*
 "* "* 
"*H$,r   r6   )r   rS   r   r   rQ   r   )r!   z list['optuna.trial.FrozenTrial']r   r   r"   rP   r#   r   r$   rP   rQ   r   )
r"   rP   r0   zKeysView[int]r1   rP   r2   rP   rQ   rT   )
__future__r   collections.abcr   r.   r   numpyr   optunaoptuna.prunersr   optuna.study._study_directionr   optuna.trial._stater   r   r&   r4   r6   r)   r   r   <module>r`      s    " $     % 8 *%2@
6  	
  89
9#09BE9WZ9	9$J,z J,r   