o
    rric9                     @   s  U d Z ddlmZ ddlmZmZ ddlZddlmZ ddl	Z	ddl
mZ ddlZddlZddlZddlZddlmZmZmZ dd	lmZmZmZ dd
lmZ ddlmZmZmZ ddlm Z m!Z! ddl"m#Z#m$Z$m%Z% ddl&Z'eedZej(e)gdf e*d< dd Z+eG dd dZ,dd Z-dej.defddZ/e de, fdedede)dedej0e de,dej1e  fdd Z2d!d" Z3d#ej1e) ded$ej1e  dej1e  fd%d&Z4dej.deded'ej1e  d(ej(de5fd)d*Z6dS )+z
This defines the `dora grid` action, and provides a `run_grid` API
that can be used from a notebook or any other script.

When using the API, you can provide the equivalent of the command line flags
with the `RunGridArgs` dataclass.
    )ProcessPoolExecutor)	dataclassfieldN)partial)Path   )SlurmConfigSubmitRulesupdate_from_args)ExplorerLauncherHerd)DecoratedMain)colorize
simple_logfatal)SheepShepherd)import_or_fatalreliable_rmtreetry_loadzGrid:logc                  O   s   d S N )argskwargsr   r   =/home/ubuntu/.local/lib/python3.10/site-packages/dora/grid.pyno_print%   s   r   c                   @   s   e Zd ZU dZeedZeje	 e
d< dZee
d< dZee
d< dZeje e
d	< d
Zee
d< d
Zee
d< d
Zee
d< d
Zee
d< d
Zee
d< d
Zeje e
d< d
Zee
d< dZeje e
d< dZeje e
d< dZeje e
d< d
Zee
d< dS )RunGridArgsay  
    Arguments to tune the behavior of the `run_grid` function.

    Args:
        patterns (list[str]): List of patterns used to filter by name
            the XPs.
        monitor (bool): if True, will monitor the advances of the XPs
            every `interval` minutes, stopping only when all runs completed or
            failed.
        interval (float): interval in minutes to wait between updates.
        trim (int or None): if provided, will trim all XP logs to the epoch of
            the XP with the provided index. Useful to compare XP started at different
            times.
        trim_last (bool): if True, will trim all XP to the least advanced XP.
        silent (bool): if True, do not print anything (e.g. API usage).
        dry_run (bool): if True, Dora will simulate the run of the grid, without scheduling
            or canceling any XP.
        cancel (bool): if True, will cancel all XPs in the grid. If `patterns` is provided,
            only XP matching the patterns will be canceled.
        clear (bool): This will cancel any previous job, clear the XP folder,
            and reschedule a new experiment.

    )default_factorypatternsTmonitor   intervalNtrimF	trim_lastsilentdry_runcancelclearinitjupyterfolderr   tail_from_commandline)__name__
__module____qualname____doc__r   listr    tpListstr__annotations__r!   boolr#   floatr$   Optionalintr%   r&   r'   r(   r)   r*   r+   r,   r   r-   r.   r   r   r   r   r   )   s"   
 r   c                 C   s  |j j}|d u r|jd }t|}| jd ur'| jddd }t|jj| }| jd u s0|	 sg }t|jj}t
|D ]0\}}	}
|
D ](}t|| |}|jdrl|jdsl|j|j }|t|dd qDq=| jd ur|	 std| d| d td	d
|  td |d | j }t|}z|j}W n ty   t| d Y nw t|tst| d |S )Nz.grids./z.py_zNo grid file z in package z. Maybe you made a typo?zPotential grids are: z, r   z( has no exploration function `explorer`.z' must be an instance of `dora.Explorer`)doragrid_packagepackager   gridreplacer   __file__parentexistsoswalkrelative_tonameendswith
startswithstemappendr6   r   joinsysexitexplorerAttributeErrorr   
isinstancer   )r   mainr@   gridsgrid_filename	grid_file
candidatespkg_rootrootfoldersfilesfilefullpath	grid_namerB   rR   r   r   r   _get_explore[   s@   




ra   r   rU   c                 C   sZ   t | |}| }t||  t }t||  t }d|_t||  t||| j||| d S )NT)ra   get_slurm_configr
   r	   r   r.   run_gridrB   )r   rU   rR   slurmrules	grid_argsr   r   r   grid_action   s   



