o
    ci'                     @   s  d dl Z 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
 d dlZd dlZd dlmZ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mZmZ e eZe ddZ!dZ"ee Z#dZ$ej%dd\Z&Z'ej(ej)ej*ej+ej,ej-dZ.dd Z/dd Z0						d(de1de
e	e1  de
e1 de
e1 de
e	e1  de2de3fddZ4						d(d e1de
e	e1  de1de1de
e	e1  de2de3fd!d"Z5d)d$e1d%e1fd&d'Z6dS )*    N)datetime)Path)ListOptional)is_numeric_dtypeis_string_dtype)tabulateEXPR_RESULT_FILE)	TuneError)ExperimentAnalysis)CONFIG_PREFIXDEFAULT_EXPERIMENT_INFO_KEYSDEFAULT_RESULT_KEYSEDITORvimz%Y-%m-%d %H:%M:%S (%A))nametotal_trialslast_updated)d   r   )fallback)<z<=z==z!=z>=>c                   C   s   t du rtddS )z%Checks whether tabulate is installed.Nz:Tabulate not installed. Please run `pip install tabulate`.)r   ImportError r   r   I/home/ubuntu/.local/lib/python3.10/site-packages/ray/tune/cli/commands.py_check_tabulate2   s   r   c                 C   s   t  }g }g }t| D ]=\}}| |   r||g7 }q| | ||< t|ddd}t|dtkrI|j	|ddd |t
| j|d 7 } nqt|ddd	d
}t| |rgtjd|dd td |rstjd|dd |||fS )zPrints output of given dataframe to fit into terminal.

    Returns:
        table: Final outputted dataframe.
        dropped_cols: Columns dropped due to terminal size.
        empty_cols: Empty columns (dropped on default).
    keyspsql)headerstablefmt
   T)axisinplaceNnever)r   r    	showindexzDropped columns: {}yellowfgz=Please increase your terminal size to view remaining columns.zEmpty columns: {})pd	DataFrame	enumerateisnullallr   strindex
TERM_WIDTHdroplistcolumnsprintclicksechoformat)	dataframeprint_dfdropped_cols
empty_colsicol
test_tabletabler   r   r   print_format_output8   s,   


rA   Fexperiment_pathsortoutput	filter_op	info_keyslimitdescc              
      sn  t   zt|  }W n ty } ztd|d}~ww td   fddfdd|jD }	rRD ]}
|
|jvrGtd|
|jq6fd	d|jD }	|	sYtd
||	 }d|v rt	
dd |d  }W d   n1 sxw   Y  |dd }||d< d|v r|d j| d|d< |r|d\}}}|| j}t|rt|}nt|rt|}n	td||t| }||| |}|| }|r|D ]}||vrtd|t|q| }|j||d}|r|d| }t| |r5tj|d  }|dv r|| n|dkr!|j|dd ntd|tjd|dd dS dS )a	  Lists trials in the directory subtree starting at the given path.

    Args:
        experiment_path: Directory where trials are located.
            Like Experiment.local_dir/Experiment.name/experiment*.json.
        sort: Keys to sort by.
        output: Name of file where output is saved.
        filter_op: Filter operation in the format
            "<column> <operator> <value>".
        info_keys: Keys that are displayed.
        limit: Number of rows to display.
        desc: Sort ascending vs. descending.
    zNo trial data found!N/c                    s   | t v p|  S N)DEFAULT_CLI_KEYS
