
    Vhc9                        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 Z+e G d d                      Z,d Z-dej.        defdZ/ e            d e,            fdedede)dedej0        e         de,dej1        e          fdZ2d Z3dej1        e)         dedej1        e          dej1        e          fd Z4dej.        deded!ej1        e          d"ej(        de5f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                      d S N )argskwargss     O/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/dora/grid.pyno_printr   %   s    D    c                   ~   e Zd ZU dZ ee          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/   r0   r   r1   r2   r   r    r   r"   r"   )   sK         . #U4888Hbgcl888 GTHe!D"+c
!!!ItFD GTFDE4#D"+d
###GT  $FBK### CS	   !D"+c
!!!#t#####r    r"   c                 p   |j         j        }|
|j        dz   }t          |          }| j        :| j                            dd          dz   }t          |j                  j        |z  }| j        |	                                sCg }t          |j                  j        }t          j        |          D ]\  }}	}
|
D ]}t          |          |z                      |          }|j                            d          r_|j                            d          sE|j        |j        z  }|                    t%          |                              dd                     | j        *|	                                st'          d| d| d           t'          d	d
                    |                      t+          j        d           |dz   | j        z   }t          |          }	 |j        }n"# t0          $ r t3          | d           Y nw xY wt5          |t6                    st3          | 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appendr:   r   joinsysexitexplorerAttributeErrorr   
isinstancer   )r   mainrE   gridsgrid_filename	grid_file
candidatespkg_rootrootfoldersfilesfilefullpath	grid_namerG   rW   s                   r   _get_explorerf   [   so   9)L|h.L))Ey	))#s33e;((/-?	y	 0 0 2 2
''.$&GH$5$5 	G 	G D'5 G G JJ-::8DD=))%00 G9Q9QRU9V9V G'>H%%c(mm&;&;C&E&EFFF	G
 9 )9)9););  ) ) )< ) ) ) * * *;DIIj$9$9;;<<<s"TY.I9%%DF= F F FDDDEEEEEFh)) DBBBCCCOs   %G- -HHr   rZ   c                 &   t          | |          }|                                }t          ||            t                      }t          ||            t	                      }d|_        t          ||            t          ||| j        |||           d S )NT)rf   get_slurm_configr   r
   r"   r2   run_gridrG   )r   rZ   rW   slurmrules	grid_argss         r   grid_actionrm      s    D$''H!!##EUD!!!MMEUD!!!I"&IY%%%T8TYui@@@@@r    rW   re   rk   rj   returnc           	        " t          |t                    sJ ||                                 }| j        j        | j        j        z  |z  }|                    dd           t                      }t          | t                    }| j
        rZt          d          5 }	t          ||||	          }
 ||
           |                                 ddd           n# 1 swxY w Y   nt          |||          }
 ||
           |                                 t          |j                                                  }t%          |j        | |          }|j        r|j        rt-          d           t          dt/          |           d	| d
           |j        r6t3          d          }|                                dk    rt-          d           t          d           |D ]#}|j        |                    |j                   $|                                 t          d           |D ]@}|j        j                                         rtC          |j        j                   d|_        Ag }g }|"                                D ]}|j#        |j        vr|$                    |           	 |%                    |j#                  }|J |$                    |           Z# tL          $ r}t          d|j#         d|            || j        j'        j(        z  }tS          |          }|=|d         }t          d|j*         d|j#         d           |                    |           Y d}~d}~ww xY w|                                 |j+        sd |D             "|j,        D ]}"fd|D             }|s|d         }|j-        |j        j.                 }t/          |          dk    r|/                    |||           ]|0                    |          5  |D ]}|/                    |||           	 ddd           n# 1 swxY w Y   |D ]}|1                                si|j        J |                    |j                   | 2                    |j                  }t          d|j        j*         d|j        j.         d|            |j+        r|D ]}|1                                si|j        J | 2                    |j                  }t          d|j        j*         d|j        j.         d|            |                    |j                   |j        s|D ]}||j        j.        z  }|                                 s|3                                rK|3                                r4|4                                |j        j        4                                k    sJ |5                    |j        j                   |                                 |D ]}|6                                 |j7        r|D ]}| 8                    |j                   |j+        r|S |st          d           |S d |j        |j	        |j9        fD             }|rh|j        stu          d          t/          |          dk    sJ |d         }	 ||         }n'# tv          $ r t-          d|j                    Y nw xY w| 2                    |j                  }|j        ty          |j        j                   n|j9        Q|j	                                         st-          d |j	         d!           t{          j>        d"d"d#d$d%|j	        g           no|j	                                         st-          d&| d           	 t          j@        t          |j	                  t          jC                   n# t          $ r Y nw xY w|S |jE        rt          }ntx          } |d'|            	 |jG        r#|jE        sdd(lHmI} |J                    d)           |                                 t          || |||          rn|jK        snt          |jM        d*z            } |             t          |          D ]F} d+|| z
  d,d-}!|| z
  d.k     rt          |!d/          }! ||!d01           t          jQ        d           G |d2           |S )3a  
    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 rA   c                 (    i | ]}|j         j        |S r   )xpsig.0sheeps     r   
