
    &`i(                         d dl mZ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  ed	
           G d d                      ZdS )    )OptionalUnionN)Result)RayTaskError)ExperimentAnalysis)	TuneError)Trial)	PublicAPIbeta)	stabilityc                      e Zd ZdZdefdZedefd            Zede	j
        j        fd            Z	 	 	 	 dd
ee         dee         dededef
dZ	 	 ddee         dee         dej        fdZdefdZdedefdZed             Zed             Zed             Zededeeeef                  fd            ZdedefdZ defdZ!dS )
ResultGrida2  A set of ``Result`` objects for interacting with Ray Tune results.

    You can use it to inspect the trials and obtain the best result.

    The constructor is a private API. This object can only be created as a result of
    ``Tuner.fit()``.

    Example:
    .. testcode::

        import random
        from ray import tune
        def random_error_trainable(config):
            if random.random() < 0.5:
                return {"loss": 0.0}
            else:
                raise ValueError("This is an error")
        tuner = tune.Tuner(
            random_error_trainable,
            run_config=tune.RunConfig(name="example-experiment"),
            tune_config=tune.TuneConfig(num_samples=10),
        )
        try:
            result_grid = tuner.fit()
        except ValueError:
            pass
        for i in range(len(result_grid)):
            result = result_grid[i]
            if not result.error:
                    print(f"Trial finishes successfully with metrics"
                       f"{result.metrics}.")
            else:
                    print(f"Trial failed with error {result.error}.")

    .. testoutput::
        :hide:

        ...

    You can also use ``result_grid`` for more advanced analysis.

    >>> # Get the best result based on a particular metric.
    >>> best_result = result_grid.get_best_result( # doctest: +SKIP
    ...     metric="loss", mode="min")
    >>> # Get the best checkpoint corresponding to the best result.
    >>> best_checkpoint = best_result.checkpoint # doctest: +SKIP
    >>> # Get a dataframe for the last reported results of all of the trials
    >>> df = result_grid.get_dataframe() # doctest: +SKIP
    >>> # Get a dataframe for the minimum loss seen for each trial
    >>> df = result_grid.get_dataframe(metric="loss", mode="min") # doctest: +SKIP

    Note that trials of all statuses are included in the final result grid.
    If a trial is not in terminated state, its latest result and checkpoint as
    seen by Tune will be provided.

    See :doc:`/tune/examples/tune_analyze_results` for more usage examples.
    experiment_analysisc                 P     | _          fd j         j        D              _        d S )Nc                 :    g | ]}                     |          S  )_trial_to_result).0trialselfs     h/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/tune/result_grid.py
<listcomp>z'ResultGrid.__init__.<locals>.<listcomp>O   s4     
 
 
-2D!!%((
 
 
    )_experiment_analysistrials_results)r   r   s   ` r   __init__zResultGrid.__init__J   sA     %8!
 
 
 
6:6O6V
 
 
r   returnc                     | j         j        S )zPath pointing to the experiment 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).)r   experiment_pathr   s    r   r    zResultGrid.experiment_pathS   s     (88r   c                     | j         j        S )zReturn the filesystem that can be used to access the experiment path.

        Returns:
            pyarrow.fs.FileSystem implementation.
        )r   _fsr!   s    r   
filesystemzResultGrid.filesystem[   s     (,,r   NlastTmetricmodescopefilter_nan_and_infc                    t          | j        j                  dk    r%|                     | j        j        d                   S |s| j        j        st          d          |s| j        j        st          d          | j                            ||||          }|s*d|p| j        j         d}||rdnd	z  }t          |          |                     |          S )
a  Get the best result from all the trials run.

        Args:
            metric: Key for trial info to order on. Defaults to
                the metric specified in your Tuner's ``TuneConfig``.
            mode: One of [min, max]. Defaults to the mode specified
                in your Tuner's ``TuneConfig``.
            scope: One of [all, last, avg, last-5-avg, last-10-avg].
                If `scope=last`, only look at each trial's final step for
                `metric`, and compare across trials based on `mode=[min,max]`.
                If `scope=avg`, consider the simple average over all steps
                for `metric` and compare across trials based on
                `mode=[min,max]`. If `scope=last-5-avg` or `scope=last-10-avg`,
                consider the simple average over the last 5 or 10 steps for
                `metric` and compare across trials based on `mode=[min,max]`.
                If `scope=all`, find each trial's min/max score for `metric`
                based on `mode`, and compare trials based on `mode=[min,max]`.
            filter_nan_and_inf: If True (default), NaN or infinite
                values are disregarded and these trials are never selected as
                the best trial.
           r   zNo metric is provided. Either pass in a `metric` arg to `get_best_result` or specify a metric in the `TuneConfig` of your `Tuner`.z|No mode is provided. Either pass in a `mode` arg to `get_best_result` or specify a mode in the `TuneConfig` of your `Tuner`.)r&   r'   r(   r)   z*No best trial found for the given metric: z3. This means that no trial has reported this metricz~, or all values reported for this metric are NaN. To not ignore NaN values, you can set the `filter_nan_and_inf` arg to False..)	lenr   r   r   default_metric
