
    &`i2=                     N   d dl Z d dlZd dlmZmZmZmZ d dlZd dl	m
Z
 d dlmZ d dlmZmZmZmZ d dlmZmZmZmZmZmZ d dlmZ d dlmZmZ 	 d dlZd d	lm Z  n# e!$ r dxZZ Y nw xY w	 d d
l"m#Z# d dl$m%Z% n# e!$ r e&xZ%Z#Y nw xY w ej'        e(          Z) G d de          Z*dS )    N)DictListOptionalUnion)cloudpickle)DEFAULT_METRIC)UNDEFINED_METRIC_MODEUNDEFINED_SEARCH_SPACEUNRESOLVED_SEARCH_SPACESearcher)CategoricalFloatInteger
LogUniform	QuantizedUniform)parse_spec_vars)flatten_dictunflatten_list_dict)AxClient)DataRequiredError)MaxParallelismReachedExceptionc                   \    e Zd ZdZ	 	 	 	 	 	 	 ddeeeee         f                  dee         dee         deee                  dee         dee         d	ee	         f fd
Z
d Zdee         dee         defdZdedee         fdZddZd Zedefd            ZdefdZdefdZ xZS )AxSearcha&  Uses `Ax <https://ax.dev/>`_ to optimize hyperparameters.

    Ax is a platform for understanding, managing, deploying, and
    automating adaptive experiments. Ax provides an easy to use
    interface with BoTorch, a flexible, modern library for Bayesian
    optimization in PyTorch. More information can be found in https://ax.dev/.

    To use this search algorithm, you must install Ax:

    .. code-block:: bash

        $ pip install ax-platform

    Parameters:
        space: Parameters in the experiment search space.
            Required elements in the dictionaries are: "name" (name of
            this parameter, string), "type" (type of the parameter: "range",
            "fixed", or "choice", string), "bounds" for range parameters
            (list of two values, lower bound first), "values" for choice
            parameters (list of values), and "value" for fixed parameters
            (single value).
        metric: Name of the metric used as objective in this
            experiment. This metric must be present in `raw_data` argument
            to `log_data`. This metric must also be present in the dict
            reported/returned by the Trainable. If None but a mode was passed,
            the `ray.tune.result.DEFAULT_METRIC` will be used per default.
        mode: One of {min, max}. Determines whether objective is
            minimizing or maximizing the metric attribute. Defaults to "max".
        points_to_evaluate: Initial parameter suggestions to be run
            first. This is for when you already have some good parameters
            you want to run first to help the algorithm make better suggestions
            for future parameters. Needs to be a list of dicts containing the
            configurations.
        parameter_constraints: Parameter constraints, such as
            "x3 >= x4" or "x3 + x4 >= 2".
        outcome_constraints: Outcome constraints of form
            "metric_name >= bound", like "m1 <= 3."
        ax_client: Optional AxClient instance. If this is set, do
            not pass any values to these parameters: `space`, `metric`,
            `parameter_constraints`, `outcome_constraints`.
        **ax_kwargs: Passed to AxClient instance. Ignored if `AxClient` is not
            None.

    Tune automatically converts search spaces to Ax's format:

    .. code-block:: python

        from ray import tune
        from ray.tune.search.ax import AxSearch

        config = {
            "x1": tune.uniform(0.0, 1.0),
            "x2": tune.uniform(0.0, 1.0)
        }

        def easy_objective(config):
            for i in range(100):
                intermediate_result = config["x1"] + config["x2"] * i
                tune.report({"score": intermediate_result})

        ax_search = AxSearch()
        tuner = tune.Tuner(
            easy_objective,
            tune_config=tune.TuneConfig(
                search_alg=ax_search,
                metric="score",
                mode="max",
            ),
            param_space=config,
        )
        tuner.fit()

    If you would like to pass the search space manually, the code would
    look like this:

    .. code-block:: python

        from ray import tune
        from ray.tune.search.ax import AxSearch

        parameters = [
            {"name": "x1", "type": "range", "bounds": [0.0, 1.0]},
            {"name": "x2", "type": "range", "bounds": [0.0, 1.0]},
        ]

        def easy_objective(config):
            for i in range(100):
                intermediate_result = config["x1"] + config["x2"] * i
                tune.report({"score": intermediate_result})

        ax_search = AxSearch(space=parameters, metric="score", mode="max")
        tuner = tune.Tuner(
            easy_objective,
            tune_config=tune.TuneConfig(
                search_alg=ax_search,
            ),
        )
        tuner.fit()

    Nspacemetricmodepoints_to_evaluateparameter_constraintsoutcome_constraints	ax_clientc                 z   t           
J d            |r|dv s
J d            t          t          |                               ||           || _        |pi | _        t          |t                    ri|rgt          |          \  }	}
}|
s|rPt          
                    t          j        dt          |                                |                     |          }|| _        || _        || _        t%          j        |          | _        g | _        i | _        | j        s| j        r|                                  d S d S )NzsAx must be installed!
            You can install AxSearch with the command:
            `pip install ax-platform`.minmaxz`mode` must be 'min' or 'max'.)r   r   r   )parcls)axsuperr   __init___ax