<dictcomp>zrun_grid.<locals>.<dictcomp>   s    ===UUX\5===r    c                 (    g | ]}|v |         S r   r   )ry   rw   	sheep_maps     r   
<listcomp>zrun_grid.<locals>.<listcomp>   s'    TTTs3)CSCSIcNCSCSCSr    r   z for no longer required sheep rB   z for sheep zNo sheep to handle.c                     g | ]}||S r   r   )ry   actions     r   r~   zrun_grid.<locals>.<listcomp>  s    ]]]&&J\vJ\J\J\r    zIThe folder, log, and tail flags are only supported from the command line.zInvalid index zLog z does not existr1   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<                                                            )RrY   r   rh   rD   dir_gridsmkdirr   r   r   _slowr   r   completeupdater7   sheepsvalues_filter_grid_sheepsr$   r-   r+   r   lenr2   inputlowerjobcancel_lazycommitrv   r0   rK   r   iterdirrO   rS   get_sheep_from_sig	Exceptionshepjob_filer   job_idr,   
job_arraysslurm_configsrw   maybe_submit_lazy	job_arrayis_doneget_name
is_symlinkresolve
symlink_tounlinkr.   init_xpr1   RuntimeError
IndexErrorprintrL   execvpshutilcopyfileobjopenrU   stdoutBrokenPipeErrorr*   r   r/   IPythonr   clear_outputr%   r?   r'   ranger   timesleep)#rZ   rW   re   rk   rj   r   grid_folderherdshepherdrs   launcherr   replrz   	to_unlink
old_sheepschild	old_sheeperrorr   jobsr   r   array_sheepsfirstrO   linkactionsindexmaybe_printr   r   elaoutr}   s#                                     @r   ri   ri      s
   * h)))))}%%'')-$)"22Y>KtT22266D#&&&Hz  ## 	t%DAAAHHXMMOOO	 	 	 	 	 	 	 	 	 	 	 	 	 	 	
 HeT22OO$+$$&&''F f==Fz < 	=;<<< 5F 5 5PY 5 5 5 	6 	6 	6! 	")**Dzz||s""j!!!+,,, 	0 	0Ey$$$UY///$%%% 	 	Ex%%'' 1000EIIIJ$$&& - -:T[((U###-$77
