
    &`iD                     D   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mZm	Z	m
Z
mZmZmZ d dlZd dlmZmZmZmZ d dlmZmZ  ej        e          Ze	 	 d4deded	d
de	eeef         ddf         fd            Z ed          de
deee
f         fd            ZeedZdZdedeeef         fdZ ededefd            Z!dedefdZ"dedefdZ#ededeeeeef                  eeeef                  eeeef                  f         fd            Z$d5dede%fdZ&d6dedeee                  de%fdZ'	 d4deded	d
deeef         fd Z(	 	 d4ded!eded	d
fd"Z)eded#edefd$            Z*ded#edefd%Z+	 	 d4ded&eeeef                  d'ed	d
deeef         f
d(Z,ded)ede	eddf         fd*Z-defd+Z.deeef         fd,Z/dedeeeef         eeef         f         fd-Z0dedeeef         fd.Z1dedefd/Z2 G d0 d1e3          Z4e G d2 d3e5                      Z6dS )7    N)Mapping)AnyDict	GeneratorIterableListOptionalTuple)CategoricalDomainFunctionRandomState)DeveloperAPI	PublicAPIFunresolved_specconstant_grid_searchrandom_stater   returnc              #   h   K   t          | ||          D ]\  }}t          |          rJ ||fV  dS )a  Generates variants from a spec (dict) with unresolved values.

    There are two types of unresolved values:

        Grid search: These define a grid search over values. For example, the
        following grid search values in a spec will produce six distinct
        variants in combination:

            "activation": grid_search(["relu", "tanh"])
            "learning_rate": grid_search([1e-3, 1e-4, 1e-5])

        Lambda functions: These are evaluated to produce a concrete value, and
        can express dependencies or conditional distributions between values.
        They can also be used to express random search (e.g., by calling
        into the `random` or `np` module).

            "cpu": lambda spec: spec.config.num_workers
            "batch_size": lambda spec: random.uniform(1, 1000)

    Finally, to support defining specs in plain JSON / YAML, grid search
    and lambda functions can also be defined alternatively as follows:

        "activation": {"grid_search": ["relu", "tanh"]}
        "cpu": {"eval": "spec.config.num_workers"}

    Use `format_vars` to format the returned dict of hyperparameters.

    Yields:
        (Dict of resolved variables, Spec object)
    r   r   N)_generate_variants_internal_unresolved_values)r   r   r   resolved_varsspecs        u/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/tune/search/variant_generator.pygenerate_variantsr      si      H  ;1!      " "t
 &d+++++T!!!!!" "    beta)	stabilityvaluesc                 
    d| iS )a  Specify a grid of values to search over.

    Values specified in a grid search are guaranteed to be sampled.

    If multiple grid search variables are defined, they are combined with the
    combinatorial product. This means every possible combination of values will
    be sampled.

    Example:

        >>> from ray import tune
        >>> param_space={
        ...   "x": tune.grid_search([10, 20]),
        ...   "y": tune.grid_search(["a", "b", "c"])
        ... }

    This will create a grid of 6 samples:
    ``{"x": 10, "y": "a"}``, ``{"x": 10, "y": "b"}``, etc.

    When specifying ``num_samples`` in the
    :class:`TuneConfig <ray.tune.tune_config.TuneConfig>`, this will specify
    the number of random samples per grid search combination.

    For instance, in the example above, if ``num_samples=4``,
    a total of 24 trials will be started -
    4 trials for each of the 6 grid search combinations.

    Args:
        values: An iterable whose parameters will be used for creating a trial grid.

    grid_search )r    s    r   r"   r"   =   s    B 6""r   )randomnp   nested_dictc                     i }|                                  D ]Q\  }}t          |t                    r1t          |                                           D ]\  }}|||f|z   <   K|||f<   R|S )zlFlattens a nested dict by joining keys into tuple of paths.

    Can then be passed into `format_vars`.
    )items
isinstancedict_resolve_nested_dict)r'   reskvk_v_s         r   r,   r,   i   s    
 C!!##  1a 	.q117799 $ $B!#QD2I$ CIIJr   r   c                     |                                  }dD ]}|                    |d           d                    d t          |                                          D                       S )a  Format variables to be used as experiment tags.

    Experiment tags are used in directory names, so this method makes sure
    the resulting tags can be legally used in directory names on all systems.

    The input to this function is a dict of the form
    ``{("nested", "config", "path"): "value"}``. The output will be a comma
    separated string of the form ``last_key=value``, so in this example
    ``path=value``.

    Note that the sanitizing implies that empty strings are possible return
    values. This is expected and acceptable, as it is not a common case and
    the resulting directory names will still be valid.

    Args:
        resolved_vars: Dictionary mapping from config path tuples to a value.

    Returns:
        Comma-separated key=value string.
    )runenvresources_per_trialN,c              3   j   K   | ].\  }}t          |d                     dt          |           V  /dS )=N)_clean_value).0r.   r/   s      r   	<genexpr>zformat_vars.<locals>.<genexpr>   sW        7;q!<"22a22     r   )copypopjoinsortedr)   )r   varsr/   s      r   format_varsrB   x   s}    , D2  D88  ?Edjjll?S?S     r   c                     i }|                                  D ]?\  }}|d         dk    r
|dd         }d |D             }||d                    |          <   @|S )zDFormats the resolved variable dict into a mapping of (str -> value).r   config   Nc                 ,    g | ]}t          |          S r#   )str)r;   pieces     r   
<listcomp>z*_flatten_resolved_vars.<locals>.<listcomp>   s    111#e**111r   /)r)   r?   )r   flattened_resolved_vars_dictpiecesvalues       r   _flatten_resolved_varsrN      sv    #% &,,.. ? ?!9  ABBZF11&1119>$SXXf%5%566''r   rM   c                     t          | t                    r| dS d}t          j        |dt	          |                                         d          S )z?Format floats and replace invalid string characters with ``_``.z.4fz[^a-zA-Z0-9_-]+_)r*   floatresubrG   strip)rM   invalid_alphabets     r   r:   r:      sP    % D~~ .v&SZZ88>>sCCCr   r   c                 j   t          |           \  }}t          |                                          }|s|g g fS g }g }|                                D ]H\  }}|                                r|                    ||f           1|                    ||f           I|                                 |||fS N)!_split_resolved_unresolved_valueslistr)   is_gridappendsort)r   resolved
unresolvedr   	grid_varsdomain_varspathrM   s           r   parse_spec_varsrb      s     =TBBHj))**M %b"$$IK!'')) . .e==?? 	.dE]++++e}----NN+y00r   rE   c                 t    t          |           \  }}}d}|D ]\  }}|t          |j                  z  }||z  S )z!Count samples for a specific specrE   )rb   len
categories)r   num_samplesrP   r`   r_   
grid_countra   domains           r   _count_spec_samplesri      sP     / 5 5A{IJ! - -fc&+,,,

##r   presetsc                     fdd}|                      dd          }|D ]@}t          j        |           } |d         |           |t          |d          z  }|dz  }A|dk    r|t          | |          z  }|S )Nc                     |                                 D ]C\  }}t          |t                    r$ |                     |i           |          | |<   >|| |<   D| S rW   )r)   r*   r   get)dur.   r/   deep_updates       r   rp   z$_count_variants.<locals>.deep_update   sc    GGII 	 	DAq!W%% "{155B<<33!!r   r   rf   rE   rD   )rm   r=   deepcopyri   )r   rj   total_samplestotal_num_samplespresetpreset_specrp   s         @r   _count_variantsrv      s         M22   mD))K)6222,[!<<<Q 1,T3DEEEr   c              #   d  K   t          j        |           } t          |           \  }}}|s
|si | fV  d S |}d}|r&t          | |d|          \  }|sfd|D             }t	          | |          }|D ]}	|r|st          |	||          \  }t          |	||          D ]\  }
} |D ]\  }}t          | |          |<   |
                                D ]Q\  }}|v rC||         k    r7t          |                   r"t          d
                    |                    ||<   R| fV  d S )NT)
