
    (^i{4                    v   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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 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j<                  e      Z ejB                  ejD                  fZ# ejH                         Z% ed       G d de             Z&y)    )annotations)SequenceN)Any)TYPE_CHECKING)logging)experimental_class)_LazyImport)_SearchSpaceTransform)BaseDistribution)CategoricalDistribution)BaseSampler)&_INDEPENDENT_SAMPLING_WARNING_TEMPLATE)FrozenTrial)
TrialState)Studyz3.0.0c                      e Zd ZdZddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZ	 	 	 	 	 	 dd	Zdd
Zedd       Z	ddZ
	 	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 ddZddZ	 	 	 	 	 	 	 	 	 	 ddZddZddZy)
QMCSamplerap  A Quasi Monte Carlo Sampler that generates low-discrepancy sequences.

    Quasi Monte Carlo (QMC) sequences are designed to have lower discrepancies than
    standard random sequences. They are known to perform better than the standard
    random sequences in hyperparameter optimization.

    For further information about the use of QMC sequences for hyperparameter optimization,
    please refer to the following paper:

    - `Bergstra, James, and Yoshua Bengio. Random search for hyper-parameter optimization.
      Journal of machine learning research 13.2, 2012.
      <https://jmlr.org/papers/v13/bergstra12a.html>`__

    We use the QMC implementations in Scipy. For the details of the QMC algorithm,
    see the Scipy API references on `scipy.stats.qmc
    <https://scipy.github.io/devdocs/reference/stats.qmc.html>`__.

    .. note:
        If your search space contains categorical parameters, it samples the categorical
        parameters by its `independent_sampler` without using QMC algorithm.

    .. note::
        The search space of the sampler is determined by either previous trials in the study or
        the first trial that this sampler samples.

        If there are previous trials in the study, :class:`~optuna.samplers.QMCSampler` infers its
        search space using the trial which was created first in the study.

        Otherwise (if the study has no previous trials), :class:`~optuna.samplers.QMCSampler`
        samples the first trial using its `independent_sampler` and then infers the search space
        in the second trial.

        As mentioned above, the search space of the :class:`~optuna.samplers.QMCSampler` is
        determined by the first trial of the study. Once the search space is determined, it cannot
        be changed afterwards.

    Args:
        qmc_type:
            The type of QMC sequence to be sampled. This must be one of
            `"halton"` and `"sobol"`. Default is `"sobol"`.

            .. note::
                Sobol' sequence is designed to have low-discrepancy property when the number of
                samples is :math:`n=2^m` for each positive integer :math:`m`. When it is possible
                to pre-specify the number of trials suggested by `QMCSampler`, it is recommended
                that the number of trials should be set as power of two.

        scramble:
            If this option is :obj:`True`, scrambling (randomization) is applied to the QMC
            sequences.

        seed:
            A seed for ``QMCSampler``. This argument is used only when ``scramble`` is :obj:`True`.
            If this is :obj:`None`, the seed is initialized randomly. Default is :obj:`None`.

            .. note::
                When using multiple :class:`~optuna.samplers.QMCSampler`'s in parallel and/or
                distributed optimization, all the samplers must share the same seed when the
                `scrambling` is enabled. Otherwise, the low-discrepancy property of the samples
                will be degraded.

        independent_sampler:
            A :class:`~optuna.samplers.BaseSampler` instance that is used for independent
            sampling. The first trial of the study and the parameters not contained in the
            relative search space are sampled by this sampler.

            If :obj:`None` is specified, :class:`~optuna.samplers.RandomSampler` is used
            as the default.

            .. seealso::
                :class:`~optuna.samplers` module provides built-in independent samplers
                such as :class:`~optuna.samplers.RandomSampler` and
                :class:`~optuna.samplers.TPESampler`.

        warn_independent_sampling:
            If this is :obj:`True`, a warning message is emitted when
            the value of a parameter is sampled by using an independent sampler.

            Note that the parameters of the first trial in a study are sampled via an
            independent sampler in most cases, so no warning messages are emitted in such cases.

        warn_asynchronous_seeding:
            If this is :obj:`True`, a warning message is emitted when the scrambling
            (randomization) is applied to the QMC sequence and the random seed of the sampler is
            not set manually.

            .. note::
                When using parallel and/or distributed optimization without manually
                setting the seed, the seed is set randomly for each instances of
                :class:`~optuna.samplers.QMCSampler` for different workers, which ends up
                asynchronous seeding for multiple samplers used in the optimization.

            .. seealso::
                See parameter ``seed`` in :class:`~optuna.samplers.QMCSampler`.

    Example:

        Optimize a simple quadratic function by using :class:`~optuna.samplers.QMCSampler`.

        .. testcode::

            import optuna


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


            sampler = optuna.samplers.QMCSampler()
            study = optuna.create_study(sampler=sampler)
            study.optimize(objective, n_trials=8)

    sobolFNT)qmc_typescrambleseedindependent_samplerwarn_asynchronous_seedingwarn_independent_samplingc               V   || _         |,t        j                  j                         j	                         n|| _        |xs  t        j                  j                  |      | _	        d | _
        || _        |dv r|| _        nd| d}t        |      ||r|r| j                          y y y y )N)r   )haltonr   zThe `qmc_type`, "z:", is not a valid. It must be one of "halton" and "sobol".)	_scramblenprandomPCG64
