o
    $io+                     @   s   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	m
Z
mZmZmZmZ d dlZd dlZd dlZd dlmZ d dlmZmZmZ d dlmZ eeZeedd	G d
d dZdS )    N)	dataclass)Path)AnyDictListOptionalTupleUnionunflattened_lookup)EXPR_ERROR_PICKLE_FILEEXPR_PROGRESS_FILEEXPR_RESULT_FILE)	PublicAPIstable	stabilityc                   @   s^  e Zd ZU dZeeeef  ed< ed ed< ee	 ed< eed< dZ
ed ed	< dZeeedeeef f   ed
< dZeejj ed< g dZedeeeef  fddZedejjfddZd$dedefddZdefddZedejjdedefddZe	d%deeejf deejj dd fddZe ddd ed!eded fd"d#Z!dS )&Resulta{  The final result of a ML training run or a Tune trial.

    This is the output produced by ``Trainer.fit``.
    ``Tuner.fit`` outputs a :class:`~ray.tune.ResultGrid` that is a collection
    of ``Result`` objects.

    This API is the recommended way to access the outputs such as:
    - checkpoints (``Result.checkpoint``)
    - the history of reported metrics (``Result.metrics_dataframe``, ``Result.metrics``)
    - errors encountered during a training run (``Result.error``)

    The constructor is a private API -- use ``Result.from_path`` to create a result
    object from a directory.

    Attributes:
        metrics: The latest set of reported metrics.
        checkpoint: The latest checkpoint.
        error: The execution error of the Trainable run, if the trial finishes in error.
        path: Path pointing to the result directory on persistent storage. This can
            point to a remote storage location (e.g. S3) or to a local location (path
            on the head node). The path is accessible via the result's associated
            `filesystem`. For instance, for a result stored in S3 at
            ``s3://bucket/location``, ``path`` will have the value ``bucket/location``.
        metrics_dataframe: The full result dataframe of the Trainable.
            The dataframe is indexed by iterations and contains reported
            metrics. Note that the dataframe columns are indexed with the
            *flattened* keys of reported metrics, so the format of this dataframe
            may be slightly different than ``Result.metrics``, which is an unflattened
            dict of the latest set of reported metrics.
        best_checkpoints: A list of tuples of the best checkpoints and
            their associated metrics. The number of
            saved checkpoints is determined by :class:`~ray.train.CheckpointConfig`
            (by default, all checkpoints will be saved).
    metricszray.tune.Checkpoint
checkpointerrorpathNzpd.DataFramemetrics_dataframebest_checkpoints_storage_filesystem)r   r   r   
filesystemr   returnc                 C   s   | j sdS | j ddS )z&The config associated with the result.Nconfig)r   getself r!   K/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/ray/air/result.pyr   I   s   zResult.configc                 C   s   | j ptj S )zReturn the filesystem that can be used to access the result path.

        Returns:
            pyarrow.fs.FileSystem implementation.
        )r   pyarrowfsLocalFileSystemr   r!   r!   r"   r   P   s   zResult.filesystemr   indentc                    s   ddl m} ddlm} fddjD }jr"tjj|d< n|d |d j	|d< j
rHt|  |  fddj
 D |d	< d
| }d
|d  fdd| D }d|}d|tj|S )zCConstruct the representation with specified number of space indent.r   )BLACKLISTED_KEYS)AUTO_RESULT_KEYSc                    s   i | ]}|t  |qS r!   )getattr).0kr   r!   r"   
<dictcomp>^   s    z Result._repr.<locals>.<dictcomp>r   r   c                    s   i | ]\}}| vr||qS r!   r!   )r*   r+   v)excluder!   r"   r,   i   s    r       c                    s"   g | ]\}}  | d |qS )=r!   )r*   keyvalue)
kws_indentr!   r"   
<listcomp>p   s    z Result._repr.<locals>.<listcomp>z,
z{0}{1}(
{2}
{0}))ray.tune.experimental.outputr'   ray.tune.resultr(   _items_to_reprr   type__name__pop	type_namer   setupdateitemsjoinformat)r    r&   r'   r(   shown_attributes
cls_indentkwskws_reprr!   )r.   r4   r    r"   _reprY   s(   





zResult._reprc                 C   s   | j ddS )Nr   )r&   )rF   r   r!   r!   r"   __repr__v   s   zResult.__repr__storage_filesystemstorage_pathc                 C   s:   |  |}|  W  d   S 1 sw   Y  dS )a   Opens a file as an input stream reading all byte content sequentially and
         decoding read bytes as utf-8 string.

        Args:
            storage_filesystem: The filesystem to use.
            storage_path: The source to open for reading.
        N)open_input_streamreadalldecode)rH   rI   fr!   r!   r"   _read_file_as_stry   s   
