
    (^i)                        d dl mZ d dlZd dlZd dlmZ d dlmZ d dlm	Z	  G d de      Z
ddZdd	Zdd
Z	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 	 	 ddZy)    )annotationsN)
BasePruner)StudyDirection)
TrialStatec                  <    e Zd ZdZ	 	 	 	 d	 	 	 	 	 	 	 	 	 ddZddZy)SuccessiveHalvingPrunera|  Pruner using Asynchronous Successive Halving Algorithm.

    `Successive Halving <https://proceedings.mlr.press/v51/jamieson16.html>`__ is a bandit-based
    algorithm to identify the best one among multiple configurations. This class implements an
    asynchronous version of Successive Halving. Please refer to the paper of
    `Asynchronous Successive Halving <https://proceedings.mlsys.org/paper_files/paper/2020/file/
    a06f20b349c6cf09a6b171c71b88bbfc-Paper.pdf>`__ for detailed descriptions.

    Note that, this class does not take care of the parameter for the maximum
    resource, referred to as :math:`R` in the paper. The maximum resource allocated to a trial is
    typically limited inside the objective function (e.g., ``step`` number in `simple_pruning.py
    <https://github.com/optuna/optuna-examples/blob/main/basic/pruning.py>`__,
    ``EPOCH`` number in `chainer_integration.py
    <https://github.com/optuna/optuna-examples/tree/main/chainer/chainer_integration.py#L73>`__).

    .. seealso::
        Please refer to :meth:`~optuna.trial.Trial.report`.

    Example:

        We minimize an objective function with ``SuccessiveHalvingPruner``.

        .. 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.SuccessiveHalvingPruner()
            )
            study.optimize(objective, n_trials=20)

    Args:
        min_resource:
            A parameter for specifying the minimum resource allocated to a trial
            (in the `paper <https://proceedings.mlsys.org/paper_files/paper/2020/file/
            a06f20b349c6cf09a6b171c71b88bbfc-Paper.pdf>`__ this parameter is referred to as
            :math:`r`).
            This parameter defaults to 'auto' where the value is determined based on a heuristic
            that looks at the number of required steps for the first trial to complete.

            A trial is never pruned until it executes
            :math:`\mathsf{min}\_\mathsf{resource} \times
            \mathsf{reduction}\_\mathsf{factor}^{
            \mathsf{min}\_\mathsf{early}\_\mathsf{stopping}\_\mathsf{rate}}`
            steps (i.e., the completion point of the first rung). When the trial completes
            the first rung, it will be promoted to the next rung only
            if the value of the trial is placed in the top
            :math:`{1 \over \mathsf{reduction}\_\mathsf{factor}}` fraction of
            the all trials that already have reached the point (otherwise it will be pruned there).
            If the trial won the competition, it runs until the next completion point (i.e.,
            :math:`\mathsf{min}\_\mathsf{resource} \times
            \mathsf{reduction}\_\mathsf{factor}^{
            (\mathsf{min}\_\mathsf{early}\_\mathsf{stopping}\_\mathsf{rate}
            + \mathsf{rung})}` steps)
            and repeats the same procedure.

            .. note::
                If the step of the last intermediate value may change with each trial, please
                manually specify the minimum possible step to ``min_resource``.
        reduction_factor:
            A parameter for specifying reduction factor of promotable trials
            (in the `paper <https://proceedings.mlsys.org/paper_files/paper/2020/file/
            a06f20b349c6cf09a6b171c71b88bbfc-Paper.pdf>`__ this parameter is
            referred to as :math:`\eta`).  At the completion point of each rung,
            about :math:`{1 \over \mathsf{reduction}\_\mathsf{factor}}`
            trials will be promoted.
        min_early_stopping_rate:
            A parameter for specifying the minimum early-stopping rate
            (in the `paper <https://proceedings.mlsys.org/paper_files/paper/2020/file/
            a06f20b349c6cf09a6b171c71b88bbfc-Paper.pdf>`__ this parameter is
            referred to as :math:`s`).
        bootstrap_count:
            Minimum number of trials that need to complete a rung before any trial
            is considered for promotion into the next rung.
    c                (   t        |t              r|dk7  rt        dj                  |            t        |t              r|dk  rt        dj                  |            |dk  rt        dj                  |            |dk  rt        dj                  |            |dk  rt        d	j                  |            |dkD  r|dk(  rt        d
j                  |            d | _        t        |t              r|| _        || _        || _        || _        y )NautozSThe value of `min_resource` is {}, but must be either `min_resource` >= 1 or 'auto'   zSThe value of `min_resource` is {}, but must be either `min_resource >= 1` or 'auto'   zJThe value of `reduction_factor` is {}, but must be `reduction_factor >= 2`r   zXThe value of `min_early_stopping_rate` is {}, but must be `min_early_stopping_rate >= 0`zHThe value of `bootstrap_count` is {}, but must be `bootstrap_count >= 0`z_bootstrap_count > 0 and min_resource == 'auto' are mutually incompatible, bootstrap_count is {})	
isinstancestr
ValueErrorformatint_min_resource_reduction_factor_min_early_stopping_rate_bootstrap_count)selfmin_resourcereduction_factormin_early_stopping_ratebootstrap_counts        c/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/optuna/pruners/_successive_halving.py__init__z SuccessiveHalvingPruner.__init__s   s8    lC(\V-CCCI6,CW 
 lC(\A-=CCI6,CW 
 a66<f=M6N 
 #Q&==CVD[=\ 
 Q55;VO5L 
 Q<6#9CCI6/CZ 
 *.lC(!-D!1(?% /    c                   |j                   }|yt        |      }|j                  |   }d }	 | j                  1||j	                  d      }t        |      | _        | j                  y| j                  J | j                  | j                  | j                  |z   z  z  }||k  ryt        j                  |      ry||j	                  d      }t        |      }|j                  j                  |j                  ||       t        |||      }	t        |	      | j                   k  ryt#        ||	| j                  |j$                        sy|dz  }&)NFT)deepcopyr   )	last_step_get_current_rungintermediate_valuesr   
