
    (^iR                    8   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 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rJd dlmZ d dlmZ d dlZd dlmc mZ  d dl!mc m"Z" d dl#mc m$Z$ d dl%mc m&Z& d dl'mc m(Z) d dl*m+Z+ d dlm,Z, n6d dl-m.Z.  e.d      Z e.d      Z) e.d      Z" e.d      Z$ e.d      Z  e.d      Z&d dl/Z/ e/j`                  e1      Z2dZ3d!dZ4 e	d       G d de             Z5	 	 	 	 	 	 d"d Z6y)#    )annotations)Any)TYPE_CHECKINGN)experimental_class)warn_experimental_argument)_CONSTRAINTS_KEY)&_INDEPENDENT_SAMPLING_WARNING_TEMPLATE) _process_constraints_after_trial)BaseSampler)LazyRandomState)StudyDirection)_is_pareto_front)FrozenTrial)
TrialState)Callable)Sequence)BaseDistribution)Study)_LazyImporttorchzoptuna._gp.search_spacezoptuna._gp.gpzoptuna._gp.optim_mixedzoptuna._gp.acqfzoptuna._gp.priorg|=c                    t        j                  |       }t        j                  |d      }t        j                  |d      }||z
  t        j
                  t        |      z  }|||fS )Nr   axis)gpwarn_and_convert_infnpmeanstdmaximumEPS)valuesclipped_valuesmeansstdsstandardized_valuess        \/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/optuna/samplers/_gp/sampler.py_standardize_valuesr'   5   sZ    ,,V4NGGN+E66.q)D)E1RZZT5JJt++    z3.6.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	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 ddZ		 	 	 	 	 	 ddZ
	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 	 	 ddZddZ	 	 	 	 	 	 	 	 	 	 ddZy)	GPSamplerau  Sampler using Gaussian process-based Bayesian optimization.

    This sampler fits a Gaussian process (GP) to the objective function and optimizes
    the acquisition function to suggest the next parameters.

    The current implementation uses Matern kernel with nu=2.5 (twice differentiable) with automatic
    relevance determination (ARD) for the length scale of each parameter.
    The hyperparameters of the kernel are obtained by maximizing the marginal log-likelihood of the
    hyperparameters given the past trials.
    To prevent overfitting, Gamma prior is introduced for kernel scale and noise variance and
    a hand-crafted prior is introduced for inverse squared lengthscales.

    As an acquisition function, we use:

    - log expected improvement (logEI) for single-objective optimization,
    - log expected hypervolume improvement (logEHVI) for Multi-objective optimization, and
    - the summation of logEI and the logarithm of the feasible probability with the independent
      assumption of each constraint for (black-box inequality) constrained optimization.

    For further information about these acquisition functions, please refer to the following
    papers:

    - `Unexpected Improvements to Expected Improvement for Bayesian Optimization
      <https://arxiv.org/abs/2310.20708>`__
    - `Differentiable Expected Hypervolume Improvement for Parallel Multi-Objective Bayesian
      Optimization <https://arxiv.org/abs/2006.05078>`__
    - `Bayesian Optimization with Inequality Constraints
      <https://proceedings.mlr.press/v32/gardner14.pdf>`__

    Please also check our articles:

    - `[Optuna v4.5] Gaussian Process-Based Sampler (GPSampler) Can Now Perform Constrained
      Multi-Objective Optimization <https://medium.com/optuna/optuna-v4-5-81e78d8e077a>`__
    - `[Optuna v4.2] Gaussian Process-Based Sampler (GPSampler) Can Now Handle Inequality
      Constraints
      <https://medium.com/optuna/optuna-v4-2-gaussian-process-based-sampler-can-now-handle-inequality-constraints-a4f68e8ee810>`__
    - `Introducing Optuna's Native GPSampler
      <https://medium.com/optuna/introducing-optunas-native-gpsampler-0aa9aa3b4840>`__

    The optimization of the acquisition function is performed via:

    1. Collect the best param from the past trials,
    2. Collect ``n_preliminary_samples`` points using Quasi-Monte Carlo (QMC) sampling,
    3. Choose the best point from the collected points,
    4. Choose ``n_local_search - 2`` points from the collected points using the roulette
       selection,
    5. Perform a local search for each chosen point as an initial point, and
    6. Return the point with the best acquisition function value as the next parameter.

    Note that the procedures for non single-objective optimization setups are slightly different
    from the single-objective version described above, but we omit the descriptions for the others
    for brevity.

    The local search iteratively optimizes the acquisition function by repeating:

    1. Gradient ascent using l-BFGS-B for continuous parameters, and
    2. Line search or exhaustive search for each discrete parameter independently.

    The local search is terminated if the routine stops updating the best parameter set or the
    maximum number of iterations is reached.

    We use line search instead of rounding the results from the continuous optimization since EI
    typically yields a high value between one grid and its adjacent grid.

    .. note::
        This sampler requires ``scipy`` and ``torch``.
        You can install these dependencies with ``pip install scipy torch``.

    Args:
        seed:
            Random seed to initialize internal random number generator.
            Defaults to :obj:`None` (a seed is picked randomly).
        independent_sampler:
            Sampler used for initial sampling (for the first ``n_startup_trials`` trials)
            and for conditional parameters. Defaults to :obj:`None`
            (a random sampler with the same ``seed`` is used).
        n_startup_trials:
            Number of initial trials. Defaults to 10.
        deterministic_objective:
            Whether the objective function is deterministic or not.
            If :obj:`True`, the sampler will fix the noise variance of the surrogate model to
            the minimum value (slightly above 0 to ensure numerical stability).
            Defaults to :obj:`False`. Currently, all the objectives will be assume to be
            deterministic if :obj:`True`.
        constraints_func:
            An optional function that computes the objective constraints. It must take a
            :class:`~optuna.trial.FrozenTrial` and return the constraints. The return value must
            be a sequence of :obj:`float` s. A value strictly larger than 0 means that a
            constraints is violated. A value equal to or smaller than 0 is considered feasible.
            If ``constraints_func`` returns more than one value for a trial, that trial is
            considered feasible if and only if all values are equal to 0 or smaller.

            The ``constraints_func`` will be evaluated after each successful trial.
            The function won't be called when trials fail or are pruned, but this behavior is
            subject to change in future releases.
        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,
            meaning that no GP model is used in the sampling.
            Note that the parameters of the first trial in a study are always sampled
            via an independent sampler, so no warning messages are emitted in this case.
    N
   FT)seedindependent_samplern_startup_trialsdeterministic_objectiveconstraints_funcwarn_independent_samplingc                  t        |      | _        |xs  t        j                  j	                  |      | _        t        j                  j                         | _        || _	        t        j                  | _        t        j                  | _        d | _        d | _        || _        || _        || _        |t)        d       d| _        d| _        d| _        y )N)r,   r0   i   r+   g-C6?)r   _rngoptunasamplersRandomSampler_independent_samplersearch_spaceIntersectionSearchSpace_intersection_search_space_n_startup_trialspriordefault_log_prior
