o
    ci3=                     @   s   d dl mZmZmZ d dlZd dlZd dlm	Z	 d dl
mZmZmZmZmZ d dlmZ d dlmZ eddG d	d
 d
eZeddG dd deZeddG dd deZeddG dd deZdS )    )ListOptionalTupleN)Dataset)AbsMaxMaxMeanMinStd)Preprocessor)	PublicAPIalpha)	stabilityc                   @   Z   e Zd ZdZddee deee  fddZdede	fd	d
Z
dejfddZdd ZdS )StandardScalerav	  Translate and scale each column by its mean and standard deviation,
    respectively.

    The general formula is given by

    .. math::

        x' = \frac{x - \bar{x}}{s}

    where :math:`x` is the column, :math:`x'` is the transformed column,
    :math:`\bar{x}` is the column average, and :math:`s` is the column's sample
    standard deviation. If :math:`s = 0` (i.e., the column is constant-valued),
    then the transformed column will contain zeros.

    .. warning::
        :class:`StandardScaler` works best when your data is normal. If your data isn't
        approximately normal, then the transformed features won't be meaningful.

    Examples:
        >>> import pandas as pd
        >>> import ray
        >>> from ray.data.preprocessors import StandardScaler
        >>>
        >>> df = pd.DataFrame({"X1": [-2, 0, 2], "X2": [-3, -3, 3], "X3": [1, 1, 1]})
        >>> ds = ray.data.from_pandas(df)  # doctest: +SKIP
        >>> ds.to_pandas()  # doctest: +SKIP
           X1  X2  X3
        0  -2  -3   1
        1   0  -3   1
        2   2   3   1

        Columns are scaled separately.

        >>> preprocessor = StandardScaler(columns=["X1", "X2"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
                 X1        X2  X3
        0 -1.224745 -0.707107   1
        1  0.000000 -0.707107   1
        2  1.224745  1.414214   1

        Constant-valued columns get filled with zeros.

        >>> preprocessor = StandardScaler(columns=["X3"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
           X1  X2   X3
        0  -2  -3  0.0
        1   0  -3  0.0
        2   2   3  0.0

        >>> preprocessor = StandardScaler(
        ...     columns=["X1", "X2"],
        ...     output_columns=["X1_scaled", "X2_scaled"]
        ... )
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
           X1  X2  X3  X1_scaled  X2_scaled
        0  -2  -3   1  -1.224745  -0.707107
        1   0  -3   1   0.000000  -0.707107
        2   2   3   1   1.224745   1.414214

    Args:
        columns: The columns to separately scale.
        output_columns: The names of the transformed columns. If None, the transformed
            columns will be the same as the input columns. If not None, the length of
            ``output_columns`` must match the length of ``columns``, othwerwise an error
            will be raised.
    Ncolumnsoutput_columnsc                 C      || _ t||| _d S Nr   r   #_derive_and_validate_output_columnsr   selfr   r    r   Q/home/ubuntu/.local/lib/python3.10/site-packages/ray/data/preprocessors/scaler.py__init__Q      
zStandardScaler.__init__datasetreturnc                 C   s:   dd | j D }dd | j D }|jg ||R  | _| S )Nc                 S      g | ]}t |qS r   )r   .0colr   r   r   
<listcomp>X       z'StandardScaler._fit.<locals>.<listcomp>c                 S   s   g | ]}t |d dqS )r   )ddof)r
   r    r   r   r   r#   Y       r   	aggregatestats_)r   r   mean_aggregatesstd_aggregatesr   r   r   _fitW   s   zStandardScaler._fitdfc                    .   dt jf fdd}| j || j< |S )Nsc                    sb    j d| j d } j d| j d }|d u s|d u r%tj| d d < | S |dkr+d}| | | S )Nzmean()zstd(r      )r)   namenpnan)r/   s_means_stdr   r   r   column_standard_scaler^   s   z@StandardScaler._transform_pandas.<locals>.column_standard_scalerpdSeriesr   	transformr   )r   r-   r8   r   r7   r   _transform_pandas]   s   z StandardScaler._transform_pandasc                 C      | j j d| jd| jdS N	(columns=z, output_columns=r0   	__class____name__r   r   r7   r   r   r   __repr__p      zStandardScaler.__repr__r   rC   
