o
    RhC                  
   @   sN  d Z ddlZddlZddlmZ ddlZddlmZm	Z	 ddl
mZ ddlmZ ddlmZmZ dd	lmZmZmZmZ dd
lmZmZ ddlmZmZmZ ddlmZmZ ddl m!Z!m"Z" g dZ#edgdgddddd Z$edgddgeedddddgeedddddgdgddddddddddZ%G dd deeeZ&dS )z8Isotonic regression for obtaining monotonic fit to data.    N)Real)interpolateoptimize)	spearmanr)metadata_routing   )'_inplace_contiguous_isotonic_regression_make_unique)BaseEstimatorRegressorMixinTransformerMixin_fit_context)check_arraycheck_consistent_length)Interval
StrOptionsvalidate_params)parse_versionsp_base_version)_check_sample_weightcheck_is_fitted)check_increasingisotonic_regressionIsotonicRegressionz
array-like)xyTprefer_skip_nested_validationc           	      C   s   t | |\}}|dk}|dvrNt| dkrNdtd| d|   }dtt| d  }t|d|  }t|d|  }t|t|krNt	d |S )	a?  Determine whether y is monotonically correlated with x.

    y is found increasing or decreasing with respect to x based on a Spearman
    correlation test.

    Parameters
    ----------
    x : array-like of shape (n_samples,)
            Training data.

    y : array-like of shape (n_samples,)
        Training target.

    Returns
    -------
    increasing_bool : boolean
        Whether the relationship is increasing or decreasing.

    Notes
    -----
    The Spearman correlation coefficient is estimated from the data, and the
    sign of the resulting estimate is used as the result.

    In the event that the 95% confidence interval based on Fisher transform
    spans zero, a warning is raised.

    References
    ----------
    Fisher transformation. Wikipedia.
    https://en.wikipedia.org/wiki/Fisher_transformation

    Examples
    --------
    >>> from sklearn.isotonic import check_increasing
    >>> x, y = [1, 2, 3, 4, 5], [2, 4, 6, 8, 10]
    >>> check_increasing(x, y)
    np.True_
    >>> y = [10, 8, 6, 4, 2]
    >>> check_increasing(x, y)
    np.False_
    r   )g            ?   g      ?r   r   g\(\?zwConfidence interval of the Spearman correlation coefficient spans zero. Determination of ``increasing`` may be suspect.)