random_raw_seedoptunasamplersRandomSampler_independent_sampler_initial_search_space_warn_independent_sampling	_qmc_type
ValueError_log_asynchronous_seeding)selfr   r   r   r   r   r   messages           U/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/optuna/samplers/_qmc.py__init__zQMCSampler.__init__   s     "7;|RYY__&113
$7$c6??;X;X^b;X;c!IM"*C'**%DN $H: .: :  W%%<H)B**, *CH<    c                8    | j                   j                          y N)r&   
reseed_rng)r,   s    r.   r3   zQMCSampler.reseed_rng   s     	!!,,.r0   c                    | j                   | j                   S |j                  dt        d      }t        |      dk(  ri S t	        |d       }| j                  |      | _         | j                   S )NFT)deepcopystates	use_cacher   c                    | j                   S r2   )number)ts    r.   <lambda>z8QMCSampler.infer_relative_search_space.<locals>.<lambda>   s
    QXX r0   )key)r'   _get_trials_SUGGESTED_STATESlenmin_infer_initial_search_space)r,   studytrialpast_trialsfirst_trials        r.   infer_relative_search_spacez&QMCSampler.infer_relative_search_space   su     %%1---''?P\`'a{q I ++=>%)%E%Ek%R")))r0   c                z    i }|j                   j                         D ]  \  }}t        |t              r|||<    |S r2   )distributionsitems
isinstancer   )r,   rC   search_space
param_namedistributions        r.   rA   z&QMCSampler._infer_initial_search_space   sJ    46(-(;(;(A(A(C 	4$J,(?@'3L$	4
 r0   c                 .    t         j                  d       y )Na  No seed is provided for `QMCSampler` and the seed is set randomly. If you are running multiple `QMCSampler`s in parallel and/or distributed  environment, the same seed must be used in all samplers to ensure that resulting samples are taken from the same QMC sequence. )_loggerwarning r0   r.   r+   z$QMCSampler._log_asynchronous_seeding   s    =	
r0   c           	         t         j                  t        j                  ||j                  | j
                  j                  j                  | j                  j                  d             y )NzTdynamic search space and `CategoricalDistribution` are not supported by `QMCSampler`)rL   trial_numberindependent_sampler_namesampler_namefallback_reason)rO   rP   r   formatr9   r&   	__class____name__)r,   rC   rL   s      r.   _log_independent_samplingz$QMCSampler._log_independent_sampling   sM    299%"\\)-)B)B)L)L)U)U!^^44&		
r0   c                    | j                   | j                  r| j                  ||       | j                  j	                  ||||      S r2   )r'   r(   rZ   r&   sample_independent)r,   rB   rC   rL   param_distributions        r.   r\   zQMCSampler.sample_independent   sL     %%1....ujA((;;5*&8
 	
