
    (^iK                        d dl m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Z G d dej.                        Zy)    )annotationsN)	Container)Sequence)Any)cast)JSONSerializable)BaseDistribution)UpdateFinishedTrialError)FrozenStudy)StudyDirection)FrozenTrial)
TrialStatezno-name-c                  t   e Zd ZdZej
                  	 d	 	 	 	 	 d d       Zej
                  d!d       Zej
                  d"d       Zej
                  d#d       Z	ej
                  d$d       Z
ej
                  d%d       Zej
                  d&d	       Zej
                  d'd
       Zej
                  d'd       Zej
                  d(d       Zej
                  dd)d       Zej
                  	 	 	 	 	 	 	 	 	 	 d*d       Zd+dZd,dZd-dZej
                  	 d	 	 	 	 	 	 	 d.d       Zej
                  	 	 	 	 	 	 	 	 d/d       Zej
                  d0d       Zej
                  d1d       Zej
                  d2d       Zej
                  	 	 d3	 	 	 	 	 	 	 d4d       Z	 d	 	 	 	 	 d5dZd6dZd7dZd7dZd7dZd8dZ d9dZ!y):BaseStoragea  Base class for storages.

    This class is not supposed to be directly accessed by library users.

    This class abstracts a backend database and provides internal interfaces to
    read/write histories of studies and trials.

    A storage class implementing this class must meet the following requirements.

    **Thread safety**

    A storage class instance can be shared among multiple threads, and must therefore be
    thread-safe. It must guarantee that a data instance read from the storage must not be modified
    by subsequent writes. For example, `FrozenTrial` instance returned by `get_trial`
    should not be updated by the subsequent `set_trial_xxx`. This is usually achieved by replacing
    the old data with a copy on `set_trial_xxx`.

    A storage class can also assume that a data instance returned are never modified by its user.
    When a user modifies a return value from a storage class, the internal state of the storage
    may become inconsistent. Consequences are undefined.

    **Ownership of RUNNING trials**

    Trials in finished states are not allowed to be modified.
    Trials in the WAITING state are not allowed to be modified except for the `state` field.
    Nc                    t         )a  Create a new study from a name.

        If no name is specified, the storage class generates a name.
        The returned study ID is unique among all current and deleted studies.

        Args:
            directions:
                 A sequence of direction whose element is either
                 :obj:`~optuna.study.StudyDirection.MAXIMIZE` or
                 :obj:`~optuna.study.StudyDirection.MINIMIZE`.
            study_name:
                Name of the new study to create.

        Returns:
            ID of the created study.

        Raises:
            :exc:`optuna.exceptions.DuplicatedStudyError`:
                If a study with the same ``study_name`` already exists.
        NotImplementedError)self