startswith)k)config_prefixr   r   
key_filter}   s   zlist_trials.<locals>.key_filterc                    s   g | ]} |r|qS r   r   .0rM   )rO   r   r   
<listcomp>       zlist_trials.<locals>.<listcomp>z-Provided key invalid: {}. Available keys: {}.c                       g | ]}| v r|qS r   r   rP   )rF   r   r   rR      rS   zNo columns to output.last_update_timezmode.use_inf_as_nullTc                 S   s   t | tS rJ   )r   fromtimestampstrftimeTIMESTAMP_FORMAT)tr   r   r   <lambda>   s    zlist_trials.<locals>.<lambda>logdir  Unsupported dtype for {}: {}{} not in: {}by	ascendingr"   z.pz.pklz.pickle.csvFr0   Unsupported filetype: {}Output saved at {}greenr(   )r   r   r9   r   r6   ClickExceptionr   r4   r8   r*   option_contextdropnaapplyr/   replacesplitdtyper   floatr   	OPERATORSr3   sort_valuesrA   ospathsplitextlower	to_pickleto_csvr7   )rB   rC   rD   rE   rF   rG   rH   checkpoints_dfecol_keysrM   datetime_seriesr>   opvalcol_typefiltered_indexkeyrb   file_extensionr   )rN   rF   rO   r   list_trials^   s   









r   project_pathc              	      s  t   tt| \}}}	g }
|D ]}tdd ttj||D }||d}|
| q|
s6t	dt
|
 |s?t} fddt|D }|sTt	d| |  |r|d\}}} | j}t|rpt|}nt|ryt|}n	t	d	||t| }| | |} |  |r|D ]}| vrt	d
|t q| } j||d |r d|  t  |rtj|d  }|dv rӈ | n|dkr߈ j|dd nt	d|tjd|dd dS dS )a  Lists experiments in the directory subtree.

    Args:
        project_path: Directory where experiments are located.
            Corresponds to Experiment.local_dir.
        sort: Keys to sort by.
        output: Name of file where output is saved.
        filter_op: Filter operation in the format
            "<column> <operator> <value>".
        info_keys: Keys that are displayed.
        limit: Number of rows to display.
        desc: Sort ascending vs. descending.
    c                 s   s    | ]
\}}}t |v V  qd S rJ   r	   )rQ   _filesr   r   r   	<genexpr>   s
    
z#list_experiments.<locals>.<genexpr>)r   r   zNo experiments found!c                    rT   r   r   rP   info_dfr   r   rR      rS   z$list_experiments.<locals>.<listcomp>z#None of keys {} in experiment data!r]   r^   r_   r`   Nr"   rc   rd   Fre   rf   rg   rh   r(   )r   nextrs   walksumrt   joinappendr6   ri   r*   r+   DEFAULT_PROJECT_INFO_KEYSr3   r8   rn   ro   r   rp   r   r/   rq   rr   rA   ru   rv   rw   rx   r7   )r   rC   rD   rE   rF   rG   rH   baseexperiment_foldersr   experiment_data_collectionexperiment_dir
num_trialsexperiment_datar{   r>   r}   r~   r   r   r   rb   r   r   r   r   list_experiments   sh   






r   note.txtrt   filenamec              
   C   s   t |  } |  sJ d| | | }ztt| g W n ty> } zt	j
dt|dd W Y d}~nd}~ww | rLtd|  dS td|  dS )zOpens a txt file at the given path where user can add and save notes.

    Args:
        path: Directory where note will be saved.
        filename: Name of note. Defaults to "note.txt"
    z{} is not a valid directory.zEditing note failed: {}redr(   NzNote updated at:zNote created at:)r   
expanduseris_dirr8   
subprocesscallr   as_posix	Exceptionr6   r7   r/   existsr5   )rt   r   filepathexcr   r   r   add_note  s   $r   )NNNNNF)r   )7loggingoperatorrs   shutilr   r   pathlibr   typingr   r   r6   pandasr*   pandas.api.typesr   r   )ray._private.thirdparty.tabulate.tabulater   ray.air.constantsr
   ray.tuner   ray.tune.analysisr   ray.tune.resultr   r   r   	getLogger__name__loggergetenvr   rX   rK   r   get_terminal_sizer1   TERM_HEIGHTltleeqnegegtrq   r   rA   r/   intboolr   r   r   r   r   r   r   <module>   s    

(


k


X