__module____qualname____doc__r   strr   r   r   r   r,   r:   	DataFramer=   rD   r   r   r   r   r      s     Cr   c                   @   r   )MinMaxScalera  Scale each column by its range.

    The general formula is given by

    .. math::

        x' = \frac{x - \min(x)}{\max{x} - \min{x}}

    where :math:`x` is the column and :math:`x'` is the transformed column. If
    :math:`\max{x} - \min{x} = 0` (i.e., the column is constant-valued), then the
    transformed column will get filled with zeros.

    Transformed values are always in the range :math:`[0, 1]`.

    .. tip::
        This can be used as an alternative to :py:class:`StandardScaler`.

    Examples:
        >>> import pandas as pd
        >>> import ray
        >>> from ray.data.preprocessors import MinMaxScaler
        >>>
        >>> df = pd.DataFrame({"X1": [-2, 0, 2], "X2": [-3, -3, 3], "X3": [1, 1, 1]})   # noqa: E501
        >>> ds = ray.data.from_pandas(df)  # doctest: +SKIP
        >>> ds.to_pandas()  # doctest: +SKIP
           X1  X2  X3
        0  -2  -3   1
        1   0  -3   1
        2   2   3   1

        Columns are scaled separately.

        >>> preprocessor = MinMaxScaler(columns=["X1", "X2"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
            X1   X2  X3
        0  0.0  0.0   1
        1  0.5  0.0   1
        2  1.0  1.0   1

        Constant-valued columns get filled with zeros.

        >>> preprocessor = MinMaxScaler(columns=["X3"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
           X1  X2   X3
        0  -2  -3  0.0
        1   0  -3  0.0
        2   2   3  0.0

        >>> preprocessor = MinMaxScaler(columns=["X1", "X2"], output_columns=["X1_scaled", "X2_scaled"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
           X1  X2  X3  X1_scaled  X2_scaled
        0  -2  -3   1        0.0        0.0
        1   0  -3   1        0.5        0.0
        2   2   3   1        1.0        1.0

    Args:
        columns: The columns to separately scale.
        output_columns: The names of the transformed columns. If None, the transformed
            columns will be the same as the input columns. If not None, the length of
            ``output_columns`` must match the length of ``columns``, othwerwise an error
            will be raised.
    Nr   r   c                 C   r   r   r   r   r   r   r   r      r   zMinMaxScaler.__init__r   r   c                    s&    fddt tfD }|j|  _ S )Nc                    s    g | ]} j D ]}||qqS r   )r   )r!   Aggr"   r7   r   r   r#      s     z%MinMaxScaler._fit.<locals>.<listcomp>)r	   r   r(   r)   r   r   