_ax_kwargs
isinstancedictr   loggerwarningr   formattypeconvert_search_space_space_parameter_constraints_outcome_constraintscopydeepcopy_points_to_evaluate_parameters_live_trial_mapping_setup_experiment)selfr   r   r   r   r   r    r!   	ax_kwargsresolved_varsdomain_vars	grid_vars	__class__s               p/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/tune/search/ax/ax_search.pyr*   zAxSearch.__init__   so    NN* NN
  	L>)))+K)))h&& 	' 	
 	
 	

 #/reT"" 	9u 	94CE4J4J1M;	 9i 9+2wDJJOOO   11%88&;#$7!#'=1C#D#D #% 8 	%t{ 	%""$$$$$	% 	%    c                 8   | j         | j        rt          | _         | j        st	          di | j        | _        	 | j        j        }d}n# t          $ r d}Y nw xY w|sk| j        st          d          | j        dvrt          d          | j        	                    | j        | j         | j
        | j        | j        dk               nQt          | j        | j
        | j        | j        | j         g          r$t          d                    g d	                    | j        j        }|j        j        j        rd
nd| _        |j        j        j        j        | _         t'          |j                  | _        | j        j        rt.                              d           d S d S )NTFzYou have to create an Ax experiment by calling `AxClient.create_experiment()`, or you should pass an Ax search space as the `space` parameter to `AxSearch`, or pass a `param_space` dict to `tune.Tuner()`.r#   zmPlease specify the `mode` argument when initializing the `AxSearch` object or pass it to `tune.TuneConfig()`.r%   )
parametersobjective_namer   r    minimizezdIf you create the Ax experiment yourself, do not pass values for these parameters to `AxSearch`: {}.)r   r   r    r   r   r$   zEDetected sequential enforcement. Be sure to use a ConcurrencyLimiter. )_metric_moder   r+   r   r,   
experiment
ValueErrorr4   create_experimentr5   r6   anyr1   optimization_config	objectiverH   r   namelistrF   r:    _enforce_sequential_optimizationr/   r0   )r=   exphas_experiments      rC   r<   zAxSearch._setup_experiment   s   <DJ)DLx 	322$/22DH	#(%C!NN 	# 	# 	#"NNN	#  )	;  F   z// O   H&&;#|&*&A$($=u, '     K/-JL   !EEKV  F F   h! "5?HSUUe
.8?D//84 	NN(    	 	s   A AAconfigc                     | j         rdS |                     |          }|| _        |r|| _        |r|| _        |                                  dS )NFT)r+   r3   r4   rJ   rK   r<   )r=   r   r   rW   specr   s         rC   set_search_propertieszAxSearch.set_search_properties  sb     8 	5))&11 	"!DL 	DJ   trD   trial_idreturnc                    | j         s-t          t          j        | j        j        d                    | j        r| j        s8t          t          j        | j        j        | j        | j                            | j	        r8| j	        
                    d          }| j                             |          \  }n6	 | j                                         \  }n# t          t          f$ r Y d S w xY w|| j        |<   	 t!                    }nJ# t"          $ r= t!          fdt%                                                    D                       }Y nw xY w|S )Nr   )r'   r   )r'   r   r   r   c                 "    i | ]}||         S rI   rI   ).0krF   s     rC   
<dictcomp>z$AxSearch.suggest.<locals>.<dictcomp>8  s    EEEaJqMEEErD   )r+   RuntimeErrorr
   r1   rB   __name__rJ   rK   r	   r9   popattach_trialget_next_trialr   r   r;   r   AssertionErrorsortedkeys)r=   r[   rW   trial_indexsuggested_configrF   s        @rC   suggestzAxSearch.suggest  s   x 	&-/w     | 	4: 	%,/4:     # 	-11!44F&*h&;&;F&C&C#J*.(*A*A*C*C'
KK24EF   tt .9 *		2:>> 	 	 	
  3EEEE6*//2C2C+D+DEEE   	  s%   <C C.-C.<D AEEFc                 j    |r|                      ||           | j                            |           dS )zyNotification for the completion of trial.

        Data of form key value dictionary of metric names and values.
        N)_process_resultr;   rd   )r=   r[   resulterrors       rC   on_trial_completezAxSearch.on_trial_complete<  s?    
  	3  6222 $$X.....rD   c                 j   | j         |         }| j        gd | j        j        j        j        D             z   }i }|D ][}||         }t          j        |          st          j        |          r"| j        	                    |d|             d S |d f||<   \| j        
                    ||           d S )Nc                 &    g | ]}|j         j        S rI   )r   rR   )r_   ocs     rC   
<listcomp>z,AxSearch._process_result.<locals>.<listcomp>G  s,     /
 /
 /
 IN/
 /
 /