r0   c                    |i k(  ri S | j                  ||      }t        |      }|j                  d d df   ||j                  d d df   |j                  d d df   z
  z  z   }|j                  |dd d f         S )Nr      )_sample_qmcr
   boundsuntransform)r,   rB   rC   rK   sampletranss         r.   sample_relativezQMCSampler.sample_relative   s     2I!!%6%l3ad#fQT0BU\\RSUVRVEW0W&XX  1..r0   c                <    | j                   j                  ||       y r2   )r&   before_trial)r,   rB   rC   s      r.   rg   zQMCSampler.before_trial  s    !!..ue<r0   c                @    | j                   j                  ||||       y r2   )r&   after_trial)r,   rB   rC   statevaluess        r.   ri   zQMCSampler.after_trial	  s     	!!--eUE6Jr0   c                   t        d      }| j                  |      }t        |      }| j                  dk(  r)|j	                  || j
                  | j                        }nR| j                  dk(  r8t        5  |j                  || j
                  | j                        }d d d        nt        d      |}|dkD  rj                  |       j                  d      }|S # 1 sw Y   4xY w)Nzscipy.stats.qmcr   )r   r   r   zInvalid `qmc_type`r   r_   )r	   _find_sample_idr?   r)   Haltonr"   r   _threading_lockSobolr*   fast_forwardr   )	r,   rB   rK   
qmc_module	sample_idd
qmc_engineforward_sizerc   s	            r.   r`   zQMCSampler._sample_qmc  s     !23
((/	>>X%#**14::*WJ^^w& ! ['--adjj4>>-Z
[ [ 122  !##L1""1%[ [s   5)CC&c                R   d}|| j                   z  }| j                  r|d| j                   dz  }n|dz  }|dz   }|j                  j	                  |j
                        }||j                         v r||   }|dz  }nd}|j                  j                  |j
                  ||       |S )N z (scramble=True, seed=)z (scramble=False)z's last sample idr_   r   )r)   r   r"   _storageget_study_system_attrs	_study_idkeysset_study_system_attr)r,   rB   qmc_id
key_qmc_idsystem_attrsrs   s         r.   rm   zQMCSampler._find_sample_id-  s    $.. >>.tzzl!<<F))F11

 ~~<<U__M**,,$Z0INII,,U__j)Tr0   )r   strr   boolr   z
int | Noner   zBaseSampler | Noner   r   r   r   returnNone)r   r   )rB   r   rC   r   r   dict[str, BaseDistribution])rC   r   r   r   )rC   r   rL   r   r   r   )
rB   r   rC   r   rL   r   r]   r   r   r   )rB   r   rC   r   rK   r   r   zdict[str, Any])rB   r   rC   r   r   r   )
rB   r   rC   z'optuna.trial.FrozenTrial'rj   r   rk   zSequence[float] | Noner   r   )rB   r   rK   r   r   z
np.ndarray)rB   r   r   int)rY   
__module____qualname____doc__r/   r3   rF   rA   staticmethodr+   rZ   r\   re   rg   ri   r`   rm   rQ   r0   r.   r   r   !   sL   rn  26*.*.- - 	-
 - 0- $(- $(- 
-:/**#.*	$*  
 



 
 	

 -
 

	/	/#.	/>Y	/		/=KK *K 	K
 'K 
K6r0   r   )'
__future__r   collections.abcr   	threadingtypingr   r   numpyr   r#   r   optuna._experimentalr   optuna._importsr	   optuna._transformr
   optuna.distributionsr   r   optuna.samplersr   optuna.samplers._baser   optuna.trialr   r   optuna.studyr   
get_loggerrY   rO   COMPLETEPRUNEDr>   Lockro   r   rQ   r0   r.   <module>r      s    " $        3 ' 3 1 8 ' H $ # " '

X
&((**;*;<  ).." G` ` `r0   