_log_priorDEFAULT_MINIMUM_NOISE_VAR_minimum_noise_gprs_cache_list_constraints_gprs_cache_list_deterministic_constraints_func_warn_independent_samplingr   _n_preliminary_samples_n_local_search_tol)selfr,   r-   r.   r/   r0   r1   s          r&   __init__zGPSampler.__init__   s     $D)	$7$c6??;X;X^b;X;c!*0*=*=*U*U*W'!1DID[D[%*%D%D >BIM)5!1*C''&'9: ,0#!	r(   c                    t        j                  ||j                  | j                  j                  j
                  | j                  j
                  d      }t        j                  |       y )Nz2dynamic search space is not supported by GPSampler)
param_nametrial_numberindependent_sampler_namesampler_namefallback_reason)r	   formatnumberr7   	__class____name___loggerwarning)rI   trialrL   msgs       r&   _log_independent_samplingz#GPSampler._log_independent_sampling   sO    4;;!%)%>%>%H%H%Q%Q00P
 	r(   c                    | j                   j                  j                          | j                  j	                          y N)r3   rngr,   r7   
reseed_rng)rI   s    r&   r]   zGPSampler.reseed_rng   s(    		!!,,.r(   c                    i }| j                   j                  |      j                         D ]  \  }}|j                         r|||<    |S r[   )r:   	calculateitemssingle)rI   studyrW   r8   namedistributions         r&   infer_relative_search_spacez%GPSampler.infer_relative_search_space   sX     "&"A"A"K"KE"R"X"X"Z 	.D,""$!-L	.
 r(   c                    |t        |j                        dk(  sJ t        j                  ||| j                  | j
                  | j                  | j                  j                        \  }}|S )N   )!warmstart_normalized_params_arrayn_preliminary_samplesn_local_searchtolr\   )	lenshapeoptim_mixedoptimize_acqf_mixedrF   rG   rH   r3   r\   )rI   acqfbest_paramsnormalized_params	_acqf_vals        r&   _optimize_acqfzGPSampler._optimize_acqf   sj     "c+*;*;&<&AAA'2'F'F.9"&"="=//				(