directions
study_names      V/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/optuna/storages/_base.pycreate_new_studyzBaseStorage.create_new_study3   s
    0 "!    c                    t         )zDelete a study.

        Args:
            study_id:
                ID of the study.

        Raises:
            :exc:`KeyError`:
                If no study with the matching ``study_id`` exists.
        r   r   study_ids     r   delete_studyzBaseStorage.delete_studyM   s
     "!r   c                    t         )a  Register a user-defined attribute to a study.

        This method overwrites any existing attribute.

        Args:
            study_id:
                ID of the study.
            key:
                Attribute key.
            value:
                Attribute value. It should be JSON serializable.

        Raises:
            :exc:`KeyError`:
                If no study with the matching ``study_id`` exists.
        r   r   r   keyvalues       r   set_study_user_attrzBaseStorage.set_study_user_attr[   
    $ "!r   c                    t         )a  Register an optuna-internal attribute to a study.

        This method overwrites any existing attribute.

        Args:
            study_id:
                ID of the study.
            key:
                Attribute key.
            value:
                Attribute value. It should be JSON serializable.

        Raises:
            :exc:`KeyError`:
                If no study with the matching ``study_id`` exists.
        r   r   s       r   set_study_system_attrz!BaseStorage.set_study_system_attro   r#   r   c                    t         )a  Read the ID of a study.

        Args:
            study_name:
                Name of the study.

        Returns:
            ID of the study.

        Raises:
            :exc:`KeyError`:
                If no study with the matching ``study_name`` exists.
        r   )r   r   s     r   get_study_id_from_namez"BaseStorage.get_study_id_from_name   
     "!r   c                    t         )a  Read the study name of a study.

        Args:
            study_id:
                ID of the study.

        Returns:
            Name of the study.

        Raises:
            :exc:`KeyError`:
                If no study with the matching ``study_id`` exists.
        r   r   s     r   get_study_name_from_idz"BaseStorage.get_study_name_from_id   r(   r   c                    t         )a@  Read whether a study maximizes or minimizes an objective.

        Args:
            study_id:
                ID of a study.

        Returns:
            Optimization directions list of the study.

        Raises:
            :exc:`KeyError`:
                If no study with the matching ``study_id`` exists.
        r   r   s     r   get_study_directionsz BaseStorage.get_study_directions   r(   r   c                    t         )a<  Read the user-defined attributes of a study.

        Args:
            study_id:
                ID of the study.

        Returns:
            Dictionary with the user attributes of the study.

        Raises:
            :exc:`KeyError`:
                If no study with the matching ``study_id`` exists.
        r   r   s     r   get_study_user_attrsz BaseStorage.get_study_user_attrs   r(   r   c                    t         )aJ  Read the optuna-internal attributes of a study.

        Args:
            study_id:
                ID of the study.

        Returns:
            Dictionary with the optuna-internal attributes of the study.

        Raises:
            :exc:`KeyError`:
                If no study with the matching ``study_id`` exists.
        r   r   s     r   get_study_system_attrsz"BaseStorage.get_study_system_attrs   r(   r   c                    t         )zRead a list of :class:`~optuna.study.FrozenStudy` objects.

        Returns:
            A list of :class:`~optuna.study.FrozenStudy` objects, sorted by ``study_id``.

        r   r   s    r   get_all_studieszBaseStorage.get_all_studies   s
     "!r   c                    t         )a'  Create and add a new trial to a study.

        The returned trial ID is unique among all current and deleted trials.

        Args:
            study_id:
                ID of the study.
            template_trial:
                Template :class:`~optuna.trial.FrozenTrial` with default user-attributes,
                system-attributes, intermediate-values, and a state.

        Returns:
            ID of the created trial.

        Raises:
            :exc:`KeyError`:
                If no study with the matching ``study_id`` exists.
        r   )r   r   template_trials      r   create_new_trialzBaseStorage.create_new_trial   
    ( "!r   c                    t         )a?  Set a parameter to a trial.

        Args:
            trial_id:
                ID of the trial.
            param_name:
                Name of the parameter.
            param_value_internal:
                Internal representation of the parameter value.
            distribution:
                Sampled distribution of the parameter.

        Raises:
            :exc:`KeyError`:
                If no trial with the matching ``trial_id`` exists.
            :exc:`~optuna.exceptions.UpdateFinishedTrialError`:
                If the trial is already finished.
        r   )r   trial_id