CC	 !,,,!!),,,,  . . .P5:PPPPQQQ 49>#::))#q'CYYYEJYYYZZZ((---.	 )" OO; H==f===	 	H 	HITTTTiTTTL  OE&ux|4E<  A%%**5%????''.. H H!- H H 225%GGGGHH H H H H H H H H H H H H H H   4 4	  "" 	4=,,,  ///==..D 3!5 3 3")3 3,03 3 4 4 4 { 0 	0 	0E==?? 0y,,,}}UX..WUY%5WW%(,WWQUWWXXX$$UY///<  	1 	1E%(,.D{{}} 1 1 1 1((XT\\^^ux?V?V?X?X-X-X-XX-X0000 	 	ELLNNNNy # 	# 	#ELL""""{  !"""]]T[$(DI$F]]]G % 	R  Q R R R7||q    
	25MEE 	2 	2 	204;0011111	2}}UX&&;"%(/""""Y"9##%% 97UY777888IfvtUD%)DEEEE9##%% DB4BBBCCC"4	??CJ????"    { K.9..///< 	, 	,''''''  d +++4x== 	| 	DMB&''<< 	 	CDECKDDDDCs{RsD))K&&&&JqMMMMH%& Msa   3CC"C*K
M.(A<M))M.P<<Q 	Q 	[ ![10[141_& &
_32_3c                     |sdS |D ]F}d}|d d         dk    r|dd          }d}t          j         | d|z   dz             }|r|r dS A|s dS GdS )NTFr   !*)fnmatch)rO   r$   patternnegresults        r   _match_namer   P  s     t 
 
2A2;#abbkGCsW}s':;; 	 uu 	55	4r    r$   r   c                 l   g }t          |           D ]J}	 |                    t          |                     |                     |           ;# t          $ r Y Gw xY wg |D ]A}|                    |j                  }t          ||           r                    |           B|rfd|D             S )Nc                      g | ]
}|         S r   r   )ry   idxr   s     r   r~   z'_filter_grid_sheeps.<locals>.<listcomp>q  s    +++Cs3x+++r    )r7   rS   r?   remove
ValueErrorr   rv   r   )r$   rZ   r   indexesprz   rO   r   s          @r   r   r   a  s    G(^^  	NN3q66""" OOA  	 	 	H	 C  }}UX&&tX&& 	JJu ,++++7+++Js   "A
AAr   r   c                 $                        d |D                       \  }}fd|D             }d| j        t          || j                           n | j        rt	          d |D                       fd|D             }g }d}	t          t          |||                    D ]\  }
\  }}}|                                }|                                sd}	|d}n
|dd	         }||
|j	        r|j	        j
        nd
|j        j        |d}i }||d<   	 |                    ||          }n%# t          $ r |                    |          }Y nw xY w|                    |           |                    |           |r |d|           t%          j        dt%          j        d|                                          g|                                z             } |t%          j        |||                                                     |	S )zSingle iteration of monitoring of the jobs in a Grid.
    Returns `True` if all jobs are done or failed, and `False` otherwise.
    c                     g | ]	}|j         
S r   )rv   rx   s     r   r~   zmonitor.<locals>.<listcomp>z  s    &B&B&BEux&B&B&Br    c                 D    g | ]}                     |j                  S r   )get_xp_historyrv   )ry   rz   rZ   s     r   r~   zmonitor.<locals>.<listcomp>{  s)    AAA5$$UX..AAAr    Nc              3   4   K   | ]}t          |          V  d S r   )r   )ry   metricss     r   	<genexpr>zmonitor.<locals>.<genexpr>  s(      99G3w<<999999r    c                 $    g | ]}|d          S r   r   )ry   r   r(   s     r   r~   zmonitor.<locals>.<listcomp>  s!    ===WUdU^===r    TFzN/A    )rO   r   sidrw   stateMetazBase name: )shortengroups)colors)	get_namesr(   r   r)   min	enumeratezipr   r   r   r   rv   rw   process_sheepNotImplementedErrorprocess_historyr   rS   tttablegroupget_grid_metaget_grid_metrics	treetable
get_colors)r   rZ   rW   r   r   names	base_name	historieslinesfinishedr   rz   historyrO   r   metalineotherr   r(   s    `                 @r   r%   r%   u  sp   
 ~~&B&BT&B&B&BCCE9AAAADAAAIDy9TY'((	 :99y99999====9===	EH)23tY3N3N)O)O  %%w}} 	H=EE"1"IE',y859##b8<
 
 V	6**5'::EE" 	6 	6 	6,,W55EEE	6ET .M9---HHVX335566
%%''(  E KUE(2E2E2G2GHHHIIIOs   D//EE)7r6   concurrent.futuresr   dataclassesr   r   r   	functoolsr   rL   pathlibr   typingr8   r   rU   r   confr	   r
   r   explorer   r   r   rZ   r   r   r   r   r   r   r   r   utilsr   r   r   r   r   Callabler:   r;   r   r"   rf   Anyrm   r>   r9   ri   r   r   r<   r%   r   r    r   <module>r
     s     3 2 2 2 2 2 ( ( ( ( ( ( ( (        				            



  < < < < < < < < < < - - - - - - - - - -       , , , , , , , , , , ! ! ! ! ! ! ! ! = = = = = = = = = =     '
G < <R[# < < <	 	 	 .$ .$ .$ .$ .$ .$ .$ .$b# # #L	Abf 	AM 	A 	A 	A 	A #.+--SW!,@ @= @H @ @@8:K8P@@3575>@ @ @ @F  ""'#, m  "3575>   (4"& 4 4 4QV 44)-4 4 4 4 4 4r    