o
    /wiK                     @  s   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 dejZdS )    )annotationsN)	Container)Sequence)Any)cast)JSONSerializable)BaseDistribution)UpdateFinishedTrialError)FrozenStudy)StudyDirection)FrozenTrial)
TrialStatezno-name-c                   @  s  e Zd ZdZej	dcddd	d
ZejdeddZejdfddZejdgddZ	ejdhddZ
ejdiddZejdjddZejdkd d!Zejdkd"d#Zejdld%d&Zejdcdmd)d*Zejdnd1d2Zdod4d5Zdpd6d7Zdqd8d9Zej	dcdrd?d@ZejdsdCdDZejdtdEdFZejdudGdHZejdvdJdKZej	L	dwdxdQdRZ	dcdydTdUZdzdVdWZd{dXdYZd{dZd[Zd{d\d]Zd|d^d_Z d}dadbZ!dS )~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.
    N
directionsSequence[StudyDirection]
study_name
str | Nonereturnintc                 C     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)selfr   r    r   R/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/optuna/storages/_base.pycreate_new_study3   s   zBaseStorage.create_new_studystudy_idNonec                 C  r   )zDelete a study.

        Args:
            study_id:
                ID of the study.

        Raises:
            :exc:`KeyError`:
                If no study with the matching ``study_id`` exists.
        r   r   r   r   r   r   delete_studyM   s   zBaseStorage.delete_studykeystrvaluer   c                 C  r   )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   r    r"   r   r   r   set_study_user_attr[      zBaseStorage.set_study_user_attrr   c                 C  r   )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#   r   r   r   set_study_system_attro   r%   z!BaseStorage.set_study_system_attrc                 C  r   )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   r   r   r   get_study_id_from_name      z"BaseStorage.get_study_id_from_namec                 C  r   )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   r   r   r   get_study_name_from_id   r(   z"BaseStorage.get_study_name_from_idlist[StudyDirection]c                 C  r   )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   r   r   r   get_study_directions   r(   z BaseStorage.get_study_directionsdict[str, Any]c                 C  r   )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   r   r   r   get_study_user_attrs   r(   z BaseStorage.get_study_user_attrsc                 C  r   )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   r   r   r   get_study_system_attrs   r(   z"BaseStorage.get_study_system_attrslist[FrozenStudy]c                 C  r   )zRead a list of :class:`~optuna.study.FrozenStudy` objects.

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

        r   r   r   r   r   get_all_studies   s   zBaseStorage.get_all_studiestemplate_trialFrozenTrial | Nonec                 C  r   )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   r2   r   r   r   create_new_trial      zBaseStorage.create_new_trialtrial_id
param_nameparam_value_internalfloatdistributionr   c                 C  r   )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   r6   r7   r8   r:   r   r   r   set_trial_param   s   zBaseStorage.set_trial_paramtrial_numberc                 C  s4   | j |dd}t||krtd|||| 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   r<   trialsr   r   r   'get_trial_id_from_study_id_trial_number  s   
z3BaseStorage.get_trial_id_from_study_id_trial_numberc                 C     |  |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   r6   r   r   r   get_trial_number_from_id1  s   z$BaseStorage.get_trial_number_from_idc                 C  s    |  |}|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.
        )rF   distributionsto_internal_reprparams)r   r6   r7   trialr   r   r   get_trial_paramE  s   
zBaseStorage.get_trial_paramstater   valuesSequence[float] | Noneboolc                 C  r   )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   r6   rO   rP   r   r   r   set_trial_state_valuesY  s   z"BaseStorage.set_trial_state_valuesstepintermediate_valuec                 C  r   )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   r6   rT   rU   r   r   r   set_trial_intermediate_valuey  s   z(BaseStorage.set_trial_intermediate_valuec                 C  r   )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   r6   r    r"   r   r   r   set_trial_user_attr  r5   zBaseStorage.set_trial_user_attrc                 C  r   )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   rW   r   r   r   set_trial_system_attr  r5   z!BaseStorage.set_trial_system_attrr   c                 C  r   )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   rH   r   r   r   rF     r(   zBaseStorage.get_trialTr=   statesContainer[TrialState] | Nonelist[FrozenTrial]c                 C  r   )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=   rZ   r   r   r   r>     s   zBaseStorage.get_all_trials*tuple[TrialState, ...] | TrialState | Nonec                 C  s$   t |tr|f}t| j|d|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=   rZ   )
isinstancer   r?   r>   )r   r   rO   r   r   r   get_n_trials  s   
zBaseStorage.get_n_trialsc                 C  s   | j |dtjgd}t|dkrtd| |}t|dkr#td|d }|tjkr6t	|dd d	}|S t
|d
d 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.
        Fr^   r   zNo trials are completed yet.   zBBest trial can be obtained only for single-objective optimization.c                 S     t t| jS Nr   r9   r"   tr   r   r   <lambda>$      z,BaseStorage.get_best_trial.<locals>.<lambda>)r    c                 S  rb   rc   rd   re   r   r   r   rg   &  rh   )r>   r   COMPLETEr?   
ValueErrorr+   RuntimeErrorr   MAXIMIZEmaxmin)r   r   
all_trialsr   	direction
best_trialr   r   r   get_best_trial  s   

zBaseStorage.get_best_trialc                 C  rE   )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.
        )rF   rL   rH   r   r   r   get_trial_params*  s   zBaseStorage.get_trial_paramsc                 C  rE   )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.
        )rF   
user_attrsrH   r   r   r   get_trial_user_attrs;     z BaseStorage.get_trial_user_attrsc                 C  rE   )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.
        )rF   system_attrsrH   r   r   r   get_trial_system_attrsK  rv   z"BaseStorage.get_trial_system_attrsc                 C  s   dS )z'Clean up all connections to a database.Nr   r0   r   r   r   remove_session[  s   zBaseStorage.remove_sessiontrial_statec                 C  s&   |  r| |}td|jdS )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_finishedrF   r	   rA   rG   )r   r6   rz   rM   r   r   r   check_trial_is_updatable_  s   

z$BaseStorage.check_trial_is_updatablerc   )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   r2   r3   r   r   )
r6   r   r7   r!   r8   r9   r:   r   r   r   )r   r   r<   r   r   r   )r6   r   r   r   )r6   r   r7   r!   r   r9   )r6   r   rO   r   rP   rQ   r   rR   )r6   r   rT   r   rU   r9   r   r   )r6   r   r    r!   r"   r   r   r   )r6   r   r    r!   r"   r   r   r   )r6   r   r   r   )TN)r   r   r=   rR   rZ   r[   r   r\   )r   r   rO   r]   r   r   )r   r   r   r   )r6   r   r   r,   )r   r   )r6   r   rz   r   r   r   )"__name__
__module____qualname____doc__abcabstractmethodr   r   r$   r&   r'   r)   r+   r-   r.   r1   r4   r;   rD   rI   rN   rS   rV   rX   rY   rF   r>   r`   rr   rs   ru   rx   ry   r|   r   r   r   r   r      sj    




'


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   r   <module>   s    