
    mic9                        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jP                  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j`                  e   de,dejb                  e    fdZ2d Z3dejb                  e)   dedejb                  e    dejb                  e    fd Z4dej\                  deded!ejb                  e    d"ejP                  de5fd#Z6y)$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                       y N )argskwargss     C/var/www/stems/demucs_env/lib/python3.12/site-packages/dora/grid.pyno_printr   %   s        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<   y)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"   )   s    . #48Hbggcl8 GTHe!D"++c
!ItFD GTFDE4#D"++d
#GT  $FBKK# CS	 !D"++c
!#t#r    r"   c                    |j                   j                  }||j                  dz   }t        |      }| j                  A| j                  j                  dd      dz   }t        |j                        j                  |z  }| j                  j                         s>g }t        |j                        j                  }t        j                  |      D ]  \  }}	}
|
D ]  }t        |      |z  j                  |      }|j                  j                  d      s<|j                  j                  d      rX|j                  |j                   z  }|j#                  t%        |      j                  dd               | j                  "j                         st'        d d| d       t'        d	d
j)                  |              t+        j,                  d       |dz   | j                  z   }t        |      }	 |j.                  }t5        t6              st3        | d       |S # t0        $ r t3        | d       Y 9w xY w)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   [   s   99))L||h.L)Eyy		))#s3e;(//-?	yy	 0 0 2
'..$&GGH$5 	G D'5 G J-::8D==))%09Q9QRU9V'>H%%c(m&;&;C&EF	G	G 99 )9)9);-l<. I) ) *#DIIj$9#:;<s"TYY.I9%DF== h)
ABCO	  FCDEFs   9H% %H?>H?r   rZ   c                     t        | |      }|j                         }t        ||        t               }t        ||        t	               }d|_        t        ||        t        ||| j                  |||       y )NT)rf   get_slurm_configr   r
   r"   r2   run_gridrG   )r   rZ   rW   slurmrules	grid_argss         r   grid_actionrm      sf    D$'H!!#EUD!MEUD!I"&IY%T8TYYui@r    rW   re   rk   rj   returnc           	         t        |t              sJ || j                         }| j                  j                  | j                  j
                  z  |z  }|j                  dd       t               }t        | t              }| j                  r<t        d      5 }	t        ||||	      }
 ||
       |j                          ddd       nt        |||      }
 ||
       |j                          t        |j                   j#                               }t%        |j&                  | |      }|j(                  r|j*                  rt-        d       t        dt/        |       d	| d
       |j0                  r)t3        d      }|j5                         dk7  rt-        d       t        d       |D ]*  }|j6                  |j9                  |j6                         , |j;                          t        d       |D ]L  }|j<                  j>                  jA                         rtC        |j<                  j>                         d|_        N g }g }|jE                         D ]]  }|jF                  |j                   vs|jI                  |       	 |jK                  |jF                        }|J |jI                  |       _ |j                          |jV                  s|D ci c]  }|j<                  jX                  | }}|jZ                  D ]  }|D cg c]  }||v s||    }}|s|d   }|j\                  |j<                  jX                     }t/        |      dk(  r|j_                  |||       g|ja                  |      5  |D ]  }|j_                  |||        	 ddd        |D ]  }|jc                         r|j6                  J |j9                  |j6                         | je                  |j<                        }t        d|j6                  jT                   d|j<                  jX                   d|         |jV                  r|D ]  }|jc                         r|j6                  J | je                  |j<                        }t        d|j6                  jT                   d|j<                  jX                   d|        |j9                  |j6                          |j*                  s|D ]  }||j<                  jX                  z  }|jA                         s|jg                         rH|jg                         r6|ji                         |j<                  j>                  ji                         k(  rJ |jk                  |j<                  j>                          |j;                          |D ]  }|jm                           |jn                  r"|D ]  }| jq                  |j<                          |jV                  r|S |st        d       |S |j>                  |j                  |jr                  fD cg c]  }||	 }}|rC|j0                  stu        d      t/        |      dk(  sJ |d   }	 ||   }| je                  j<                        }|j>                  !ty        |j<                  j>                         |S |jr                  Z|j                  jA                         st-        d|j                   d       t{        j|                  ddd d!d"|j                  g       |S |j                  jA                         st-        d#| d       	 t        j                  t        |j                        t        j                         |S |j                  rt        } ntx        }  | d$|        	 |j                  r$|j                  sdd%lHmI}! |!j                  d&       |j                          t        || |||       r	 |S |j                  s	 |S t        |j                  d'z        }" |         t        |"      D ]?  }#d(|"|#z
  d)d*}$|"|#z
  d+k  rt        |$d,      }$ | |$d-.       t        j                  d       A  | d/       # 1 sw Y   xY w# tL        $ r}t        d|jF                   d|        || j                  jN                  jP                  z  }tS        |      }|<|d   }t        d|jT                   d|jF                   d       |j9                  |       Y d}~d}~ww xY wc c}w c c}w # 1 sw Y   8xY wc c}w # tv        $ r t-        d|j>                          Y w xY w# t        $ r Y |S w xY w)0a  
    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   r   z for no longer required sheep rB   z for sheep zNo sheep to handle.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commitxpr0   rK   r   iterdirrO   rS   get_sheep_from_sig	Exceptionshepjob_filer   job_idr,   sig
job_arraysslurm_configs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/   IPythonrv   clear_outputr%   r?   r'   ranger   timesleep)%rZ   rW   re   rk   rj   r   grid_folderherdshepherdrs   launcherr   replsheep	to_unlink
old_sheepschild	old_sheeperrorr   jobsr   	sheep_mapr   r   array_sheepsfirstrO   linkactionactionsindexmaybe_printrv   r   elaouts%                                        r   ri   ri      sv   * h)))}%%'))--$))"2"22Y>KtT26D#&Hzz # 	t%DAHXMMO	 	
 HeT2OO$++$$&'F f=Fzz<<;<'F}4OPY{ [5 5 	6!!)*Dzz|s"j!+, 	0Eyy$$$UYY/	0 	$% 	Exx%%'0EI	
 IJ$$& -::T[[(U#-$77

C	 !,,,!!),!-$ OO;;6<=UUXX\\5(=	= 	HI6?Ts3)CSIcNTLT OE&&uxx||4E< A%**5%?''. H!- H 225%GHH H	H   4	  "==,,,  /==.D.!5!5 6 7"))*!D63 44 {{ 	0E==?yy,,,}}UXX.nUYY%5%5$6k%((,,qQUPVWX$$UYY/	0 << 	1E%((,,.D{{} 1(T\\^uxx?V?V?X-XXX0	1 	 	ELLN	yy 	#ELL"	# {{!"%)[[$((DII$F]&&J\v]G]%%  Q R R7|q   
	25ME }}UXX&;;"%((//"  YY"99##%UYYK78IIfvtUD%))DE  99##%:4&BC""4		?CJJ?  {{"9+./
<<'  d +4x= M || M DMMB&'< 	C#ECK#4ODCs{RsD)&JJqM	 	H% ]	 	N  .:5::,bPQ 499>>#:#::)#q'C.4KEJJ<WXYZ((-.  >TH HV ^  	2N4;;-01	2 # ss   (a=b
d(	d-d-<d2.d?6d?,e 	7e, =b
	d%Bd  d%2d<	!e)(e),	e98e9c                     |sy|D ]:  }d}|d d dk(  r|dd  }d}t        j                   | d|z   dz         }|r|s5 y|r: y y)NTFr   !*)fnmatch)rO   r$   patternnegresults        r   _match_namer   P  sg     
2A;#abkGCsW}s':;
 r    r$   r   c                 V   g }t        |       D ].  }	 |j                  t        |             | j                  |       0 g }|D ];  }|j                  |j                        }t        ||       s+|j                  |       = |r|D cg c]  }||   	 }}|S # t        $ r Y w xY wc c}w r   )r7   rS   r?   remove
ValueErrorr   r   r   )	r$   rZ   r   indexespr   r   rO   idxs	            r   r   r   a  s    G(^ 	NN3q6" OOA C }}UXX&tX&JJu #*+Cs3x++J  		 ,s   BB&	B#"B#r   r   c                 Z   |j                  |D cg c]  }|j                   c}      \  }}|D cg c]  }|j                  |j                         }}d}	| j                  t	        || j                           }	n| j
                  rt        d |D              }	|	|D 
cg c]  }
|
d|	 	 }}
g }d}t        t        |||            D ]  \  }\  }}}|j                         }|j                         sd}|d}n|dd }|||j                  r|j                  j                  nd|j                  j                  |d}i }||d	<   	 |j                  ||      }|j#                  |       |j%                  |        |r	 |d
|       t'        j(                  dt'        j*                  d	|j-                               g|j/                         z         } |t'        j0                  |||j3                                      |S c c}w c c}w c c}
w # t        $ r |j!                  |      }Y w xY w)zSingle iteration of monitoring of the jobs in a Grid.
    Returns `True` if all jobs are done or failed, and `False` otherwise.
    Nc              3   2   K   | ]  }t        |        y wr   )r   ).0metricss     r   	<genexpr>zmonitor.<locals>.<genexpr>  s     9G3w<9s   TFzN/A    )rO   r   sidr   stateMetazBase name: )shortengroups)colors)	get_namesr   get_xp_historyr(   r   r)   min	enumeratezipr   r   r   r   r   process_sheepNotImplementedErrorprocess_historyr   rS   tttablegroupget_grid_metaget_grid_metrics	treetable
get_colors)r   rZ   rW   r   r   r   names	base_name	historiesr(   r   linesfinishedr   historyrO   r   metalineotherr   s                        r   r%   r%   u  s   
 ~~T&BEuxx&BCE9<@A5$$UXX.AIADyy9TYY'(	9y993<=WUd^=	=EH)23tY3N)O %%w}}H=E"1IE',yy599##b88<<
 V	6**5':E 	ET-0 M9-HHHHVX3356
%%'(E UE(2E2E2GHIO_ 'CA >. # 	6,,W5E	6s"   G>"H HHH*)H*)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 (   	    
  < < - -  , , ! = =  '
G <R[[# <	 .$ .$ .$b#L	Abff 	AM 	A #.-SW!,@= @H @ @@8:K8P@@35775>@F""''#, m  "35775>(4"&& 4 4 4QV 44)-4r    