o
    }oiO                  	   @  sN  d dl mZ d dlmZ 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
 d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dl m!Z! e"e#Z$dZ%G dd deZ&e!j'ddddddddd,d*d+Z(dS )-    )annotations)Mapping)SequenceN)Any)cast)overload)distributions)logging)convert_positional_args)deprecated_func)JSONSerializable)optuna_warn-_convert_old_distribution_to_new_distribution)BaseDistribution)CategoricalChoiceType)CategoricalDistribution)FloatDistribution)IntDistribution)_SUGGEST_INT_POSITIONAL_ARGS)	BaseTrial)
TrialStatez Use suggest_float{args} instead.c                   @  s  e Zd ZdZdddddZddd Zdd!d"Zdd#d$Zdd%d&Zdd(d)Z	dd*d+dd2d3Z
ed4d5ejd6d7d8dd9d:Zed4d5ejd;d7d8dd<d=Zed4d5ejd>d7d8dd@dAZeedBdCdDdEd*d+ddFdGZeddJdKZeddMdKZeddOdKZeddQdKZeddSdKZeddVdKZddWdKZddXdYZddZd[Zdd]d^Zed_dCdd`daZddbdcZddfdgZeddhdiZejddjdiZeddkdlZejddndlZddpdqZ ddrdsZ!ee e!Z"eddtduZ#e#jddvduZ#eddwdxZ$e$jddydxZ$eddzd{Z%e%jdd|d{Z%edd}d~Z&e&jddd~Z&edddZ'e'jdddZ'edddZ(edddZ)dS )FrozenTriala  Status and results of a :class:`~optuna.trial.Trial`.

    An object of this class has the same methods as :class:`~optuna.trial.Trial`, but is not
    associated with, nor has any references to a :class:`~optuna.study.Study`.

    It is therefore not possible to make persistent changes to a storage from this object by
    itself, for instance by using :func:`~optuna.trial.FrozenTrial.set_user_attr`.

    It will suggest the parameter values stored in :attr:`params` and will not sample values from
    any distributions.

    It can be passed to objective functions (see :func:`~optuna.study.Study.optimize`) and is
    useful for deploying optimization results.

    Example:

        Re-evaluate an objective function with parameter values optimized study.

        .. testcode::

            import optuna


            def objective(trial):
                x = trial.suggest_float("x", -1, 1)
                return x**2


            study = optuna.create_study()
            study.optimize(objective, n_trials=3)

            assert objective(study.best_trial) == study.best_value

    .. note::
        Instances are mutable, despite the name.
        For instance, :func:`~optuna.trial.FrozenTrial.set_user_attr` will update user attributes
        of objects in-place.


        Example:

            Overwritten attributes.

            .. testcode::

                import copy
                import datetime

                import optuna


                def objective(trial):
                    x = trial.suggest_float("x", -1, 1)

                    # this user attribute always differs
                    trial.set_user_attr("evaluation time", datetime.datetime.now())

                    return x**2


                study = optuna.create_study()
                study.optimize(objective, n_trials=3)

                best_trial = study.best_trial
                best_trial_copy = copy.deepcopy(best_trial)

                # re-evaluate
                objective(best_trial)

                # the user attribute is overwritten by re-evaluation
                assert best_trial.user_attrs != best_trial_copy.user_attrs

    .. note::
        Please refer to :class:`~optuna.trial.Trial` for details of methods and properties.


    Attributes:
        number:
            Unique and consecutive number of :class:`~optuna.trial.Trial` for each
            :class:`~optuna.study.Study`. Note that this field uses zero-based numbering.
        state:
            :class:`TrialState` of the :class:`~optuna.trial.Trial`.
        value:
            Objective value of the :class:`~optuna.trial.Trial`.
            ``value`` and ``values`` must not be specified at the same time.
        values:
            Sequence of objective values of the :class:`~optuna.trial.Trial`.
            The length is greater than 1 if the problem is multi-objective optimization.
            ``value`` and ``values`` must not be specified at the same time.
        datetime_start:
            Datetime where the :class:`~optuna.trial.Trial` started.
        datetime_complete:
            Datetime where the :class:`~optuna.trial.Trial` finished.
        params:
            Dictionary that contains suggested parameters.
        distributions:
            Dictionary that contains the distributions of :attr:`params`.
        user_attrs:
            Dictionary that contains the attributes of the :class:`~optuna.trial.Trial` set with
            :func:`optuna.trial.Trial.set_user_attr`.
        system_attrs:
            Dictionary that contains the attributes of the :class:`~optuna.trial.Trial` set with
            :func:`optuna.trial.Trial.set_system_attr`.
        intermediate_values:
            Intermediate objective values set with :func:`optuna.trial.Trial.report`.
    N)valuesnumberintstater   valuefloat | Nonedatetime_startdatetime.datetime | Nonedatetime_completeparamsdict[str, Any]r   dict[str, BaseDistribution]
user_attrssystem_attrsintermediate_valuesdict[int, float]trial_idr   Sequence[float] | NonereturnNonec                C  s   || _ || _d | _|d ur|d urtd|d ur|g| _n	|d ur't|| _|| _|| _|| _|| _|	| _	|
| _
|| _|| _d S )Nz)Specify only one of `value` and `values`.)_numberr   _values
ValueErrorlist_datetime_startr!   _params_user_attrs_system_attrsr'   _distributions	_trial_id)selfr   r   r   r   r!   r"   r   r%   r&   r'   r)   r    r8   H/home/ubuntu/.local/lib/python3.10/site-packages/optuna/trial/_frozen.py__init__   s"   


zFrozenTrial.__init__otherr   boolc                 C  s   t |tstS |j| jkS N)
isinstancer   NotImplemented__dict__r7   r;   r8   r8   r9   __eq__   s   
zFrozenTrial.__eq__c                 C  s   t |tstS | j|jk S r=   r>   r   r?   r   rA   r8   r8   r9   __lt__      
zFrozenTrial.__lt__c                 C  s   t |tstS | j|jkS r=   rC   rA   r8   r8   r9   __le__   rE   zFrozenTrial.__le__c                   s   t t fdd jD S )Nc                 3  s    | ]}t  |V  qd S r=   )getattr.0fieldr7   r8   r9   	<genexpr>       z'FrozenTrial.__hash__.<locals>.<genexpr>)hashtupler@   rK   r8   rK   r9   __hash__   s   zFrozenTrial.__hash__strc                   s,   dj  jjd fdd jD d dS )Nz{cls}({kwargs})z, c                 3  s>    | ]}d j |ds|n|dd tt |dV  qdS )z{field}={value}_   N)rJ   r   )format
startswithreprrG   rH   rK   r8   r9   rL      s    
z'FrozenTrial.__repr__.<locals>.<genexpr>z, value=None)clskwargs)rT   	__class____name__joinr@   rK   r8   rK   r9   __repr__   s   zFrozenTrial.__repr__F)steplognamelowfloathighr]   r^   c             	   C  s   |  |t||||dS N)r^   r]   )_suggestr   r7   r_   r`   rb   r]   r^   r8   r8   r9   suggest_float   s   	zFrozenTrial.suggest_floatz3.0.0z6.0.0 )args)textc                 C  s   |  |||S r=   rf   r7   r_   r`   rb   r8   r8   r9   suggest_uniform      zFrozenTrial.suggest_uniformz(..., log=True)c                 C  s   | j |||ddS )NT)r^   rj   rk   r8   r8   r9   suggest_loguniform      zFrozenTrial.suggest_loguniformz(..., step=...)qc                 C  s   | j ||||dS )N)r]   rj   )r7   r_   r`   rb   rp   r8   r8   r9   suggest_discrete_uniform   ro   z$FrozenTrial.suggest_discrete_uniformz3.5.0z5.0.0)previous_positional_arg_namesdeprecated_versionremoved_versionrS   c             
   C  s   t | |t||||dS rc   )r   rd   r   re   r8   r8   r9   suggest_int   s   zFrozenTrial.suggest_intchoicesSequence[None]c                 C     d S r=   r8   r7   r_   rv   r8   r8   r9   suggest_categorical      zFrozenTrial.suggest_categoricalSequence[bool]c                 C  rx   r=   r8   ry   r8   r8   r9   rz      r{   Sequence[int]c                 C  rx   r=   r8   ry   r8   r8   r9   rz      r{   Sequence[float]c                 C  rx   r=   r8   ry   r8   r8   r9   rz      r{   Sequence[str]c                 C  rx   r=   r8   ry   r8   r8   r9   rz      r{   Sequence[CategoricalChoiceType]r   c                 C  rx   r=   r8   ry   r8   r8   r9   rz      s   c                 C  s   |  |t|dS )N)rv   )rd   r   ry   r8   r8   r9   rz     s   c                 C     dS )a  Interface of report function.

        Since :class:`~optuna.trial.FrozenTrial` is not pruned,
        this report function does nothing.

        .. seealso::
            Please refer to :func:`~optuna.trial.FrozenTrial.should_prune`.

        Args:
            value:
                A value returned from the objective function.
            step:
                Step of the trial (e.g., Epoch of neural network training). Note that pruners
                assume that ``step`` starts at zero. For example,
                :class:`~optuna.pruners.MedianPruner` simply checks if ``step`` is less than
                ``n_warmup_steps`` as the warmup mechanism.
        Nr8   )r7   r   r]   r8   r8   r9   report	  s   zFrozenTrial.reportc                 C  r   )a'  Suggest whether the trial should be pruned or not.

        The suggestion is always :obj:`False` regardless of a pruning algorithm.

        .. note::
            :class:`~optuna.trial.FrozenTrial` only samples one combination of parameters.

        Returns:
            :obj:`False`.
        Fr8   rK   r8   r8   r9   should_prune  s   zFrozenTrial.should_prunekeyc                 C     || j |< d S r=   r3   r7   r   r   r8   r8   r9   set_user_attr,  s   zFrozenTrial.set_user_attrz3.1.0c                 C  r   r=   r4   r   r8   r8   r9   set_system_attr/  rm   zFrozenTrial.set_system_attrc                 C  s8  | j tjkr| jd u rtd| j  r| jd u rtdn	| jd ur'td| j tjkr;| jd ur;td| j d| j tj	krX| jd u rJtdt