get_trials_estimate_min_resourcer   r   mathisnan_completed_rung_key_storageset_trial_system_attr	_trial_id_get_competing_valueslenr   !_is_trial_promotable_to_next_rung	direction)
r   studytrialsteprungvaluetrialsrung_promotion_steprung_key	competings
             r   prunezSuccessiveHalvingPruner.prune   sa   < '))$/:>!!)>"--u-=F%;F%C"%%- %%111"&"4"4&&4+H+H4+OP# ))zz% ~))5)9*40HNN00(ER-feXFI 9~!6!664&&	 AIDQ r   N)r
      r   r   )
r   z	str | intr   r   r   r   r   r   returnNone)r/   z'optuna.study.Study'r0   'optuna.trial.FrozenTrial'r:   bool)__name__
__module____qualname____doc__r   r8    r   r   r   r      sR    eR #) !'( 0000 00 "%	00
 00 
00d1r   r   c                    | D cg c]9  }|j                   t        j                  k(  s!|j                  .|j                  ; }}|sy t	        |      }t	        |dz  d      S c c}w )Nd   r   )stater   COMPLETEr    max)r4   tn_stepsr    s       r   r$   r$      sd    #qww*2E2E'E!++JaG   GIyC##s   "A"A"A"c                r    d}t        |      | j                  v r|dz  }t        |      | j                  v r|S )Nr   r   )r'   system_attrs)r0   r2   s     r   r!   r!      s=    D
d
#u'9'9
9	 d
#u'9'9
9Kr   c                $    dj                  |       S )Nzcompleted_rung_{})r   )r2   s    r   r'   r'      s    %%d++r   c                    | D cg c]   }||j                   v s|j                   |   " }}|j                  |       |S c c}w )N)rK   append)r4   r3   r6   rH   competing_valuess        r   r+   r+      sJ     ;A_QHPQP^P^D^x0__E" `s   ??c                    t        |      |z  dz
  }|dk(  rd}|j                          |t        j                  k(  r| ||dz       k\  S | ||   k  S )Nr   r   )r,   sortr   MAXIMIZE)r3   rO   r   study_directionpromotable_idxs        r   r-   r-      sm     *+/??1DN .111(>A+=)>???$^444r   )r4    list['optuna.trial.FrozenTrial']r:   z
int | None)r0   r<   r:   r   )r2   r   r:   r   )r4   rV   r3   floatr6   r   r:   list[float])
r3   rW   rO   rX   r   r   rT   r   r:   r=   )
__future__r   r%   optunaoptuna.pruners._baser   optuna.study._study_directionr   optuna.trial._stater   r   r$   r!   r'   r+   r-   rB   r   r   <module>r^      s    "   + 8 *Kj K\
$,,5:FI55!5 5 $	5
 
5r   