param_nameparam_value_internaldistributions        r   set_trial_paramzBaseStorage.set_trial_param   s
    4 "!r   c                    | j                  |d      }t        |      |k  rt        dj                  ||            ||   j                  S )a`  Read the trial ID of a trial.

        Args:
            study_id:
                ID of the study.
            trial_number:
                Number of the trial.

        Returns:
            ID of the trial.

        Raises:
            :exc:`KeyError`:
                If no trial with the matching ``study_id`` and ``trial_number`` exists.
        F)deepcopyz?No trial with trial number {} exists in study with study_id {}.)get_all_trialslenKeyErrorformat	_trial_id)r   r   trial_numbertrialss       r   'get_trial_id_from_study_id_trial_numberz3BaseStorage.get_trial_id_from_study_id_trial_number  sX      $$X$>v;,&QXX ( 
 l#---r   c                8    | j                  |      j                  S )aw  Read the trial number of a trial.

        .. note::

            The trial number is only unique within a study, and is sequential.

        Args:
            trial_id:
                ID of the trial.

        Returns:
            Number of the trial.

        Raises:
            :exc:`KeyError`:
                If no trial with the matching ``trial_id`` exists.
        )	get_trialnumberr   r9   s     r   get_trial_number_from_idz$BaseStorage.get_trial_number_from_id1  s    $ ~~h'...r   c                z    | j                  |      }|j                  |   j                  |j                  |         S )a  Read the parameter of a trial.

        Args:
            trial_id:
                ID of the trial.
            param_name:
                Name of the parameter.

        Returns:
            Internal representation of the parameter.

        Raises:
            :exc:`KeyError`:
                If no trial with the matching ``trial_id`` exists.
                If no such parameter exists.
        )rI   distributionsto_internal_reprparams)r   r9   r:   trials       r   get_trial_paramzBaseStorage.get_trial_paramE  s7    " x("":.??Z@XYYr   c                    t         )a  Update the state and values of a trial.

        Set return values of an objective function to values argument.
        If values argument is not :obj:`None`, this method overwrites any existing trial values.

        Args:
            trial_id:
                ID of the trial.
            state:
                New state of the trial.
            values:
                Values of the objective function.

        Returns:
            :obj:`True` if the state is successfully updated.
            :obj:`False` if the state is kept the same.
            The latter happens when this method tries to update the state of
            :obj:`~optuna.trial.TrialState.RUNNING` trial to
            :obj:`~optuna.trial.TrialState.RUNNING`.

        Raises:
            :exc:`KeyError`:
                If no trial with the matching ``trial_id`` exists.
            :exc:`~optuna.exceptions.UpdateFinishedTrialError`:
                If the trial is already finished.
        r   )r   r9   statevaluess       r   set_trial_state_valuesz"BaseStorage.set_trial_state_valuesY  s
    < "!r   c                    t         )a  Report an intermediate value of an objective function.

        This method overwrites any existing intermediate value associated with the given step.

        Args:
            trial_id:
                ID of the trial.
            step:
                Step of the trial (e.g., the epoch when training a neural network).
            intermediate_value:
                Intermediate value corresponding to the step.

        Raises:
            :exc:`KeyError`:
                If no trial with the matching ``trial_id`` exists.
            :exc:`~optuna.exceptions.UpdateFinishedTrialError`:
                If the trial is already finished.
        r   )r   r9   stepintermediate_values       r   set_trial_intermediate_valuez(BaseStorage.set_trial_intermediate_valuey  s
    , "!r   c                    t         )a  Set a user-defined attribute to a trial.

        This method overwrites any existing attribute.

        Args:
            trial_id:
                ID of the trial.
            key:
                Attribute key.
            value:
                Attribute value. It should be JSON serializable.

        Raises:
            :exc:`KeyError`:
                If no trial with the matching ``trial_id`` exists.
            :exc:`~optuna.exceptions.UpdateFinishedTrialError`:
                If the trial is already finished.
        r   r   r9   r    r!   s       r   set_trial_user_attrzBaseStorage.set_trial_user_attr  r7   r   c                    t         )a  Set an optuna-internal attribute to a trial.

        This method overwrites any existing attribute.

        Args:
            trial_id:
                ID of the trial.
            key:
                Attribute key.
            value:
                Attribute value. It should be JSON serializable.

        Raises:
            :exc:`KeyError`:
                If no trial with the matching ``trial_id`` exists.
            :exc:`~optuna.exceptions.UpdateFinishedTrialError`:
                If the trial is already finished.
        r   r\   s       r   set_trial_system_attrz!BaseStorage.set_trial_system_attr  r7   r   c                    t         )a  Read a trial.

        Args:
            trial_id:
                ID of the trial.

        Returns:
            Trial with a matching trial ID.

        Raises:
            :exc:`KeyError`:
                If no trial with the matching ``trial_id`` exists.
        r   rK   s     r   rI   zBaseStorage.get_trial  r(   r   c                    t         )aI  Read all trials in a study.

        Args:
            study_id:
                ID of the study.
            deepcopy:
                Whether to copy the list of trials before returning.
                Set to :obj:`True` if you intend to update the list or elements of the list.
            states:
                Trial states to filter on. If :obj:`None`, include all states.

        Returns:
            List of trials in the study, sorted by ``trial_id``.

        Raises:
            :exc:`KeyError`:
                If no study with the matching ``study_id`` exists.
        r   )r   r   r?   statess       r   r@   zBaseStorage.get_all_trials  s
    2 "!r   c                b    t        |t              r|f}t        | j                  |d|            S )a  Count the number of trials in a study.

        Args:
            study_id:
                ID of the study.
            state:
                Trial states to filter on. If :obj:`None`, include all states.

        Returns:
            Number of trials in the study.

        Raises:
            :exc:`KeyError`:
                If no study with the matching ``study_id`` exists.
        Fr?   rb   )
isinstancer   rA   r@   )r   r   rT   s      r   get_n_trialszBaseStorage.get_n_trials  s2    ( eZ(HE4&&x%&NOOr   c                >   | j                  |dt        j                  g      }t        |      dk(  rt	        d      | j                  |      }t        |      dkD  rt        d      |d   }|t        j                  k(  rt        |d       }|S t        |d	       }|S )
aS  Return the trial with the best value in a study.

        This method is valid only during single-objective optimization.

        Args:
            study_id:
                ID of the study.

        Returns:
            The trial with the best objective value among all finished trials in the study.

        Raises:
            :exc:`KeyError`:
                If no study with the matching ``study_id`` exists.
            :exc:`RuntimeError`:
                If the study has more than one direction.
            :exc:`ValueError`:
                If no trials have been completed.
        Frd   r   zNo trials are completed yet.   zBBest trial can be obtained only for single-objective optimization.c                6    t        t        | j                        S Nr   floatr!   ts    r   <lambda>z,BaseStorage.get_best_trial.<locals>.<lambda>$      tE1777K r   )r    c                6    t        t        | j                        S rj   rk   rm   s    r   ro   z,BaseStorage.get_best_trial.<locals>.<lambda>&  rp   r   )r@   r   COMPLETErA   