dd | jD rXtd	t| j t| j krxtd
t| j t| j | j D ]\}}| j| }||}||std|||q}d S )NzK`datetime_start` is supposed to be set when the trial state is not waiting.z?`datetime_complete` is supposed to be set for a finished trial.zC`datetime_complete` is supposed to be None for an unfinished trial.z2values should be None for a failed trial, but got .z*values should be set for a complete trial.c                 s  s    | ]}t |V  qd S r=   )mathisnan)rI   xr8   r8   r9   rL   G  rM   z(FrozenTrial._validate.<locals>.<genexpr>zvalues should not contain NaN.z0Inconsistent parameters {} and distributions {}.zFThe value {} of parameter '{}' isn't contained in the distribution {}.)r   r   WAITINGr   r/   is_finishedr!   FAILr.   COMPLETEanysetr"   keysr   rT   itemsto_internal_repr	_contains)r7   
param_nameparam_valuedistributionparam_value_in_internal_reprr8   r8   r9   	_validate3  sF   







zFrozenTrial._validater   r   c                 C  sr   || j vrtd|| j | }||}||s$td||| || jv r2t| j| | || j|< |S )NzjThe value of the parameter '{}' is not found. Please set it at the construction of the FrozenTrial object.zNThe value {} of the parameter '{}' is out of the range of the distribution {}.)	r2   r/   rT   r   r   r   r5   r    check_distribution_compatibility)r7   r_   r   r   r   r8   r8   r9   rd   [  s    






zFrozenTrial._suggestc                 C     | j S r=   r-   rK   r8   r8   r9   r   q     zFrozenTrial.numberc                 C  
   || _ d S r=   r   r7   r   r8   r8   r9   r   u     
c                 C  s.   | j d urt| j dkrtd| j d S d S )NrS   DThis attribute is not available during multi-objective optimization.r   r.   lenRuntimeErrorrK   r8   r8   r9   r   y  s   