$zResult._read_file_as_strc              	      s  ddl m  ddlm}m}m} ddlm} |||\|s*td dt	t
 }t	t }||r]| |d}	dd	 |	D }
tj|
d
d}|
rZ|
d ni }n)||r{tt| |}|jsx|jd  ni }ntdt
 dt dt|dd d}|rԇ fdd	|D }g }|D ]%}||| |k }|jrtd| d ||jri n|jd   q|d }tt||}nd }}d}t	t }||r|}tj !|}W d   n1 sw   Y  t"|||||dS )a3  Restore a Result object from local or remote trial directory.

        Args:
            path: A path of a trial directory on local or remote storage
                (ex: s3://bucket/path or /tmp/ray_results).
            storage_filesystem: A custom filesystem to use. If not provided,
                this will be auto-resolved by pyarrow. If provided, the path
                is assumed to be prefix-stripped already, and must be a valid path
                on the filesystem.

        Returns:
            A :py:class:`Result` object of that trial.
        r   )
Checkpoint)_exists_at_fs_path_list_at_fs_pathget_fs_and_path)CHECKPOINT_DIR_NAMEzTrial folder z doesn't exist!
c                 S   s   g | ]	}|rt |qS r!   )jsonloads)r*   liner!   r!   r"   r5      s    z$Result.from_path.<locals>.<listcomp>/)sepz-Failed to restore the Result object: Neither z nor z exists in the trial folder!c                 S   s   | j tjjjko| jdS )Ncheckpoint_)r9   r#   r$   FileType	Directory	base_name
startswith)	file_infor!   r!   r"   <lambda>   s    z"Result.from_path.<locals>.<lambda>)file_filterc                    s"   g | ]} t | d qS ))r   r   )r   as_posix)r*   checkpoint_dir_namerO   r$   fs_pathr!   r"   r5      s    z(Could not find metrics corresponding to z&. These will default to an empty dict.N)r   r   r   r   r   r   r   )#	ray.trainrO   ray.train._internal.storagerP   rQ   rR   ray.train.constantsrS   RuntimeErrorr   r   rc   r   rN   splitpdjson_normalizeread_csvioStringIOemptyilocto_dictsortedloggerwarningappendlistzipr   rJ   raycloudpickleloadr   )clsr   rH   rP   rQ   rR   rS   result_json_fileprogress_csv_filelines	json_list
metrics_dflatest_metricscheckpoint_dir_namescheckpointsr   rd   #metrics_corresponding_to_checkpointlatest_checkpointr   r   error_file_pathrM   r!   re   r"   	from_path   s   




zResult.from_pathalphar   metricmodec                    s   | j std|dvrtd| d|dkrtnt} fdd| j D }|s5td  d	| j  d
|| fdddd S )a  Get the best checkpoint from this trial based on a specific metric.

        Any checkpoints without an associated metric value will be filtered out.

        Args:
            metric: The key for checkpoints to order on.
            mode: One of ["min", "max"].

        Returns:
            :class:`Checkpoint <ray.train.Checkpoint>` object, or None if there is
            no valid checkpoint associated with the metric.
        z,No checkpoint exists in the trial directory!)maxminzUnsupported mode: z$. Please choose from ["min", "max"]!r   c                    s&   g | ]}t  |d  dddur|qS )   N)defaultr
   )r*   	ckpt_infor   r!   r"   r5     s
    z.Result.get_best_checkpoint.<locals>.<listcomp>zInvalid metric name z-! You may choose from the following metrics: .c                    s   t  | d S )Nr   r
   )xr   r!   r"   ra     s    z,Result.get_best_checkpoint.<locals>.<lambda>)r2   r   )r   rj   
ValueErrorr   r   r   keys)r    r   r   opvalid_checkpointsr!   r   r"   get_best_checkpoint   s"   

zResult.get_best_checkpoint)r   )N)"r:   
__module____qualname____doc__r   r   strr   __annotations__	Exceptionr   r   r   r   r   r#   r$   
FileSystemr8   propertyr   r   intrF   rG   staticmethodrN   classmethodr	   osPathLiker   r   r   r!   r!   r!   r"   r      sX   
 #
pr   )ro   rU   loggingr   dataclassesr   pathlibr   typingr   r   r   r   r   r	   pandasrl   r#   rz   ray._private.dictr   ray.air.constantsr   r   r   ray.util.annotationsr   	getLoggerr:   ru   r   r!   r!   r!   r"   <module>   s"     