aggregatesr   r7   r   r,      s   zMinMaxScaler._fitr-   c                    r.   )Nr/   c                    sH    j d| j d } j d| j d }|| }|dkrd}| | | S )Nzmin(r0   zmax(r   r1   r)   r2   )r/   s_mins_maxdiffr7   r   r   column_min_max_scaler   s   z=MinMaxScaler._transform_pandas.<locals>.column_min_max_scalerr9   )r   r-   rT   r   r7   r   r=      s   zMinMaxScaler._transform_pandasc                 C   r>   r?   rA   r7   r   r   r   rD      rE   zMinMaxScaler.__repr__r   rF   r   r   r   r   rL   t   s     ?rL   c                   @   r   )MaxAbsScalera@  Scale each column by its absolute max value.

    The general formula is given by

    .. math::

        x' = \frac{x}{\max{\vert x \vert}}

    where :math:`x` is the column and :math:`x'` is the transformed column. If
    :math:`\max{\vert x \vert} = 0` (i.e., the column contains all zeros), then the
    column is unmodified.

    .. tip::
        This is the recommended way to scale sparse data. If you data isn't sparse,
        you can use :class:`MinMaxScaler` or :class:`StandardScaler` instead.

    Examples:
        >>> import pandas as pd
        >>> import ray
        >>> from ray.data.preprocessors import MaxAbsScaler
        >>>
        >>> df = pd.DataFrame({"X1": [-6, 3], "X2": [2, -4], "X3": [0, 0]})   # noqa: E501
        >>> ds = ray.data.from_pandas(df)  # doctest: +SKIP
        >>> ds.to_pandas()  # doctest: +SKIP
           X1  X2  X3
        0  -6   2   0
        1   3  -4   0

        Columns are scaled separately.

        >>> preprocessor = MaxAbsScaler(columns=["X1", "X2"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
            X1   X2  X3
        0 -1.0  0.5   0
        1  0.5 -1.0   0

        Zero-valued columns aren't scaled.

        >>> preprocessor = MaxAbsScaler(columns=["X3"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
           X1  X2   X3
        0  -6   2  0.0
        1   3  -4  0.0

        >>> preprocessor = MaxAbsScaler(columns=["X1", "X2"], output_columns=["X1_scaled", "X2_scaled"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
           X1  X2  X3  X1_scaled  X2_scaled
        0  -2  -3   1       -1.0       -1.0
        1   0  -3   1        0.0       -1.0
        2   2   3   1        1.0        1.0

    Args:
        columns: The columns to separately scale.
        output_columns: The names of the transformed columns. If None, the transformed
            columns will be the same as the input columns. If not None, the length of
            ``output_columns`` must match the length of ``columns``, othwerwise an error
            will be raised.
    Nr   r   c                 C   r   r   r   r   r   r   r   r     r   zMaxAbsScaler.__init__r   r   c                 C   s    dd | j D }|j| | _| S )Nc                 S   r   r   )r   r    r   r   r   r#     r$   z%MaxAbsScaler._fit.<locals>.<listcomp>r'   rN   r   r   r   r,     s   zMaxAbsScaler._fitr-   c                    r.   )Nr/   c                    s(    j d| j d }|dkrd}| | S )Nzabs_max(r0   r   r1   rP   )r/   	s_abs_maxr7   r   r   column_abs_max_scaler  s   z=MaxAbsScaler._transform_pandas.<locals>.column_abs_max_scalerr9   )r   r-   rW   r   r7   r   r=     s   
zMaxAbsScaler._transform_pandasc                 C   r>   r?   rA   r7   r   r   r   rD   *  rE   zMaxAbsScaler.__repr__r   rF   r   r   r   r   rU      s     ;rU   c                	   @   sj   e Zd ZdZ		ddee deeef deee  fddZ	d	e
d
efddZdejfddZdd ZdS )RobustScalera	  Scale and translate each column using quantiles.

    The general formula is given by

    .. math::
        x' = \frac{x - \mu_{1/2}}{\mu_h - \mu_l}

    where :math:`x` is the column, :math:`x'` is the transformed column,
    :math:`\mu_{1/2}` is the column median. :math:`\mu_{h}` and :math:`\mu_{l}` are the
    high and low quantiles, respectively. By default, :math:`\mu_{h}` is the third
    quartile and :math:`\mu_{l}` is the first quartile.

    .. tip::
        This scaler works well when your data contains many outliers.

    Examples:
        >>> import pandas as pd
        >>> import ray
        >>> from ray.data.preprocessors import RobustScaler
        >>>
        >>> df = pd.DataFrame({
        ...     "X1": [1, 2, 3, 4, 5],
        ...     "X2": [13, 5, 14, 2, 8],
        ...     "X3": [1, 2, 2, 2, 3],
        ... })
        >>> ds = ray.data.from_pandas(df)  # doctest: +SKIP
        >>> ds.to_pandas()  # doctest: +SKIP
           X1  X2  X3
        0   1  13   1
        1   2   5   2
        2   3  14   2
        3   4   2   2
        4   5   8   3

        :class:`RobustScaler` separately scales each column.

        >>> preprocessor = RobustScaler(columns=["X1", "X2"])
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
            X1     X2  X3
        0 -1.0  0.625   1
        1 -0.5 -0.375   2
        2  0.0  0.750   2
        3  0.5 -0.750   2
        4  1.0  0.000   3

        >>> preprocessor = RobustScaler(
        ...    columns=["X1", "X2"],
        ...    output_columns=["X1_scaled", "X2_scaled"]
        ... )
        >>> preprocessor.fit_transform(ds).to_pandas()  # doctest: +SKIP
           X1  X2  X3  X1_scaled  X2_scaled
        0   1  13   1       -1.0      0.625
        1   2   5   2       -0.5     -0.375
        2   3  14   2        0.0      0.750
        3   4   2   2        0.5     -0.750
        4   5   8   3        1.0      0.000

    Args:
        columns: The columns to separately scale.
        quantile_range: A tuple that defines the lower and upper quantiles. Values
            must be between 0 and 1. Defaults to the 1st and 3rd quartiles:
            ``(0.25, 0.75)``.
        output_columns: The names of the transformed columns. If None, the transformed
            columns will be the same as the input columns. If not None, the length of
            ``output_columns`` must match the length of ``columns``, othwerwise an error
            will be raised.
    g      ?g      ?Nr   quantile_ranger   c                 C   s   || _ || _t||| _d S r   )r   rZ   r   r   r   )r   r   rZ   r   r   r   r   r   t  s
   
