
    ,YHh.                        d dl mZ d dl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  G d d	      Z	 	 	 	 	 	 	 	 dd
Z	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 ddZy)    )annotationsN)Any)BaseDistribution)CategoricalDistribution)FloatDistribution)IntDistributionc                  x    e Zd ZdZ	 	 	 d		 	 	 	 	 	 	 	 	 d
dZedd       Zedd       Zedd       ZddZ	ddZ
y)_SearchSpaceTransformai	  Transform a search space and parameter configurations to continuous space.

    The search space bounds and parameter configurations are represented as ``numpy.ndarray``s and
    transformed into continuous space. Bounds and parameters associated with categorical
    distributions are one-hot encoded. Parameter configurations in this space can additionally be
    untransformed, or mapped back to the original space. This type of
    transformation/untransformation is useful for e.g. implementing samplers without having to
    condition on distribution types before sampling parameter values.

    Args:
        search_space:
            The search space. If any transformations are to be applied, parameter configurations
            are assumed to hold parameter values for all of the distributions defined in this
            search space. Otherwise, assertion failures will be raised.
        transform_log:
            If :obj:`True`, apply log/exp operations to the bounds and parameters with
            corresponding distributions in log space during transformation/untransformation.
            Should always be :obj:`True` if any parameters are going to be sampled from the
            transformed space.
        transform_step:
            If :obj:`True`, offset the lower and higher bounds by a half step each, increasing the
            space by one step. This allows fair sampling for values close to the bounds.
            Should always be :obj:`True` if any parameters are going to be sampled from the
            transformed space.
        transform_0_1:
            If :obj:`True`, apply a linear transformation to the bounds and parameters so that
            they are in the unit cube.

    Attributes:
        bounds:
            Constructed bounds from the given search space.
        column_to_encoded_columns:
            Constructed mapping from original parameter column index to encoded column indices.
        encoded_column_to_column:
            Constructed mapping from encoded column index to original parameter column index.

    Note:
        Parameter values are not scaled to the unit cube.

    Note:
        ``transform_log`` and ``transform_step`` are useful for constructing bounds and parameters
        without any actual transformations by setting those arguments to :obj:`False`. This is
        needed for e.g. the hyperparameter importance assessments.

    c                z    t        |||      \  }}}|| _        || _        || _        || _        || _        || _        y N)_transform_search_space_raw_bounds_column_to_encoded_columns_encoded_column_to_column_search_space_transform_log_transform_0_1)selfsearch_spacetransform_logtransform_steptransform_0_1boundscolumn_to_encoded_columnsencoded_column_to_columns           J/var/www/html/planif/env/lib/python3.12/site-packages/optuna/_transform.py__init__z_SearchSpaceTransform.__init__=   sS     G^-G
C)+C "*C')A&)++    c                    | j                   r2t        j                  ddgg| j                  j                  d   z        S | j                  S )N        g      ?r   )r   nparrayr   shaper   s    r   r   z_SearchSpaceTransform.boundsN   sB    88c3ZL4+;+;+A+A!+DDEE###r   c                    | j                   S r   )r   r$   s    r   r   z/_SearchSpaceTransform.column_to_encoded_columnsU   s    ...r   c                    | j                   S r   )r   r$   s    r   r   z._SearchSpaceTransform.encoded_column_to_columnY   s    ---r   c                   t        j                  | j                  j                  d   t         j                        }d}| j
                  j                         D ]  \  }}||v sJ d       ||   }t        |t              r;t        |j                  |            }d|||z   <   |t        |j                        z  }at        ||| j                        ||<   |dz  } | j                  ro| j                  dddf   | j                  dddf   k(  }d||<   ||    | j                  | df   z
  | j                  | df   | j                  | df   z
  z  || <   |S )a5  Transform a parameter configuration from actual values to continuous space.

        Args:
            params:
                A parameter configuration to transform.

        Returns:
            A 1-dimensional ``numpy.ndarray`` holding the transformed parameters in the
            configuration.

        r   dtypez7Parameter configuration must contain all distributions.   N      ?)r!   zerosr   r#   float64r   items
isinstancer   intto_internal_reprlenchoices_transform_numerical_paramr   r   )	r   paramstrans_params	bound_idxnamedistributionparam
choice_idxsingle_masks	            r   	transformz_SearchSpaceTransform.transform]   sv    xx 0 0 6 6q 9L	"&"4"4":":"< 	D,6>\#\\>4LE,(?@ !>!>u!EF
78Y34S!5!566	*D<)<)<+Y' Q		 **1a40D4D4DQT4JJK(+L%k\*T-=-={lAo-NN!!;,/2T5E5E{lTUo5VV*XL+& r   c                    |j                   | j                  j                   d   fk(  sJ | j                  r>| j                  dddf   || j                  dddf   | j                  dddf   z
  z  z   }i }t        | j                  j                         | j                        D ]g  \  \  }}}||   }t        |t              r |j                  |j                               }n%t        |j                         || j                        }|||<   i |S )a  Untransform a parameter configuration from continuous space to actual values.

        Args:
            trans_params:
                A 1-dimensional ``numpy.ndarray`` in the transformed space corresponding to a
                parameter configuration.

        Returns:
            A dictionary of an untransformed parameter configuration. Keys are parameter names.
            Values are untransformed parameter values.

        r   Nr*   )r#   r   r   zipr   r.   r   r/   r   to_external_reprargmax_untransform_numerical_paramitemr   )r   r6   r5   r8   r9   encoded_columnstrans_paramr:   s           r   untransformz!_SearchSpaceTransform.untransform   s    !!d&6&6&<&<Q&?%AAAA++AqD1L  A&)9)9!Q$)??5 L 58$$&(F(F6
 	!1 T</ '7K,(?@$55k6H6H6JK4$$&d6I6I !F4L	! r   N)TTF)