ValueErrorr,   RuntimeErrorr   MAXIMIZEmaxmin)r   r   
all_trialsr   	direction
best_trials         r   get_best_trialzBaseStorage.get_best_trial  s    ( ((E:K^K^J_(`
z?a;<<..x8
z?QT  qM	///Z-KLJ  Z-KLJr   c                8    | j                  |      j                  S )a  Read the parameter dictionary of a trial.

        Args:
            trial_id:
                ID of the trial.

        Returns:
            Dictionary of a parameters. Keys are parameter names and values are external
            representations of the parameter values.

        Raises:
            :exc:`KeyError`:
                If no trial with the matching ``trial_id`` exists.
        )rI   rP   rK   s     r   get_trial_paramszBaseStorage.get_trial_params*  s     ~~h'...r   c                8    | j                  |      j                  S )aD  Read the user-defined attributes of a trial.

        Args:
            trial_id:
                ID of the trial.

        Returns:
            Dictionary with the user-defined attributes of the trial.

        Raises:
            :exc:`KeyError`:
                If no trial with the matching ``trial_id`` exists.
        )rI   
user_attrsrK   s     r   get_trial_user_attrsz BaseStorage.get_trial_user_attrs;  s     ~~h'222r   c                8    | j                  |      j                  S )aJ  Read the optuna-internal attributes of a trial.

        Args:
            trial_id:
                ID of the trial.

        Returns:
            Dictionary with the optuna-internal attributes of the trial.

        Raises:
            :exc:`KeyError`:
                If no trial with the matching ``trial_id`` exists.
        )rI   system_attrsrK   s     r   get_trial_system_attrsz"BaseStorage.get_trial_system_attrsK  s     ~~h'444r   c                     y)z'Clean up all connections to a database.N r2   s    r   remove_sessionzBaseStorage.remove_session[  s    r   c                    |j                         r5| j                  |      }t        dj                  |j                              y)aj  Check whether a trial state is updatable.

        Args:
            trial_id:
                ID of the trial.
                Only used for an error message.
            trial_state:
                Trial state to check.

        Raises:
            :exc:`~optuna.exceptions.UpdateFinishedTrialError`:
                If the trial is already finished.
        z5Trial#{} has already finished and can not be updated.N)is_finishedrI   r
   rC   rJ   )r   r9   trial_staterQ   s       r   check_trial_is_updatablez$BaseStorage.check_trial_is_updatable_  sB     ""$NN8,E*GNNu||\  %r   rj   )r   zSequence[StudyDirection]r   z
str | Nonereturnint)r   r   r   None)r   r   r    strr!   r   r   r   )r   r   r    r   r!   r   r   r   )r   r   r   r   )r   r   r   r   )r   r   r   zlist[StudyDirection])r   r   r   dict[str, Any])r   zlist[FrozenStudy])r   r   r5   zFrozenTrial | Noner   r   )
r9   r   r:   r   r;   rl   r<   r	   r   r   )r   r   rE   r   r   r   )r9   r   r   r   )r9   r   r:   r   r   rl   )r9   r   rT   r   rU   zSequence[float] | Noner   bool)r9   r   rX   r   rY   rl   r   r   )r9   r   r    r   r!   r   r   r   )r9   r   r    r   r!   r   r   r   )r9   r   r   r   )TN)r   r   r?   r   rb   zContainer[TrialState] | Noner   zlist[FrozenTrial])r   r   rT   z*tuple[TrialState, ...] | TrialState | Noner   r   )r   r   r   r   )r9   r   r   r   )r   r   )r9   r   r   r   r   r   )"__name__
__module____qualname____doc__abcabstractmethodr   r   r"   r%   r'   r*   r,   r.   r0   r3   r6   r=   rG   rL   rR   rV   rZ   r]   r_   rI   r@   rf   r{   r}   r   r   r   r   r   r   r   r   r      s   : 	MQ"2"@J"	" "2 	" " 	" "& 	" "* 	" "  	" "  	" "  	" "  	" "  	" " 	" "* 	"" " $	"
 '" 
" "6.2/(Z( 	QU""$."8N"	" "> 	""#&"<A"	" ". 	" "* 	" ". 	" "  	 /3	"" " -	"
 
" "6 RVPP$NP	P0%N/"3 5 r   r   )
__future__r   r   collections.abcr   r   typingr   r   optuna._typingr   optuna.distributionsr	   optuna.exceptionsr
   optuna.study._frozenr   optuna.study._study_directionr   optuna.trialr   r   DEFAULT_STUDY_NAME_PREFIXABCr   r   r   r   <module>r      sF    " 
 % $   + 1 6 , 8 $ # ' \	#'' \	r   