zFrozenTrial.valuevc                 C  s>   | j d urt| j dkrtd|d ur|g| _ d S d | _ d S )NrS   r   r   r7   r   r8   r8   r9   r     s   

list[float] | Nonec                 C  r   r=   )r.   rK   r8   r8   r9   _get_values  s   zFrozenTrial._get_valuesc                 C  s    |d urt || _d S d | _d S r=   )r0   r.   r   r8   r8   r9   _set_values  s   
zFrozenTrial._set_valuesc                 C  r   r=   r1   rK   r8   r8   r9   r     r   zFrozenTrial.datetime_startc                 C  r   r=   r   r   r8   r8   r9   r     r   c                 C  r   r=   r2   rK   r8   r8   r9   r"     r   zFrozenTrial.paramsc                 C  r   r=   r   )r7   r"   r8   r8   r9   r"     r   c                 C  r   r=   r5   rK   r8   r8   r9   r     r   zFrozenTrial.distributionsc                 C  r   r=   r   r   r8   r8   r9   r     r   c                 C  r   r=   r   rK   r8   r8   r9   r%     r   zFrozenTrial.user_attrsc                 C  r   r=   r   r   r8   r8   r9   r%     r   c                 C  r   r=   r   rK   r8   r8   r9   r&     r   zFrozenTrial.system_attrsMapping[str, JSONSerializable]c                 C  s   t tttf || _d S r=   )r   dictrQ   r   r4   r   r8   r8   r9   r&     s   
int | Nonec                 C  s    t | jdkr	dS t| j S )zReturn the maximum step of :attr:`intermediate_values` in the trial.

        Returns:
            The maximum step of intermediates.
        r   N)r   r'   maxr   rK   r8   r8   r9   	last_step  s   zFrozenTrial.last_stepdatetime.timedelta | Nonec                 C  s   | j r| jr| j| j  S dS )ziReturn the elapsed time taken to complete the trial.

        Returns:
            The duration.
        N)r   r!   rK   r8   r8   r9   duration  s   zFrozenTrial.duration)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   r+   r<   )r+   r   )r+   rQ   )r_   rQ   r`   ra   rb   ra   r]   r   r^   r<   r+   ra   )r_   rQ   r`   ra   rb   ra   r+   ra   )