rg   rR   r`   re   rd   returnc           "         s  t |tsJ |du r|  }| jj| jj | }|jddd t }t| t	d}| j
rQtd}	t||||	d}
||
 |  W d   n1 sKw   Y  n
t|||}
||
 |  t|j }t|j| |}|jr|jrwtd t	dt| d	| d
 |jrtd}| dkrtd t	d |D ]}|jdur||j q|  t	d |D ]}|jj  rt!|jj d|_qg }g }|" D ]g}|j#|jvr4|$| z|%|j#}W nD t&y' } z7t	d|j# d|  || jj'j( }t)|}|dur|d }t	d|j* d|j# d || W Y d}~qd}~ww |dus/J |$| q|  |j+sdd |D  |j,D ]O} fdd|D }|sWqG|d }|j-|jj. }t|dkrr|/||| qG|0| |D ]
}|/||| qzW d   n	1 sw   Y  qG|D ]-}|1 s|jdusJ ||j | 2|j}t	d|jj* d|jj. d|  q|j+r|D ]-}|1 s|jdusJ | 2|j}t	d|jj* d|jj. d|  ||j q|js>|D ].}||jj. }|  s|3 r'|3 r#|4 |jj4 ks%J q|5|jj q|  |D ]}|6  q6|j7rN|D ]	}| 8|j qD|j+rT|S |s]t	d |S dd |j|j	|j9fD }|r|jsut:d t|dks~J |d }z|| }W n t;y   td!|j  Y nw | 2|j}|jdurt<|jj |S |j9dur|j	  std"|j	 d# t=>d$d$d%d&d'|j	g |S |j	  std(| d zt?@tA|j	tBjC W |S  tDy   Y |S w |jEr tF}nt<}|d)|  	 |jGr|jEsdd*lHmI} |jJdd+ |  tK|| |||r.	 |S |jKs5	 |S tL|jMd, }|  tN|D ]#} d-||  d.d/}!||  d0k rZtO|!d1}!||!d2d3 tPQd qC|d4 q
)5a  
    Run a grid search, this is the API underlying the `dora grid` command,
    so that it can be used from a notebook.
    You can also provide patterns to filter out XPs to be displayed.

    Args:
        main (DecoratedMain): main training function, decorated with Dora.
        explorer (Explorer): explorer instance that will define the XPs to launch.
        grid_name (str): this must be a unique name for the grid.
        rules (SubmitRules): see `dora.conf.SubmitRules`, those defines the
            rules for rescheduling failed XP etc.
        slurm (SlurmConfig or None): if provided, this will override
            the default Slurm config defined my the `main` argument.

    Returns:
        A list of `dora.shep.Sheep`.

    NT)exist_okparents)r      )poolz'--dry_run is incompatible with --clear.zYou are about to restart z experiments from the grid z' from scratch. This cannot be reverted.zConfirm [yN]: yzAbort...zCanceling all current jobs...zDeleting XP folders...z$Error when trying to load old sheep z: r   zCanceling job z from unloadable sheep r<   c                 S   s   i | ]}|j j|qS r   )xpsig.0sheepr   r   r   
<dictcomp>   s    zrun_grid.<locals>.<dictcomp>c                    s   g | ]
}| v r | qS r   r   )rq   ro   	sheep_mapr   r   
<listcomp>   s    zrun_grid.<locals>.<listcomp>r   z for no longer required sheep r=   z for sheep zNo sheep to handle.c                 S   s   g | ]}|d ur|qS r   r   )rq   actionr   r   r   rv         zIThe folder, log, and tail flags are only supported from the command line.zInvalid index zLog z does not existr-   z-n200z-fz"Log file does not exist for sheep zMonitoring Grid )display)wait<   zNext update in z.0fz seconds       
   31)endz<                                                            )RrT   r   rb   r?   dir_gridsmkdirr   r   r   _slowr   r   completeupdater3   sheepsvalues_filter_grid_sheepsr    r)   r'   r   lenr.   inputlowerjobcancel_lazycommitrn   r,   rF   r   iterdirrJ   rN   get_sheep_from_sig	Exceptionshepjob_filer   job_idr(   
job_arraysslurm_configsro   maybe_submit_lazy	job_arrayis_doneget_name
is_symlinkresolve
symlink_tounlinkr*   init_xpr-   RuntimeError
IndexErrorprintrG   execvpshutilcopyfileobjopenrP   stdoutBrokenPipeErrorr&   r   r+   IPythonrz   clear_outputr!   r;   r#   ranger   timesleep)"rU   rR   r`   re   rd   r   grid_folderherdshepherdrl   launcherr   replrr   	to_unlink
old_sheepschild	old_sheeperrorr   jobsr   r   array_sheepsfirstrJ   linkactionsindexmaybe_printrz   r   elaoutr   rt   r   rc      sJ  










