
    (^i-                       d dl mZ d dlmZ d dlmZ d dlZd dlmZ d dlm	Z	 d dlm
Z
 d dlmZ d dlZd dlZd d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZ d dlmZ e
rd dlmZ eeeeedf   Z  ee!      Z" G d de      Z#y)    )annotations)Mapping)SequenceN)Real)Any)TYPE_CHECKING)Union)BaseDistribution)
get_logger)BaseSampler)LazyRandomState)FrozenTrial)
TrialState)Studyc                      e Zd ZdZ	 d	 	 	 	 	 ddZddZddZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 	 	 ddZ		 	 	 	 	 	 	 	 	 	 dd	Z
edd
       ZddZedd       ZddZddZy)GridSamplera6  Sampler using grid search.

    With :class:`~optuna.samplers.GridSampler`, the trials suggest all combinations of parameters
    in the given search space during the study.

    Example:

        .. testcode::

            import optuna


            def objective(trial):
                x = trial.suggest_float("x", -100, 100)
                y = trial.suggest_int("y", -100, 100)
                return x**2 + y**2


            search_space = {"x": [-50, 0, 50], "y": [-99, 0, 99]}
            study = optuna.create_study(sampler=optuna.samplers.GridSampler(search_space))
            study.optimize(objective)

    Note:

        This sampler with :ref:`ask_and_tell` raises :exc:`RuntimeError` just after evaluating
        the final grid. This is because :class:`~optuna.samplers.GridSampler` automatically
        stops the optimization if all combinations in the passed ``search_space`` have already
        been evaluated, internally invoking the :func:`~optuna.study.Study.stop` method.
        As a workaround, we need to handle the error manually as in
        https://github.com/optuna/optuna/issues/4121#issuecomment-1305289910.

    Note:

        :class:`~optuna.samplers.GridSampler` does not take care of a parameter's quantization
        specified by discrete suggest methods but just samples one of values specified in the
        search space. E.g., in the following code snippet, either of ``-0.5`` or ``0.5`` is
        sampled as ``x`` instead of an integer point.

        .. testcode::

            import optuna


            def objective(trial):
                # The following suggest method specifies integer points between -5 and 5.
                x = trial.suggest_float("x", -5, 5, step=1)
                return x**2


            # Non-int points are specified in the grid.
            search_space = {"x": [-0.5, 0.5]}
            study = optuna.create_study(sampler=optuna.samplers.GridSampler(search_space))
            study.optimize(objective, n_trials=2)

    Note:
        A parameter configuration in the grid is not considered finished until its trial is
        finished. Therefore, during distributed optimization where trials run concurrently,
        different workers will occasionally suggest the same parameter configuration.
        The total number of actual trials may therefore exceed the size of the grid.

    Note:
        All parameters must be specified when using :class:`~optuna.samplers.GridSampler` with
        :meth:`~optuna.study.Study.enqueue_trial`.

    Args:
        search_space:
            A dictionary whose key and value are a parameter name and the corresponding candidates
            of values, respectively.
        seed:
            A seed to fix the order of trials as the grid is randomly shuffled. This shuffle is
            beneficial when the number of grids is larger than ``n_trials`` in
            :meth:`~optuna.Study.optimize` to suppress suggesting similar grids. Please note
            that fixing ``seed`` for each process is strongly recommended in distributed
            optimization to avoid duplicated suggestions.
    Nc                L   |j                         D ]  \  }}|D ]  }| j                  ||          i | _        t        |j                               D ]  \  }}t	        |      | j                  |<    t	        t        j                  | j                  j                                | _        t        |j                               | _
        t        | j                        | _        t        |xs d      | _        | j                  j                  j!                  | j                         y )Nr   )items_check_value_search_spacesortedlist	itertoolsproductvalues
_all_gridskeys_param_nameslen_n_min_trialsr   _rngrngshuffle)selfsearch_spaceseed
param_nameparam_valuesvalues         V/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/optuna/samplers/_grid.py__init__zGridSampler.__init__m   s     )5(:(:(< 	5$J% 5!!*e45	5  (.|/A/A/C(D 	@$J-1,-?Dz*	@ y00$2D2D2K2K2MNO"<#4#4#67 1#DIA.			doo.    c                L    | j                   j                  j                          y N)r!   r"   r&   )r$   s    r*   
reseed_rngzGridSampler.reseed_rng~   s    		r,   c                   d|j                   v sd|j                   v ry d|j                  k  r||j                  | j                  k  rc|j                  j	                  |j
                  d| j                         |j                  j	                  |j
                  d|j                         y | j                  |      }t        |      dk(  r<t        j                  d       t        t        t        | j                                    }t        | j                  j                   j#                  |            }|j                  j	                  |j
                  d| j                         |j                  j	                  |j
                  d|       y )Ngrid_idfixed_paramsr   r%   z`GridSampler` is re-evaluating a configuration because the grid has been exhausted. This may happen due to a timing issue during distributed optimization or when re-running optimizations on already finished studies.)system_attrsnumberr    _storageset_trial_system_attr	_trial_idr   _get_unvisited_grid_idsr   _loggerwarningr   ranger   intr!   r"   choice)r$   studytrialtarget_gridsr1   s        r*   before_trialzGridSampler.before_trial   s)    ***n@R@R.R0B0B!BNN001C1C NN00)U\\Z33E:|!
 OOP  c$//&: ;<L diimm**<89,,U__ndN`N`a,,U__iQr,   c                    i S r.    )r$   r>   r?   s      r*   infer_relative_search_spacez'GridSampler.infer_relative_search_space   	     	r,   c                    i S r.   rC   )r$   r>   r?   r%   s       r*   sample_relativezGridSampler.sample_relative   rE   r,   c           	        d|j                   vrd}t        |      || j                  vrdj                  |      }t        |      |j                   d   }| j                  |   | j
                  j                  |         }|j                  |j                  |            }|st        j                  d| d| d| d       |S )Nr1   zKAll parameters must be specified when using GridSampler with enqueue_trial.z7The parameter name, {}, is not found in the given grid.zThe value `z$` is out of range of the parameter `z;`. The value will be used but the actual distribution is: `z`.)r3   