allow_failr   c                 &    g | ]\  }}|v	||fS r#   r#   )r;   rrn   r   s      r   rI   z/_generate_variants_internal.<locals>.<listcomp>   s+    RRRTQ1M;Q;Q1a&;Q;Q;Qr   r   r   zqThe variable `{}` could not be unambiguously resolved to a single value. Consider simplifying your configuration.)r=   rq   rb   _resolve_domain_vars_grid_search_generatorr   
_get_valuer)   _is_resolved
ValueErrorformat)r   r   r   rP   r`   r_   
to_resolveall_resolvedr"   resolved_specr]   ra   rM   r.   r/   r   s                  @r   r   r      s      =D / 5 5A{I y $h JL 
S ';+$\'
 '
 '
#m  	S SRRRZRRRJ(y99K$ & &# 	< 	3z     A} :!5%
 
 
 	& 	&NHd
  ) = =e&0t&<&<d## (( % %1&&]1---$]1%566 . %..4fQii  
 $%a  %%%%%'	&& &r   rD   c           	         t          j        |           } t          |          \  }}}|D ]C\  }}	 t          | d         |          }t	          |t
                    rd|v rt          |d                   }nd}n9# t          $ r,}	t          dd	                    |           d          |	d}	~	ww xY w|rt	          |t                    rQ|                    |          s;t                              d| dd	                    |           d	|j                    n<||k    r6t                              d| d
d	                    |           d	|            t          | d         ||           Et!          | ||          S )aA  Get variants according to a spec, initialized with a config.

    Variables from the spec are overwritten by the variables in the config.
    Thus, we may end up with less sampled parameters.

    This function also checks if values used to overwrite search space
    parameters are valid, and logs a warning if not.
    rD   r"   NzPre-set config key `rJ   z` does not correspond to a valid key in the search space definition. Please add this path to the `param_space` variable passed to `tune.Tuner()`.zPre-set value `z+` is not within valid values of parameter `z`: z*` is not equal to the value of parameter `r   )r=   rq   rb   r~   r*   r+   r   
IndexErrorr   r?   r   is_validloggerwarning
domain_strassign_valuer   )
r   rD   r   r   r]   rP   ra   valrh   excs
             r   _get_preset_variantsr     s    =D$V,,NHa 0 0	c	X55F&$'' " F**()>??FF "F 	 	 	Usxx~~ U U U  		  	&&)) s++ NNM# M M&)hhtnnM M9?9JM M   S==NNB# B B&)hhtnnB B9?B B   	T(^T3////&#7l   s   AA99
B/'B**B/ra   c                 &   d}d}|dd         D ]}| }|}| |         } |d         }t          | t                    s|| |<   dS |t          d          t          |t                    s
J d            | d|         |fz   | |dz   d         z   ||<   dS )zAssigns a value to a nested dictionary.

    Handles the special case of tuples, in which case the tuples
    will be re-constructed to accommodate the updated value.
    Nr8   zCannot assign value to a tuple.zTuple key must be an int.rE   )r*   tupler   int)r   ra   rM   parent_spec
parent_keyr.   keys          r   r   r   V  s     KJ#2#Y  
Aw
r(CdE"" JS			>???#s##@@%@@@#"&tt*x"7$sQwyy/"IJr   c                      |D ]
}| |         } | S rW   r#   )r   ra   r.   s      r   r~   r~   o  s!      AwKr   r`   rx   c                    i }d}d}|r|t           k     r|dz  }d}|D ]\  }}||v r
	 |                    t          |           |          }	t          | ||	           |	||<   F# t          $ r}