"(

rc   c                 C   sh   |sdS |D ]+}d}|d d dkr|dd  }d}t  | d| d }|r,|r+ dS q|s1 dS qdS )NTFr   !*)fnmatch)rJ   r    patternnegresultr   r   r   _match_nameP  s    r   r    r   c              	      s   g }t | D ]}z	|t| W n	 ty   Y qw | | qg  |D ]}||j}t|| r7 | q%|rC fdd|D   S )Nc                    s   g | ]} | qS r   r   )rq   idxr   r   r   rv   q  s    z'_filter_grid_sheeps.<locals>.<listcomp>)r3   rN   r;   
ValueErrorremover   rn   r   )r    rU   r   indexesprr   rJ   r   r   r   r   a  s"   

r   r   r   c              	      s    dd |D \}} fdd|D }d| jdur$t|| j n| jr0tdd |D dur=fdd|D }g }d}	tt|||D ]V\}
\}}}| }| sZd	}	|du rad
}n|dd }||
|j	rp|j	j
nd|jj|d}i }||d< z|||}W n ty   ||}Y nw || || qI|r|d| tjdtd| g|  d}|tj||| d |	S )zSingle iteration of monitoring of the jobs in a Grid.
    Returns `True` if all jobs are done or failed, and `False` otherwise.
    c                 S   s   g | ]}|j qS r   )rn   rp   r   r   r   rv   z  s    zmonitor.<locals>.<listcomp>c                    s   g | ]}  |jqS r   )get_xp_historyrn   rp   )rU   r   r   rv   {  rx   Nc                 s   s    | ]}t |V  qd S r   )r   rq   metricsr   r   r   	<genexpr>  s    zmonitor.<locals>.<genexpr>c                    s   g | ]}|d   qS r   r   r   )r$   r   r   rv     rx   TFzN/A    )rJ   r   sidro   stateMetazBase name: )shortengroups)colors)	get_namesr$   r   r%   min	enumeratezipr   r   r   r   rn   ro   process_sheepNotImplementedErrorprocess_historyr   rN   tttablegroupget_grid_metaget_grid_metrics	treetable
get_colors)r   rU   rR   r   r   names	base_name	historieslinesfinishedr   rr   historyrJ   r   metalineotherr   r   )rU   r$   r   r!   u  sX   


r!   )7r2   concurrent.futuresr   dataclassesr   r   r   	functoolsr   rG   pathlibr   typingr4   r   rP   r   confr   r	   r
   explorer   r   r   rU   r   r   r   r   r   r   r   r   utilsr   r   r   r   r   Callabler6   r7   r   r   ra   Anyrg   r:   r5   rc   r   r   r8   r!   r   r   r   r   <module>   s^   1&
 D