$9 ! r(   c           
     >   t        |       \  }}}| j                  6t        | j                  d   j                        |j                  k7  rd | _        |j                  }g }g }	| t        j                  t        |      z  j                         }	t        |j                        D ]m  \  }
}| j
                  | j
                  |
   nd }t        j                  |||| j                  | j                   || j"                        }|j%                  |       o || _        ||	fS )Nr   XYis_categorical	log_priorminimum_noise	gpr_cacher/   )r'   rA   rl   inverse_squared_lengthscalesdimrB   ry   r   r   r    tolist	enumerateTr   fit_kernel_paramsr>   r@   rC   append)rI   constraint_valsinternal_search_spacerr   standardized_constraint_valsr#   r$   ry   constraints_gprsconstraints_threshold_listivalscachegprs                 r&   _get_constraints_acqf_argsz$GPSampler._get_constraints_acqf_args   s1    5HHX4Y1$eT!!-D))!,IIJ$(() 15D-.==%'"',frzz#t/D&D%L%L%N" !=!?!?@ 	)GAt 44@ 11!4 
 &&#-//"11(,(;(;C ##C(	)" -=)!;;;r(   c                    |t        | d         }t        |      }t        | j                  dz  |      }| j                  j
                  j                  ||d      }||   S )NF)assume_unique_lexsortedrg   )sizereplace)r   rl   minrG   r3   r\   choice)rI   rr   standardized_score_valspareto_paramsn_pareto_solsr   chosen_indicess          r&   $_get_best_params_for_multi_objectivez.GPSampler._get_best_params_for_multi_objective  sj    
 *55uU
 M*4''1,m<--m$PU-V^,,r(   c                   |i k(  ri S t         j                  f}|j                  d|d      }t        |      | j                  k  ri S t        j                  |      }|j                  |      }t        j                  |j                  D cg c]  }|t        j                  k(  rdnd c}      }	t        |	t        j                  |D cg c]  }|j                   c}      z        \  }
}}| j                  6t        | j                  d   j                         |j"                  k7  rd | _        g }|
j$                  d   }|j&                  }t)        |      D ]o  }| j                  | j                  |   nd }|j+                  t-        j.                  ||
d d |f   || j0                  | j2                  || j4                               q || _        | j6                  |d	k(  rjt        |      d	k(  sJ t9        j:                  |d   ||
d d df   j=                         
      }|t        j>                  |
      t        j@                  f   }nt9        jB                  ||tE        jF                  |
      d| jH                  jJ                  jM                  d            }| jO                  ||
      }n|d	k(  rt        |      d	k(  sJ tQ        ||      \  }}t        jR                  ||
d d df   t        jT                         }| jW                  |||      \  }}t        j>                  |      }||   }t9        jX                  |d   ||||      }|j$                  d d |j$                  k(  sJ t        jZ                  |      rd n||t        j@                  f   }ntQ        ||      \  }}| jW                  |||      \  }}t]        |       }t9        j^                  |||stE        jF                  |
|         nd d| jH                  jJ                  jM                  d      ||      }|s| jO                  ||   |
|         nd }| ja                  ||      }|jc                  |      S c c}w c c}w )NFTdeepcopystates	use_cacheg      g      ?r   rv      )r   r8   	threshold   i   @)gpr_listr8   Y_trainn_qmc_samplesqmc_seed)r   r8   r   constraints_gpr_listr   )r   r8   
Y_feasibler   r   r   r   )2r   COMPLETE_get_trialsrl   r;   gp_search_spaceSearchSpaceget_normalized_paramsr   array
directionsr   MINIMIZEr'   r!   rA   r}   r~   rm   ry   ranger   r   r   r>   r@   rC   rD   acqf_moduleLogEImaxargmaxnewaxisLogEHVIr   
from_numpyr3   r\   randintr   $_get_constraint_vals_and_feasibilitywhereinfr   ConstrainedLogEIisneginfanyConstrainedLogEHVIrt   get_unnormalized_param)rI   rb   rW   r8   r   trialsr   rr   d_signr   _	gprs_listn_objectivesry   r   r   rp   rq   r   is_feasibley_with_neginfconstr_gpr_listconstr_threshold_listi_optbest_feasible_yis_all_infeasiblenormalized_params                               r&   sample_relativezGPSampler.sample_relative'  s~    2I%%'""E&D"Qv;///I / ; ;L I1GGOQVQaQabA!~'>'>">$CGbc(;BHH?uell?@@)
%A
 !!-D))!,IIJ$(() %)D!	.44R8.==|$ 	A040E0E0QD))!,W[E$$'-ad3#1"oo"&"5"5#,0,?,?
	 !* !!)q 9~***"((!!!65ad;??A
 0		:Q0RTVT^T^0^_"**&!6!,,-DE"%!YY]]227; #GG%'> q 9~***/STY[a/b, "6MaQRd6SVXV\V\U\ ] :>9X9X#%:<M:6!6 		-0"/"6"33!!!6-)8/D )..s3}7J7JJJJKK8D>OPUWYWaWaPa>b  0TTY[a/b,9=9X9X#%:<M:6!6 ),K(8$8!"55&!6  1 (()@)MN!"%!YY]]227;)8/D$ -	 ==)+6/<
    ..t[A$;;<LMMY c?s   
Q Q%c                    | j                   rOt        j                  f}|j                  d|d      }t	        |      | j
                  k\  r| j                  ||       | j                  j                  ||||      S )NFTr   )	rE   r   r   r   rl   r;   rY   r7   sample_independent)rI   rb   rW   rL   param_distributionr   complete_trialss          r&   r   zGPSampler.sample_independent  sy     ** ))+F#//vY]/^O?#t'='==..ujA((;;5*&8
 	