|
}Y d }
~
Wd }
~
wt
          $ r$ t          d                    ||                    w xY w|r|t           k     |r|s|d|fS d|fS )NTr   rE   Fr{   z%Failed to evaluate expression: {}: {})_MAX_RESOLUTION_PASSESsample_UnresolvedAccessGuardr   RecursiveDependencyError	Exceptionr   r   )r   r`   rx   r   r]   error
num_passesra   rh   rM   es              r   r|   r|   u  sE    HEJ
 'J!777a
' 	' 	'LD&x'*400| &   T4///!& ,       ;BB4PP    'J!777&  # 	#K(?">s   $A##
B%-A441B%r_   c              #     K   dgt                    z  fds| V  d S d         t          d         d                   k     rt          j        |           }t                    D ]%\  }\  }}t	          ||||                             &|V  r d          }|rd S d         t          d         d                   k     d S d S )Nr   c                     | xx         dz  cc<   |          t          |          d                   k    r+d| <   | dz   t                    k     r | dz             S dS dS )NrE   r   TF)rd   )ir_   	incrementvalue_indicess    r   r   z)_grid_search_generator.<locals>.increment  s~    aAs9Q<?3333 M!1us=)))) yQ'''tur   r8   rE   )rd   r=   rq   	enumerater   )	r   r_   r   r   ra   r    doner   r   s	    `     @@r   r}   r}     s$      C#i..(M        

c)B-"233
3
3}_--!*9!5!5 	? 	?A~ftVM!,<%=>>>>


 	9Q<<D  