ValueErrorr   formatr   r   index	_containsto_internal_reprwarningswarn)	r$   r>   r?   r'   param_distributionmessager1   param_valuecontainss	            r*   sample_independentzGridSampler.sample_independent   s     E...cGW%%T///OVVWabGW%%$$Y/oog.t/@/@/F/Fz/RS%//0B0S0ST_0`aMMk]*Nzl [KK]J^^`b
 r,   c                   | j                  |      }t        |      dk(  r|j                          y t        |      dk(  rB|j                  j	                  |j
                        d   }||d   k(  r|j                          y y y )Nr      r1   )r8   r   stopr5   get_trial_system_attrsr7   )r$   r>   r?   stater   r@   r1   s          r*   after_trialzGridSampler.after_trial   ss     33E:|!JJL!#nn;;EOOLYWG,q/)

 * $r,   c                    | t        |t        t        t        t        f      ry dj                  | t        |            }t        j                  |       y )Nz{} contains a value with the type of {}, which is not supported by `GridSampler`. Please make sure a value is `str`, `int`, `float`, `bool` or `None` for persistent storage.)	
isinstancestrr<   floatboolrJ   typerN   rO   )r'   rR   rQ   s      r*   r   zGridSampler._check_value   sF    *[3UD:Q"R117
DDU1V 	
 	gr,   c                   g }g }|j                   j                  |j                  d      }|D ]  }d|j                  v s| j	                  |j                  d         s1|j
                  j                         r|j                  |j                  d          j|j
                  t        j                  k(  s|j                  |j                  d           t        t        | j                              t        |      z
  t        |      z
  }t        |      dk(  r*t        t        | j                              t        |      z
  }t        |      S )NF)deepcopyr1   r%   r   )r5   get_all_trials	_study_idr3   _same_search_spacerY   is_finishedappendr   RUNNINGsetr;   r    r   r   )r$   r>   visited_gridsrunning_gridstrialstunvisited_gridss          r*   r8   z#GridSampler._get_unvisited_grid_ids   s   
 ..u.O 	DAANN*t/F/F~.0 77&&(!((	)BCWW
 2 22!((	)BC	D eD$6$6783};MMPSTaPbb 1$!%(:(:";<s=?QQOO$$r,   c                    t        | t              xr t        j                  t	        |             }t        |t              xr t        j                  t	        |            }| |k(  xs |xr |S r.   )r\   r   npisnanr^   )value1value2value1_is_nanvalue2_is_nans       r*   _grid_value_equalzGridSampler._grid_value_equal  sS    "640LRXXeFm5L"640LRXXeFm5L& Fm&EFr,   c                r   t        |j                               t        | j                  j                               k7  ry|j                         D ]f  }t        ||         t        | j                  |         k7  r yt	        ||         D ]*  \  }}| j                  || j                  |   |         r)  y h y)NFT)ri   r   r   r   	enumeraterv   )r$   r%   r'   irR   s        r*   re   zGridSampler._same_search_space  s    |  "#s4+=+=+B+B+D'EE&++- 	!J<
+,D4F4Fz4R0SS"+L,D"E !;--k4;M;Mj;YZ[;\] !		! r,   c                <    t        | j                  |            dk(  S )z_
        Return True if all the possible params are evaluated, otherwise return False.
        r   )r   r8   )r$   r>   s     r*   is_exhaustedzGridSampler.is_exhausted  s     4//671<<r,   r.   )r%   %Mapping[str, Sequence[GridValueType]]r&   z
int | NonereturnNone)r}   r~   )r>   r   r?   r   r}   r~   )r>   r   r?   r   r}   dict[str, BaseDistribution])r>   r   r?   r   r%   r   r}   zdict[str, Any])
r>   r   r?   r   r'   r]   rP   r
   r}   r   )
r>   r   r?   r   rY   r   r   zSequence[float] | Noner}   r~   )r'   r]   rR   r   r}   r~   )r>   r   r}   z	list[int])rr   GridValueTypers   r   r}   r_   )r%   r|   r}   r_   )r>   r   r}   r_   )__name__
__module____qualname____doc__r+   r/   rA   rD   rG   rT   rZ   staticmethodr   r8   rv   re   r{   rC   r,   r*   r   r       s   JZ W[/A/IS/	/"'RR#.	$
#.>Y	
  	
 - 
4  	
 ' 
  	 	%8 G G
=r,   r   )$
__future__r   collections.abcr   r   r   numbersr   typingr   r   r	   rN   numpyrp   optuna.distributionsr
   optuna.loggingr   optuna.samplersr   "optuna.samplers._lazy_random_stater   optuna.trialr   r   optuna.studyr   r]   r^   r<   r_   r   r   r9   r   rC   r,   r*   <module>r      sn    " # $         1 % ' > $ # " c5#tT12 X
~=+ ~=r,   