r(   c                <    | j                   j                  ||       y r[   )r7   before_trial)rI   rb   rW   s      r&   r   zGPSampler.before_trial  s    !!..ue<r(   c                    | j                   t        | j                   |||       | j                  j                  ||||       y r[   )rD   r
   r7   after_trial)rI   rb   rW   stater!   s        r&   r   zGPSampler.after_trial  s?     !!-,T-C-CUESXY!!--eUE6Jr(   )r,   z
int | Noner-   zBaseSampler | Noner.   intr/   boolr0   z/Callable[[FrozenTrial], Sequence[float]] | Noner1   r   returnNone)rW   r   rL   strr   r   )r   r   )rb   r   rW   r   r   dict[str, BaseDistribution])rp   zacqf_module.BaseAcquisitionFuncrq   znp.ndarray | Noner   
np.ndarray)r   r   r   zgp_search_space.SearchSpacerr   r   r   z(tuple[list[gp.GPRegressor], list[float]])rr   r   r   r   r   r   )rb   r   rW   r   r8   r   r   zdict[str, Any])
rb   r   rW   r   rL   r   r   r   r   r   )rb   r   rW   r   r   r   )
rb   r   rW   r   r   r   r!   zSequence[float] | Noner   r   )rT   
__module____qualname____doc__rJ   rY   r]   re   rt   r   r   r   r   r   r    r(   r&   r*   r*   =   s   eT  26 "(-LP*.  0	
  "& J $( 
B/		#.		$	!3!BS!	!"&<#&<  ;&< &	&<
 
2&<P-%- ",- 
	-{N{N#.{N>Y{N	{Nz

 
 	

 -
 

 =	K	K 	K 		K
 '	K 
	Kr(   r*   c                   |D cg c];  }| j                   j                  |j                        j                  t        d      = c}t        fdD              rt        d      t        j                        }t        |j                        dk(  sJ d       t        j                  |dk  d      }t        |t        j                        rJ d	       ||fS c c}w )
Nr   c              3  R   K   | ]  }t        d          t        |      k7     yw)r   N)rl   ).0c_constraint_valss     r&   	<genexpr>z7_get_constraint_vals_and_feasibility.<locals>.<genexpr>  s%     
H!3"#s1v-
Hs   $'z:The number of constraints must be the same for all trials.rg   z#constraint_vals must be a 2d array.r   r   r   z#MyPy Redefinition for NumPy v2.2.0.)_storageget_trial_system_attrs	_trial_idgetr   r   
ValueErrorr   r   rl   rm   all
isinstancebool_)rb   r   rW   r   r   r   s        @r&   r   r     s    
  	--eoo>BBCSUWX 
H7G
HHUVVhh/0O$$%*Q,QQ*&&A-A6K+rxx0W2WW0K''s   A C)r!   r   r   z)tuple[np.ndarray, np.ndarray, np.ndarray])rb   r   r   zlist[FrozenTrial]r   ztuple[np.ndarray, np.ndarray])7
__future__r   typingr   r   numpyr   r4   optuna._experimentalr   r   optuna.samplers._baser   r	   r
   r   "optuna.samplers._lazy_random_stater   optuna.studyr   optuna.study._multi_objectiver   optuna.trialr   r   collections.abcr   r   r   optuna._gp.acqf_gprp   r   optuna._gp.gpr   optuna._gp.optim_mixedrn   optuna._gp.priorr<   optuna._gp.search_spacer8   r   optuna.distributionsr   r   optuna._importsr   logging	getLoggerrT   rU   r    r'   r*   r   r   r(   r&   <module>r     s   "      3 ; 2 H B - > ' : $ # (())00$$555"+ E!";<O	_	%B67K/0K*+E  '

H
%, GBK BK BKJ((+("(r(   