c)B-"233
3
3
3
3
3
3r   c                 *    t          |           \  }}|S rW   )_try_resolve)r/   r]   rP   s      r   r   r     s    q//KHaOr   c                 l    t           t                    rd fS t           t                    r+t                     dk    rd v rdt	           fd          fS t           t                    rBt                     dk    r/d v r+ d         }dt          |                                          fS d fS )NFrE   evalc                 @    t          d         t          d| i          S )Nr   r   )r   _STANDARD_IMPORTS)r   r/   s    r   <lambda>z_try_resolve.<locals>.<lambda>  s    ai):VTNKK r   r"   T)r*   r   r+   rd   r   r   grid)r/   grid_valuess   ` r   r   r     s    !V 6ax	At		 6Q11hKKKK
 
 
 	
 
At		 6Q1!1C1C&k+..3355557Nr   c                    i }i }|                                  D ]"\  }}t          |          \  }}|s|||f<   !t          |t                    rYt	          |          \  }}|                                 D ]\  }}	|	||f|z   <   |                                 D ]\  }}	|	||f|z   <   t          |t
          t          f          rqt          |          D ]_\  }
}t	          |
|i          \  }}|                                 D ]\  }}	|	||f|z   <   |                                 D ]\  }}	|	||f|z   <   `|||f<   $||fS rW   )r)   r   r*   r+   rX   rY   r   r   )r   r   unresolved_varsr.   r/   r]   _resolved_children_unresolved_childrenra   rM   r   elems               r   rX   rX     s    MO

 $ $1"1oo! 	$$%OQD!!4   	$
 2!44"$17799 3 3e-2qdTk**399;; 5 5e/4t,,5D%=)) 	$$Q<< 9 94 6q$i@@&(#5#;#;#=#= 7 7KD%16M1$+..#7#=#=#?#? 9 9KD%38OQD4K0099 #$M1$/))r   c                 ,    t          |           d         S )NrE   )rX   r   s    r   r   r     s    ,T22155r   c                 (    t          |           rdndS )NTF)r   r   s    r   _has_unresolved_valuesr     s    %d++6446r   c                   $     e Zd Z fdZd Z xZS )r   c                 V     t          t          |           j        |i | | | _        d S rW   )superr   __init____dict__)selfargskwds	__class__s      r   r   z_UnresolvedAccessGuard.__init__  s1    4$d++4dCdCCCr   c                     t                               | |          }t          |          s#t          d                    ||                    t          |t                     rt          |          S |S )Nz`{}` recursively depends on {})r+   __getattribute__r   r   r   r*   r   )r   itemrM   s      r   r   z'_UnresolvedAccessGuard.__getattribute__  ss    %%dD11E"" 	*077eDD   t$$ 	)%000Lr   )__name__
__module____qualname__r   r   __classcell__)r   s   @r   r   r     sG            	 	 	 	 	 	 	r   r   c                       e Zd ZdefdZdS )r   msgc                 <    t                               | |           d S rW   )r   r   )r   r   s     r   r   z!RecursiveDependencyError.__init__
  s    4%%%%%r   N)r   r   r   rG   r   r#   r   r   r   r     s/        &C & & & & & &r   r   )FN)rE   rW   )7r=   loggingr$   rR   collections.abcr   typingr   r   r   r   r   r	   r
   numpyray.tune.search.sampler   r   r   r   ray.util.annotationsr   r   	getLoggerr   r   boolr   rG   r"   r   r   r,   rB   rN   r:   rb   r   ri   rv   r   r   r   r~   r|   r}   r   r   rX   r   r   r+   r   r   r   r#   r   r   <module>r      s      				 # # # # # # H H H H H H H H H H H H H H H H H H  M M M M M M M M M M M M 8 8 8 8 8 8 8 8		8	$	$  "'"&)" )")")"  )" uT4Z $,-	)" )" )" )"X V #  #T#x-%8  #  #  #  #H 
  
  d tE3J/?     t     >($ (4 ( ( ( (D D D D D D 1
1
4eSj!"Ducz):$;T%s
BS=TTU1 1 1 1*$ $d $c $ $ $ $ $ $t*)=     6 SW4& 4&
4&&*4&BO4&
4:4& 4& 4& 4&t "'"&	5 5
55 5  	5 5 5 5p Jt J5 J J J J J0T  3     "&	! !
!eE6M*+! !  	!
 4:! ! ! !H&*tT4    <t    
uT3Y'      *
 *
4s
T%*--. *  *  *  *F6T 6d5#:&6 6 6 6 67 7$ 7 7 7 7    T   " & & & & &y & & & & &r   