zRobustScaler.__init__r   r   c                    s   | j d }d}| j d }| }|d fdd|||fD }i | _| jD ]N |j fdddd	}| }||\}	}}}d
tdtfdd}
|
| }|
| }|
| }|| jd  d< || jd  d< || jd  d< q&| S )Nr   g      ?r1   c                    s   g | ]}t |  qS r   )int)r!   
percentile)	max_indexr   r   r#     r&   z%RobustScaler._fit.<locals>.<listcomp>c                    s
   |  g S r   r   )r-   )r"   r   r   <lambda>  s   
 z#RobustScaler._fit.<locals>.<lambda>pandas)batch_formatdscc                 S   s   |  dd | S )Nr1   r   )take)ra   rb   r   r   r   _get_first_value  s   z+RobustScaler._fit.<locals>._get_first_valuelow_quantile(r0   median(high_quantile()	rZ   countr)   r   map_batchessortsplit_at_indicesr   rJ   )r   r   lowmedhighnum_recordssplit_indicesfiltered_datasetsorted_dataset_rd   low_valmed_valhigh_valr   )r"   r]   r   r,     s*   






zRobustScaler._fitr-   c                    r.   )Nr/   c                    sb    j d| j d } j d| j d } j d| j d }|| }|dkr+t| S | | | S )Nre   r0   rf   rg   r   )r)   r2   r3   
zeros_like)r/   s_low_qs_medians_high_qrS   r7   r   r   column_robust_scaler  s   
z<RobustScaler._transform_pandas.<locals>.column_robust_scalerr9   )r   r-   r{   r   r7   r   r=     s   zRobustScaler._transform_pandasc                 C   s&   | j j d| jd| jd| jdS )Nr@   z, quantile_range=z), output_columns=r0   )rB   rC   r   rZ   r   r7   r   r   r   rD     s   zRobustScaler.__repr__)rY   N)rC   rG   rH   rI   r   rJ   r   floatr   r   r   r   r,   r:   rK   r=   rD   r   r   r   r   rX   .  s    G


"rX   )typingr   r   r   numpyr3   r_   r:   ray.datar   ray.data.aggregater   r   r   r	   r
   ray.data.preprocessorr   ray.util.annotationsr   r   rL   rU   rX   r   r   r   r   <module>   s    g_Y