r_   rQ   r`   ra   rb   ra   rp   ra   r+   ra   )r_   rQ   r`   r   rb   r   r]   r   r^   r<   r+   r   )r_   rQ   rv   rw   r+   r,   )r_   rQ   rv   r|   r+   r<   )r_   rQ   rv   r}   r+   r   )r_   rQ   rv   r~   r+   ra   )r_   rQ   rv   r   r+   rQ   )r_   rQ   rv   r   r+   r   )r   ra   r]   r   r+   r,   )r+   r<   )r   rQ   r   r   r+   r,   )r+   r,   )r_   rQ   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#   )r"   r#   r+   r,   )r+   r$   )r   r$   r+   r,   )r   r#   r+   r,   )r   r   r+   r,   )r+   r   )r+   r   )*rZ   
__module____qualname____doc__r:   rB   rD   rF   rP   r\   rf   r   _suggest_deprecated_msgrT   rl   rn   rq   r
   r   ru   r   rz   r   r   r   r   r   rd   propertyr   setterr   r   r   r   r   r"   r   r%   r&   r   r   r8   r8   r8   r9   r       s    y
"









(	


r   )r   r   r   r"   r   r%   r&   r'   r   r   r   r   r   r*   r"   dict[str, Any] | Noner   "dict[str, BaseDistribution] | Noner%   r&   r'   dict[int, float] | Noner+   c                 C  s   |pi }|pi }dd |  D }|pi }|pi }|pi }| tjkr%d}ntj }|  r1|}	nd}	tdd| ||||	|||||d}
|
  |
S )a  Create a new :class:`~optuna.trial.FrozenTrial`.

    Example:

        .. testcode::

            import optuna
            from optuna.distributions import CategoricalDistribution
            from optuna.distributions import FloatDistribution

            trial = optuna.trial.create_trial(
                params={"x": 1.0, "y": 0},
                distributions={
                    "x": FloatDistribution(0, 10),
                    "y": CategoricalDistribution([-1, 0, 1]),
                },
                value=5.0,
            )

            assert isinstance(trial, optuna.trial.FrozenTrial)
            assert trial.value == 5.0
            assert trial.params == {"x": 1.0, "y": 0}

    .. seealso::

        See :func:`~optuna.study.Study.add_trial` for how this function can be used to create a
        study from existing trials.

    .. note::

        Please note that this is a low-level API. In general, trials that are passed to objective
        functions are created inside :func:`~optuna.study.Study.optimize`.

    .. note::
        When ``state`` is :class:`TrialState.COMPLETE`, the following parameters are
        required:

        * ``params``
        * ``distributions``
        * ``value`` or ``values``

    Args:
        state:
            Trial state.
        value:
            Trial objective value. Must be specified if ``state`` is :class:`TrialState.COMPLETE`.
            ``value`` and ``values`` must not be specified at the same time.
        values:
            Sequence of the trial objective values. The length is greater than 1 if the problem is
            multi-objective optimization.
            Must be specified if ``state`` is :class:`TrialState.COMPLETE`.
            ``value`` and ``values`` must not be specified at the same time.
        params:
            Dictionary with suggested parameters of the trial.
        distributions:
            Dictionary with parameter distributions of the trial.
        user_attrs:
            Dictionary with user attributes.
        system_attrs:
            Dictionary with system attributes. Should not have to be used for most users.
        intermediate_values:
            Dictionary with intermediate objective values of the trial.

    Returns:
        Created trial.
    c                 S  s   i | ]	\}}|t |qS r8   r   )rI   r   distr8   r8   r9   
<dictcomp>1  s    z create_trial.<locals>.<dictcomp>N)r   r)   r   r   r   r   r!   r"   r   r%   r&   r'   )r   r   r   datetimenowr   r   r   )r   r   r   r"   r   r%   r&   r'   r   r!   trialr8   r8   r9   create_trial  s<   N

r   )r   r   r   r   r   r*   r"   r   r   r   r%   r   r&   r   r'   r   r+   r   ))
__future__r   collections.abcr   r   r   r   typingr   r   r   optunar   r	   optuna._convert_positional_argsr
   optuna._deprecatedr   optuna._typingr   optuna._warningsr   optuna.distributionsr   r   r   r   r   r   optuna.trial._baser   r   optuna.trial._stater   
get_loggerrZ   _loggerr   r   r   r   r8   r8   r8   r9   <module>   sL    
   F