L i-ddlmZddlmZddlmZddlZddlmZddlm Z ddlm Z ddlm Z ddl Z ddl Zdd lmZdd lmZdd lmZdd lmZdd lmZddlmZe rddlmZe eeeedfZ ee!Z"GddeZ#y)) annotations)Mapping)SequenceN)Real)Any) TYPE_CHECKING)Union)BaseDistribution) get_logger) BaseSampler)LazyRandomState) FrozenTrial) TrialState)StudyceZdZdZ d ddZddZddZ ddZ ddZ ddZ dd Z e dd Z dd Z e dd Zdd ZddZy) 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. NcL|jD]\}}|D]}|j|| i|_t|jD]\}}t ||j|<t t j |jj|_t|j|_ t|j|_ t|xsd|_|jjj!|jy)Nr)items _check_value _search_spacesortedlist itertoolsproductvalues _all_gridskeys _param_nameslen _n_min_trialsr _rngrngshuffle)self search_spaceseed param_name param_valuesvalues [/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/optuna/samplers/_grid.py__init__zGridSampler.__init__ms)5(:(:(< 5 $J % 5!!*e4 5 5 (.|/A/A/C(D @ $J -1,-?D  z * @y00$2D2D2K2K2MNO"<#4#4#67 1#DIA.  doo.cL|jjjyN)r!r"r&)r$s r* reseed_rngzGridSampler.reseed_rng~s r,cd|jvsd|jvryd|jkr||j|jkrc|jj |j d|j |jj |j d|jy|j|}t|dk(rr?s r*infer_relative_search_spacez'GridSampler.infer_relative_search_space  r,ciSr.rC)r$r>r?r%s r*sample_relativezGridSampler.sample_relativerEr,c d|jvr d}t|||jvrdj|}t||jd}|j||j j |}|j|j|}|stjd|d|d|d|S)Nr1zKAll 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 ValueErrorrformatrrindex _containsto_internal_reprwarningswarn) r$r>r?r'param_distributionmessager1 param_valuecontainss r*sample_independentzGridSampler.sample_independents E.. .cGW% % T// /OVVWabGW% %$$Y/oog.t/@/@/F/Fz/RS %//0B0S0ST_0`a MMk]*Nzl[KK]J^^`b  r,c|j|}t|dk(r|jyt|dk(rB|jj |j d}||dk(r|jyyy)Nrr1)r8rstopr5get_trial_system_attrsr7)r$r>r?staterr@r1s r* after_trialzGridSampler.after_trialss33E: |  ! JJL  ! #nn;;EOOLYWG,q/) *$r,c| t|ttttfrydj |t |}tj|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.) isinstancestrr<floatboolrJtyperNrO)r'rRrQs r*rzGridSampler._check_valuesF  *[3UD:Q"R  117 DDU1V   gr,cg}g}|jj|jd}|D]}d|jvs|j |jds1|j j r|j|jdj|j tjk(s|j|jdtt|jt|z t|z }t|dk(r*tt|jt|z }t|S)NF)deepcopyr1r%r)r5get_all_trials _study_idr3_same_search_spacerY is_finishedappendrRUNNINGsetr;r rr)r$r> visited_grids running_gridstrialstunvisited_gridss r*r8z#GridSampler._get_unvisited_grid_idss  ..u.O DAANN*t/F/F~.077&&(!(( )BCWW 2 22!(( )BC DeD$6$6783};MMPSTaPbb  1 $!%(:(:";s r* is_exhaustedzGridSampler.is_exhausteds4//671<rr?rr}r~)r>rr?rr}dict[str, BaseDistribution])r>rr?rr%rr}zdict[str, Any]) r>rr?rr'r]rPr r}r) r>rr?rrYrrzSequence[float] | Noner}r~)r'r]rRrr}r~)r>rr}z list[int])rr GridValueTypersrr}r_)r%r|r}r_)r>rr}r_)__name__ __module__ __qualname____doc__r+r/rArDrGrTrZ staticmethodrr8rvrer{rCr,r*rr sJZW[/A/IS/ /"'RR#. $ #.>Y    -  4  '      %8GG =r,r)$ __future__rcollections.abcrrrnumbersrtypingrrr rNnumpyrpoptuna.distributionsr optuna.loggingr optuna.samplersr "optuna.samplers._lazy_random_stater optuna.trialrr optuna.studyrr]r^r<r_rrr9rrCr,r*rsn"#$ 1%'>$#"c5#tT12  X ~=+~=r,