r   lenmathlogsqrttanhnpsignwarningswarn)	r   r   rho_increasing_boolFF_serho_0rho_1 r0   R/home/air/sanwanet/backup_V2/venv/lib/python3.10/site-packages/sklearn/isotonic.pyr      s   3r   bothclosedboolean)r   sample_weighty_miny_max
increasingr6   r7   r8   r9   c                C   s   t | ddtjtjgd} ttdkr$tj| ||d}tj|j	| j
d} n4|r-tjdd ntjddd }tj| | | j
d} t|| | j
d	d
}t|| }t| | | | } |dus`|durw|du rhtj }|du rotj}t| |||  | S )a0  Solve the isotonic regression model.

    Read more in the :ref:`User Guide <isotonic>`.

    Parameters
    ----------
    y : array-like of shape (n_samples,)
        The data.

    sample_weight : array-like of shape (n_samples,), default=None
        Weights on each point of the regression.
        If None, weight is set to 1 (equal weights).

    y_min : float, default=None
        Lower bound on the lowest predicted value (the minimum value may
        still be higher). If not set, defaults to -inf.

    y_max : float, default=None
        Upper bound on the highest predicted value (the maximum may still be
        lower). If not set, defaults to +inf.

    increasing : bool, default=True
        Whether to compute ``y_`` is increasing (if set to True) or decreasing
        (if set to False).

    Returns
    -------
    y_ : ndarray of shape (n_samples,)
        Isotonic fit of y.

    References
    ----------
    "Active set algorithms for isotonic regression; A unifying framework"
    by Michael J. Best and Nilotpal Chakravarti, section 3.

    Examples
    --------
    >>> from sklearn.isotonic import isotonic_regression
    >>> isotonic_regression([5, 3, 1, 2, 8, 10, 7, 9, 6, 4])
    array([2.75   , 2.75   , 2.75   , 2.75   , 7.33...,
           7.33..., 7.33..., 7.33..., 7.33..., 7.33...])
    Fr   )	ensure_2d
input_namedtypez1.12.0)r   weightsr9   r=   NT)r=   copy)r   r%   float64float32r   r   r   r   asarrayr   r=   s_arrayr   ascontiguousarrayr   infclip)r   r6   r7   r8   r9   resorderr0   r0   r1   r   f   s&   7"
r   c                       s   e Zd ZU dZdejiZdejiZee	dddddgee	dddddgde
dhge
h dgd	Zeed
< ddddd	ddZdd Zdd Zd&ddZeddd'ddZdd Zdd Zdd Zd'ddZ fd d!Z fd"d#Z fd$d%Z  ZS )(r   a  Isotonic regression model.

    Read more in the :ref:`User Guide <isotonic>`.

    .. versionadded:: 0.13

    Parameters
    ----------
    y_min : float, default=None
        Lower bound on the lowest predicted value (the minimum value may
        still be higher). If not set, defaults to -inf.

    y_max : float, default=None
        Upper bound on the highest predicted value (the maximum may still be
        lower). If not set, defaults to +inf.

    increasing : bool or 'auto', default=True
        Determines whether the predictions should be constrained to increase
        or decrease with `X`. 'auto' will decide based on the Spearman
        correlation estimate's sign.

    out_of_bounds : {'nan', 'clip', 'raise'}, default='nan'
        Handles how `X` values outside of the training domain are handled
        during prediction.

        - 'nan', predictions will be NaN.
        - 'clip', predictions will be set to the value corresponding to
          the nearest train interval endpoint.
        - 'raise', a `ValueError` is raised.

    Attributes
    ----------
    X_min_ : float
        Minimum value of input array `X_` for left bound.

    X_max_ : float
        Maximum value of input array `X_` for right bound.

    X_thresholds_ : ndarray of shape (n_thresholds,)
        Unique ascending `X` values used to interpolate
        the y = f(X) monotonic function.

        .. versionadded:: 0.24

    y_thresholds_ : ndarray of shape (n_thresholds,)
        De-duplicated `y` values suitable to interpolate the y = f(X)
        monotonic function.

        .. versionadded:: 0.24

    f_ : function
        The stepwise interpolating function that covers the input domain ``X``.

    increasing_ : bool
        Inferred value for ``increasing``.

    See Also
    --------
    sklearn.linear_model.LinearRegression : Ordinary least squares Linear
        Regression.
    sklearn.ensemble.HistGradientBoostingRegressor : Gradient boosting that
        is a non-parametric model accepting monotonicity constraints.
    isotonic_regression : Function to solve the isotonic regression model.

    Notes
    -----
    Ties are broken using the secondary method from de Leeuw, 1977.

    References
    ----------
    Isotonic Median Regression: A Linear Programming Approach
    Nilotpal Chakravarti
    Mathematics of Operations Research
    Vol. 14, No. 2 (May, 1989), pp. 303-308

    Isotone Optimization in R : Pool-Adjacent-Violators
    Algorithm (PAVA) and Active Set Methods
    de Leeuw, Hornik, Mair
    Journal of Statistical Software 2009

    Correctness of Kruskal's algorithms for monotone regression with ties
    de Leeuw, Psychometrica, 1977

    Examples
    --------
    >>> from sklearn.datasets import make_regression
    >>> from sklearn.isotonic import IsotonicRegression
    >>> X, y = make_regression(n_samples=10, n_features=1, random_state=41)
    >>> iso_reg = IsotonicRegression().fit(X, y)
    >>> iso_reg.predict([.1, .2])
    array([1.8628..., 3.7256...])
    TNr2   r3   r5   auto>   nanrI   raiser7   r8   r9   out_of_bounds_parameter_constraintsTrN   c                C   s   || _ || _|| _|| _d S NrP   )selfr7   r8   r9   rQ   r0   r0   r1   __init__   s   
zIsotonicRegression.__init__c                 C   s6   |j dks|j dkr|jd dksd}t|d S d S )Nr      zKIsotonic regression input X should be a 1d array or 2d array with 1 feature)ndimshape
ValueError)rT   Xmsgr0   r0   r1   _check_input_data_shape&  s
   "z*IsotonicRegression._check_input_data_shapec                    s@   | j dk}t dkr fdd| _dS tj| d|d| _dS )zBuild the f_ interp1d function.rO   r   c                    s     | jS rS   )repeatrX   )r   r   r0   r1   <lambda>4  s    z-IsotonicRegression._build_f.<locals>.<lambda>linear)kindbounds_errorN)rQ   r    f_r   interp1d)rT   rZ   r   rb   r0   r^   r1   _build_f.  s   
zIsotonicRegression._build_fc           
   	      sP  |  | |d}| jdkrt||| _n| j| _t|||jd}|dk}|| || || }}}t||f  fdd|||fD \}}}t	|||\}}}|}t
||| j| j| jd}t|t|| _| _|rtjt|ftd}	tt|dd |d	d
 t|dd |dd	 |	dd< ||	 ||	 fS ||fS )z Build the y_ IsotonicRegression.r@   rM   r?   r   c                    s   g | ]}|  qS r0   r0   ).0rF   rK   r0   r1   
<listcomp>L  s    z/IsotonicRegression._build_y.<locals>.<listcomp>r:   r   NrV   )r\   reshaper9   r   increasing_r   r=   r%   lexsortr	   r   r7   r8   minmaxX_min_X_max_onesr    bool
logical_or	not_equal)
rT   rZ   r   r6   trim_duplicatesmaskunique_Xunique_yunique_sample_weight	keep_datar0   rg   r1   _build_y:  s6   


	4zIsotonicRegression._build_yr   c                 C   s~   t ddd}t|fdtjtjgd|}t|fd|jd|}t||| | |||\}}||| _| _	| 
|| | S )a  Fit the model using X, y as training data.

        Parameters
        ----------
        X : array-like of shape (n_samples,) or (n_samples, 1)
            Training data.

            .. versionchanged:: 0.24
               Also accepts 2d array with 1 feature.

        y : array-like of shape (n_samples,)
            Training target.

        sample_weight : array-like of shape (n_samples,), default=None
            Weights. If set to None, all weights will be set to 1 (equal
            weights).

        Returns
        -------
        self : object
            Returns an instance of self.

        Notes
        -----
        X is stored for future use, as :meth:`transform` needs X to interpolate
        new input data.
        F)accept_sparser;   rZ   )r<   r=   r   )dictr   r%   rB   rC   r=   r   r{   X_thresholds_y_thresholds_re   )rT   rZ   r   r6   check_paramsr0   r0   r1   fitk  s   zIsotonicRegression.fitc                 C   sr   t | dr
| jj}ntj}t||dd}| | |d}| jdkr,t	|| j
| j}| |}||j}|S )a  `_transform` is called by both `transform` and `predict` methods.

        Since `transform` is wrapped to output arrays of specific types (e.g.
        NumPy arrays, pandas DataFrame), we cannot make `predict` call `transform`
        directly.

        The above behaviour could be changed in the future, if we decide to output
        other type of arrays when calling `predict`.
        r~   F)r=   r;   r@   rI   )hasattrr~   r=   r%   rB   r   r\   rj   rQ   rI   ro   rp   rc   astype)rT   rL   r=   rJ   r0   r0   r1   
_transform  s   






zIsotonicRegression._transformc                 C   
   |  |S )a  Transform new data by linear interpolation.

        Parameters
        ----------
        T : array-like of shape (n_samples,) or (n_samples, 1)
            Data to transform.

            .. versionchanged:: 0.24
               Also accepts 2d array with 1 feature.

        Returns
        -------
        y_pred : ndarray of shape (n_samples,)
            The transformed data.
        r   rT   rL   r0   r0   r1   	transform  s   
zIsotonicRegression.transformc                 C   r   )a%  Predict new data by linear interpolation.

        Parameters
        ----------
        T : array-like of shape (n_samples,) or (n_samples, 1)
            Data to transform.

        Returns
        -------
        y_pred : ndarray of shape (n_samples,)
            Transformed data.
        r   r   r0   r0   r1   predict  s   
zIsotonicRegression.predictc                 C   s,   t | d | jj }tj| dgtdS )aK  Get output feature names for transformation.

        Parameters
        ----------
        input_features : array-like of str or None, default=None
            Ignored.

        Returns
        -------
        feature_names_out : ndarray of str objects
            An ndarray with one string i.e. ["isotonicregression0"].
        rc   0r?   )r   	__class____name__lowerr%   rD   object)rT   input_features
class_namer0   r0   r1   get_feature_names_out  s   
z(IsotonicRegression.get_feature_names_outc                    s   t   }|dd |S )z0Pickle-protocol - return state of the estimator.rc   N)super__getstate__poprT   stater   r0   r1   r     s   
zIsotonicRegression.__getstate__c                    s<   t  | t| drt| dr| | j| j dS dS dS )znPickle-protocol - set state of the estimator.

        We need to rebuild the interpolation function.
        r~   r   N)r   __setstate__r   re   r~   r   r   r   r0   r1   r     s   zIsotonicRegression.__setstate__c                    s   t   }d|j_d|j_|S )NTF)r   __sklearn_tags__
input_tagsone_d_arraytwo_d_array)rT   tagsr   r0   r1   r     s   
z#IsotonicRegression.__sklearn_tags__)TrS   )r   
__module____qualname____doc__r   UNUSED._IsotonicRegression__metadata_request__predict0_IsotonicRegression__metadata_request__transformr   r   r   rR   r}   __annotations__rU   r\   re   r{   r   r   r   r   r   r   r   r   r   __classcell__r0   r0   r   r1   r      s,   
 
^

11
	r   )'r   r!   r'   numbersr   numpyr%   scipyr   r   scipy.statsr   sklearn.utilsr   	_isotonicr   r	   baser
   r   r   r   utilsr   r   utils._param_validationr   r   r   utils.fixesr   r   utils.validationr   r   __all__r   r   r   r0   r0   r0   r1   <module>   sD    
EG