ValueErrordefault_modeget_best_trialRuntimeError)r   r&   r'   r(   r)   
best_trial	error_msgs          r   get_best_resultzResultGrid.get_best_resultd   sA   8 t(/00A55(()B)I!)LMMM 	d7F 	0  
  	D5B 	0   .==1	 > 
 

  	*DET6ED D D 
  & M M 	I y)))$$Z000r   filter_metricfilter_modec                 :    | j                             ||          S )a4  Return dataframe of all trials with their configs and reported results.

        Per default, this returns the last reported results for each trial.

        If ``filter_metric`` and ``filter_mode`` are set, the results from each
        trial are filtered for this metric and mode. For example, if
        ``filter_metric="some_metric"`` and ``filter_mode="max"``, for each trial,
        every received result is checked, and the one where ``some_metric`` is
        maximal is returned.


        Example:

            .. testcode::

                import ray.tune

                def training_loop_per_worker(config):
                    ray.tune.report({"accuracy": 0.8})

                result_grid = ray.tune.Tuner(
                    trainable=training_loop_per_worker,
                    run_config=ray.tune.RunConfig(name="my_tune_run")
                ).fit()

                # Get last reported results per trial
                df = result_grid.get_dataframe()

                # Get best ever reported accuracy per trial
                df = result_grid.get_dataframe(
                    filter_metric="accuracy", filter_mode="max"
                )

            .. testoutput::
                :hide:

                ...

        Args:
            filter_metric: Metric to filter best result for.
            filter_mode: If ``filter_metric`` is given, one of ``["min", "max"]``
                to specify if we should find the minimum or maximum result.

        Returns:
            Pandas DataFrame with each trial as a row and their results as columns.
        )r&   r'   )r   	dataframe)r   r6   r7   s      r   get_dataframezResultGrid.get_dataframe   s*    f (22 { 3 
 
 	
r   c                 *    t          | j                  S N)r-   r   r!   s    r   __len__zResultGrid.__len__   s    4=!!!r   ic                     | j         |         S )z$Returns the i'th result in the grid.)r   )r   r>   s     r   __getitem__zResultGrid.__getitem__   s    }Qr   c                     d | D             S )z)Returns the exceptions of errored trials.c                 *    g | ]}|j         	|j         S r   )errorr   results     r   r   z%ResultGrid.errors.<locals>.<listcomp>   s!    @@@6<@@@@r   r   r!   s    r   errorszResultGrid.errors   s     A@4@@@@r   c                 H    t          d | j        j        D                       S )z%Returns the number of errored trials.c                 <    g | ]}|j         t          j        k    |S r   )statusr	   ERRORr   ts     r   r   z)ResultGrid.num_errors.<locals>.<listcomp>   s&    TTT1AH<S<SQ<S<S<Sr   r-   r   r   r!   s    r   
num_errorszResultGrid.num_errors   s-     TT18TTT
 
 	
r   c                 H    t          d | j        j        D                       S )z:Returns the number of terminated (but not errored) trials.c                 <    g | ]}|j         t          j        k    |S r   )rI   r	   
TERMINATEDrK   s     r   r   z-ResultGrid.num_terminated.<locals>.<listcomp>   s2       8u/// ///r   rM   r!   s    r   num_terminatedzResultGrid.num_terminated   s8      29  
 
 	
r   r   c                     | j         t          j        k    rd S |                                 p|                                 S r<   )rI   r	   rQ   get_pickled_error	get_error)r   s    r   _populate_exceptionzResultGrid._populate_exception   s8    <5+++4&&((=EOO,=,==r   c           	      T   |j         j        }d }|j        r|j        j        }|j        }d |D             }| j        j                            |j                  }t          ||j
                                        |                     |          |j        | j        j        ||          }|S )Nc                 *    g | ]}|j         |j        fS r   )
checkpointmetrics)r   checkpoint_results     r   r   z/ResultGrid._trial_to_result.<locals>.<listcomp>  s4     
 
 
! )+<+DE
 
 
r   )rY   rZ   rC   path_storage_filesystemmetrics_dataframebest_checkpoints)run_metadatacheckpoint_managerlatest_checkpoint_resultrY   best_checkpoint_resultsr   trial_dataframesgettrial_idr   last_resultcopyrV   r\   r#   )r   r   cpmrY   rc   r_   
metrics_dfrE   s           r   r   zResultGrid._trial_to_result   s     3
' 	A5@J"%"=
 
%<
 
 

 .?CCENSS
!%**,,**511 $ 9 =(-
 
 
 r   c                 P    d | D             }d                     |          }d| dS )Nc                 :    g | ]}|                     d           S )   )indent)_reprrD   s     r   r   z'ResultGrid.__repr__.<locals>.<listcomp>  s&    FFFvFLLL22FFFr   z,
zResultGrid<[
z
]>)join)r   all_results_reprs     r   __repr__zResultGrid.__repr__  s;    FFFFF ::&6776 06666r   )NNr%   T)NN)"__name__
__module____qualname____doc__r   r   propertystrr    pyarrowfs
FileSystemr$   r   boolr   r5   pd	DataFramer:   intr=   r@   rF   rN   rR   staticmethodr	   r   r   r   rV   r   rr   r   r   r   r   r      sA       8 8t
/
 
 
 
 9 9 9 9 X9 -GJ1 - - - X- !%"#'?1 ?1?1 sm?1 	?1
 !?1 
?1 ?1 ?1 ?1F (,%)5
 5
}5
 c]5
 
	5
 5
 5
 5
n" " " " " S  V         A A XA 
 
 X
 
 
 X
 >5 >XeI|<S6T-U > > > \>
e     07# 7 7 7 7 7 7r   r   )typingr   r   pandasr}   ry   ray.air.resultr   ray.exceptionsr   ray.tune.analysisr   ray.tune.errorr   ray.tune.experimentr	   ray.utilr
   r   r   r   r   <module>r      s    " " " " " " " "      ! ! ! ! ! ! ' ' ' ' ' ' 0 0 0 0 0 0 $ $ $ $ $ $ % % % % % %       VL7 L7 L7 L7 L7 L7 L7 L7 L7 L7r   