rD   znan/inf metrics reported by )rj   reason)rj   raw_data)r;   rJ   r+   rL   rP   r    npisnanisinfabandon_trialcomplete_trial)r=   r[   ro   ax_trial_indexmetrics_to_includemetric_dictkeyvals           rC   rn   zAxSearch._process_resultE  s    1(;"l^ /
 /
h)=Q/
 /
 /
 
 % 		+ 		+C+Cx}}  && .D(DD '     #T{KN[QQQQQrD   rY   c                     t          |           \  }}}|rt          d          t          | d          } t          |           \  }}}d d |D             }fd|D             }||z   S )NzOGrid search parameters cannot be automatically converted to an Ax search space.T)prevent_delimiterc                 D   |                                 }t          |t                    r!t                              d           |j        }t          |t                    rSt          |t                    r| d|j        |j	        gdddS t          |t                    r| d|j        |j	        gdddS nt          |t                    rYt          |t                    r| d|j        |j	        dz
  gdddS t          |t                    r| d|j        |j	        dz
  gdddS n5t          |t                    r t          |t                    r| d	|j        d
S t          d                    t!          |          j        t!          |j                  j                            )Nz=AxSearch does not support quantization. Dropped quantization.rangefloatT)rR   r2   bounds
value_type	log_scaleF   intchoice)rR   r2   valueszLAxSearch does not support parameters of type `{}` with samplers of type `{}`)get_samplerr-   r   r/   r0   samplerr   r   lowerupperr   r   r   
categoriesrM   r1   r2   rc   )r&   domainr   s      rC   resolve_valuez4AxSearch.convert_search_space.<locals>.resolve_valuef  s   ((**G'9-- *S   "/&%(( $Xgz22  # '#)<">&-%)    11  # '#)<">&-%*   FG,, Xgz22  # '#)<1A"B&+%)    11  # '#)<1A"B&+%*   FK00 Xgw// X$'VEVWWW228&LL)4+?+?+H3 3  rD   c                 Z    g | ](\  }}d                      d |D                       d|d)S )/c              3   4   K   | ]}t          |          V  d S Nstrr_   ps     rC   	<genexpr>z;AxSearch.convert_search_space.<locals>.<listcomp>.<genexpr>  s(      33c!ff333333rD   fixed)rR   r2   valuejoin)r_   pathr   s      rC   ru   z1AxSearch.convert_search_space.<locals>.<listcomp>  sQ     
 
 
c XX33d33333WsSS
 
 
rD   c                 h    g | ].\  }} d                      d |D                       |          /S )r   c              3   4   K   | ]}t          |          V  d S r   r   r   s     rC   r   z;AxSearch.convert_search_space.<locals>.<listcomp>.<genexpr>  s(      "8"8a3q66"8"8"8"8"8"8rD   r   )r_   r   r   r   s      rC   ru   z1AxSearch.convert_search_space.<locals>.<listcomp>  sT     
 
 
f M#(("8"84"8"8"888&AA
 
 
rD   )r   rM   r   )rY   r?   r@   rA   fixed_valuesresolved_valuesr   s         @rC   r3   zAxSearch.convert_search_spaceX  s    0?0E0E-{I 	)   DD9990?0E0E-{I3	 3	 3	n
 
*
 
 

 
 
 
 +
 
 

 o--rD   checkpoint_pathc                     | j         }t          |d          5 }t          j        ||           d d d            d S # 1 swxY w Y   d S )Nwb)__dict__openr   dump)r=   r   save_object
outputFiles       rC   savezAxSearch.save  s    m/4(( 	6J[*555	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6s   ;??c                     t          |d          5 }t          j        |          }d d d            n# 1 swxY w Y   | j                            |           d S )Nrb)r   r   loadr   update)r=   r   	inputFiler   s       rC   restorezAxSearch.restore  s    /4(( 	6I%*955K	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6[)))))s   266)NNNNNNN)NF)rc   
__module____qualname____doc__r   r   r   r   r   r   r*   r<   rZ   rl   rq   rn   staticmethodr3   r   r   __classcell__)rB   s   @rC   r   r   +   s       c cN 48 $"3704.2(,.% .%dDJ./0.% .% sm	.%
 %T$Z0.%  (~.% &d^.% H%.% .% .% .% .% .%`E E ENsm+3C=BF   #  #  #  #  #  # J/ / / /R R R& M.4 M. M. M. \M.^6C 6 6 6 6
*s * * * * * * * *rD   r   )+r7   loggingtypingr   r   r   r   numpyrx   rayr   ray.tune.resultr   ray.tune.searchr	   r
   r   r   ray.tune.search.sampler   r   r   r   r   r   !ray.tune.search.variant_generatorr   ray.tune.utils.utilr   r   r(   ax.service.ax_clientr   ImportErrorax.exceptions.corer   !ax.exceptions.generation_strategyr   	Exception	getLoggerrc   r/   r   rI   rD   rC   <module>r      s     . . . . . . . . . . . .           * * * * * *                           > = = = = = A A A A A A A AIII-------   BC444444PPPPPPP C C C9BB"%6%6%6C 
	8	$	$E* E* E* E* E*x E* E* E* E* E*s$   
A 	A'&A'+A8 8	BB