r   dict[str, BaseDistribution]r   boolr   rH   r   rH   returnNone)rI   
np.ndarray)rI   zlist[np.ndarray])r5   dict[str, Any]rI   rK   )r6   rK   rI   rL   )__name__
__module____qualname____doc__r   propertyr   r   r   r=   rF    r   r   r
   r
      s    ,b ###,1, , 	,
 , 
," $ $ / / . .$L%r   r
   c                J   t        |       dkD  sJ d       t        d | j                         D              }t        j                  |dft        j
                        }g }t        j                  |t        j                        }d}| j                         D ]  }|}	t        |	t              r[t        |	j                        }
d||||
z    t        j                  |||
z         }t        |      ||<   |j                  |       ||
z  }qt        |	t        t        f      rst        |	t              r|	j                  H|rd|	j                  z  nd}t        |	j                   |	|      |z
  t        |	j"                  |	|      |z   f}nt        |	j                   |	|      t        |	j"                  |	|      f}nt        |	t              r|rd|	j                  z  nd}|	j$                  r5t        |	j                   |z
  |	|      t        |	j"                  |z   |	|      f}n<t        |	j                   |	|      |z
  t        |	j"                  |	|      |z   f}nJ d	       |||<   t        j&                  |      }t        |      ||<   |j                  |       |d
z  }J d	        ||k(  sJ |||fS )Nr   z/Cannot transform if no distributions are given.c              3  j   K   | ]+  }t        |t              rt        |j                        nd  - yw)r*   N)r/   r   r2   r3   ).0ds     r   	<genexpr>z*_transform_search_space.<locals>.<genexpr>   s/       %Q(?@AIIaGs   13   r(   )r   r*   r+   r    *Should not reach. Unexpected distribution.r*   )r2   sumvaluesr!   emptyr-   int64r/   r   r3   arangeappendr   r   stepr4   lowhighlog
atleast_1d)r   r   r   n_boundsr   r   r   r7   r9   rV   	n_choicesrD   	half_stepbdsencoded_columns                  r   r   r      s    |q S"SS  $$& H
 XXxm2::6F24!xxAI$++- 1Ga01AIII8>F9y945 ii	9y3HIO8;<U8V$_5%,,_="I!
 !./66%0>affCI2155!]KiW21661mLyXC 3155!]K21661mLC A/,:C!&&L	55215593DaW2166I3Eq-XC 3155!]KiW21661mLyXC
 KJJu #F9]]95N7:;T7U$^4%,,^<NIFFF5c1Gf    ,.FFFr   c                v   |}t        |t              rJ d       t        |t              r=|j                  r$|rt	        j                  |       n
t        |       }|S t        |       }|S t        |t              r=|j                  r$|rt	        j                  |       n
t        |       }|S t        |       }|S J d       )N,Should not reach. Should be one-hot encoded.rY   )r/   r   r   rc   mathfloatr   )r:   r9   r   rV   rE   s        r   r4   r4      s     	A!,-DDDu	A(	)55-:$((5/eK   ,K  
A	'55-:$((5/eK 	  ,K  	CBBur   c           	        |}t        |t              rJ d       t        |t              rG|j                  re|rt	        j
                  |       n| }|j                         r	 |S t        |t        j                  |j                  |j                  dz
              }|S |j                  }t        t        j                  t        j                  | |j                  z
  |j                  z        |j                  z  |j                  z   |j                  |j                              }|S |j                         r| }|S t        | t        j                  |j                  |j                  dz
              }|S t        |t               r|j                  rk|r\t#        t        j                  t        j                  t	        j
                  |             |j                  |j                              }|S t#        |       }|S t#        t        j                  t        j                  | |j                  z
  |j                  z        |j                  z  |j                  z   |j                  |j                              }|S J d       )Nrk   r*   rY   )r/   r   r   rc   rl   expsingleminr!   	nextafterrb   r`   rm   cliproundra   r   r0   )rE   r9   r   rV   r:   s        r   rB   rB   	  s    	A!,-DDDu	A(	)55-:DHH[)Exxz2 L/ E2<<
#CD. L- VV+"5!?@166IAEEQSTSXSXZ[Z`Z`aE* L# xxz#  L Kaffaffqj)IJ L 
A	'55BGGBHHTXXk-B$CQUUAFFST L K( L +"5!?@166IAEEQSTSXSXZ[Z`Z`aE L 	CBBur   )r   rG   r   rH   r   rH   rI   z/tuple[np.ndarray, list[np.ndarray], np.ndarray])r:   int | floatr9   r   r   rH   rI   rm   )rE   rm   r9   r   r   rH   rI   ru   )
__future__r   rl   typingr   numpyr!   optuna.distributionsr   r   r   r   r
   r   r4   rB   rR   r   r   <module>rz      s    "    1 8 2 0Z ZzDG-DG>BDGTXDG4DGN&6GK
.$$&6$GK$$r   