
     h<                         d dl Z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mZmZ ddlmZmZ ddlmZ dd	lmZmZ dd
lmZmZ g dZd ZddddddZ G d deee          ZdS )    N)interpolate)	spearmanr)Real   )BaseEstimatorTransformerMixinRegressorMixin)check_arraycheck_consistent_length)_check_sample_weight)Interval
StrOptions)'_inplace_contiguous_isotonic_regression_make_unique)check_increasingisotonic_regressionIsotonicRegressionc                    t          | |          \  }}|dk    }|dvrt          |           dk    rdt          j        d|z   d|z
  z            z  }dt          j        t          |           dz
            z  }t          j        |d|z  z
            }t          j        |d|z  z             }t          j        |          t          j        |          k    rt          j	        d           |S )	aG  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
    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)	xyrho_increasing_boolFF_serho_0rho_1s	            L/var/www/html/Sam_Eipo/venv/lib/python3.11/site-packages/sklearn/isotonic.pyr   r      s    D q!__FCQhO +#a&&1**$(C#I#)455549SVVaZ((( 	!dTk/**	!dTk/** 75>>RWU^^++M       Tsample_weighty_miny_max
increasingc                   |rt           j        dd         nt           j        ddd         }t          | ddt           j        t           j        g          } t          j        | |         | j                  } t          || | j        d          }t          j        ||                   }t          | |           ||4|t           j
         }|t           j
        }t          j        | |||            | |         S )	a  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_ : list of floats
        Isotonic fit of y.

    References
    ----------
    "Active set algorithms for isotonic regression; A unifying framework"
    by Michael J. Best and Nilotpal Chakravarti, section 3.
    NFr!   )	ensure_2d
input_namedtyper4   T)r4   copy)r   s_r
   float64float32arrayr4   r   ascontiguousarrayr   infclip)r!   r,   r-   r.   r/   orders         r)   r   r   R   s    L #3BE!!!HHdddEA3rz2:>VWWWA
5)))A(tTTTM(u)=>>M+A}===E-=VGE=FE
5%###U8Or*   c                        e Zd ZU dZ eeddd          dg ee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Z
d Zd ZddZddZd Zd Zd ZddZ fdZ fdZd Z x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...])
    Nboth)closedbooleanauto>   nanr=   raiser-   r.   r/   out_of_bounds_parameter_constraintsTrD   c                >    || _         || _        || _        || _        d S NrF   )selfr-   r.   r/   rG   s        r)   __init__zIsotonicRegression.__init__   s%    

$*r*   c                 z    |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)rK   Xmsgs      r)   _check_input_data_shapez*IsotonicRegression._check_input_data_shape   sH    !!
a*  S//! r*   c                     | j         dk    }t                    dk    rfd| _        dS t          j        |d|          | _        dS )zBuild the f_ interp1d function.rE   r   c                 8                         | j                  S rJ   )repeatrP   )r    r!   s    r)   <lambda>z-IsotonicRegression._build_f.<locals>.<lambda>  s     1 1 r*   linear)kindbounds_errorN)rG   r   f_r   interp1d)rK   rR   r!   r[   s     ` r)   _build_fzIsotonicRegression._build_f   s[     )W4q66Q;;1111DGGG!*18,  DGGGr*   c           	        
 |                      |           |                    d          }| j        dk    rt          ||          | _        n| j        | _        t          |||j                  }|dk    }||         ||         ||         }}}t          j        ||f          

fd|||fD             \  }}}t          |||          \  }}}|}t          ||| j        | j        | j                  }t          j        |          t          j        |          c| _        | _        |rt          j        t%          |          ft&                    }	t          j        t          j        |dd         |dd	                   t          j        |dd         |d
d                             |	dd<   ||	         ||	         fS ||fS )z Build the y_ IsotonicRegression.r1   rC   r5   r   c                      g | ]
}|         S  ra   ).0r:   r>   s     r)   
<listcomp>z/IsotonicRegression._build_y.<locals>.<listcomp>  s    OOOuU|OOOr*   r+   r   NrN   )rT   reshaper/   r   increasing_r   r4   r   lexsortr   r   r-   r.   minmaxX_min_X_max_onesr   bool
logical_or	not_equal)rK   rR   r!   r,   trim_duplicatesmaskunique_Xunique_yunique_sample_weight	keep_datar>   s             @r)   _build_yzIsotonicRegression._build_y  s   $$Q'''IIbMM ?f$$/155D#D -]AQWMMMq gqwd0Cm1
Aq6""OOOO!Q9NOOO1m3?1m3T3T0(0.**'
 
 
 $&6!99bfQii T[ 	Q	666I !mQqtWaf--r|AadGQqrrU/K/K IadO Y<9-- a4Kr*   c                 f   |                                   t          dd          }t          |fdt          j        t          j        gd|}t          |fd|j        d|}t          |||           |                     |||          \  }}||c| _	        | _
        |                     ||           | 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_sparser2   rR   )r3   r4   r!   )_validate_paramsdictr
   r   r8   r9   r4   r   rv   X_thresholds_y_thresholds_r^   )rK   rR   r!   r,   check_paramss        r)   fitzIsotonicRegression.fit9  s    8 	%5AAA
bj"*%=
 
AM
 
 IcIILII1m444 }}Q=111 23A.D. 	ar*   c                    t          | d          r| j        j        }nt          j        }t          ||d          }|                     |           |                    d          }| j        dk    r t          j	        || 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)r4   r2   r1   r=   )hasattrr{   r4   r   r8   r
   rT   re   rG   r=   rj   rk   r\   astype)rK   Tr4   ress       r)   
_transformzIsotonicRegression._transformk  s     4)) 	&,EEJE%888$$Q'''IIbMM''4;44Aggajj jj!!
r*   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   rK   r   s     r)   	transformzIsotonicRegression.transform  s      q!!!r*   c                 ,    |                      |          S )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   s     r)   predictzIsotonicRegression.predict  s     q!!!r*   c                 |    | j         j                                        }t          j        | dgt
                    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"].
        0r5   )	__class____name__lowerr   asarrayobject)rK   input_features
class_names      r)   get_feature_names_outz(IsotonicRegression.get_feature_names_out  s;     ^,2244
zj+++,F;;;;r*   c                 t    t                                                      }|                    dd           |S )z0Pickle-protocol - return state of the estimator.r\   N)super__getstate__poprK   stater   s     r)   r   zIsotonicRegression.__getstate__  s1    $$&&		$r*   c                     t                                          |           t          | d          r2t          | 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   r^   r{   r|   r   s     r)   r   zIsotonicRegression.__setstate__  sz    
 	U###4)) 	BgdO.L.L 	BMM$,d.@AAAAA	B 	B 	B 	Br*   c                     ddgiS )NX_types1darrayra   )rK   s    r)   
_more_tagszIsotonicRegression._more_tags  s    I;''r*   )TrJ   )r   
__module____qualname____doc__r   r   r   rH   rz   __annotations__rL   rT   r^   rv   r~   r   r   r   r   r   r   r   __classcell__)r   s   @r)   r   r      s        [ [| (4tF;;;TB(4tF;;;TB **fX"6"67$*%=%=%=>>?	$ $D    !%DTQV + + + + +" " "
 
 
/ / / /b0 0 0 0d  <" " "$" " "&< < < <     B B B B B( ( ( ( ( ( (r*   r   )numpyr   scipyr   scipy.statsr   numbersr   r   r   baser   r   r	   utilsr
   r   utils.validationr   utils._param_validationr   r   	_isotonicr   r   __all__r   r   r   ra   r*   r)   <module>r      sY             ! ! ! ! ! !         A A A A A A A A A A 7 7 7 7 7 7 7 7 2 2 2 2 2 2 9 9 9 9 9 9 9 9 L L L L L L L L L
K
K8 8 8x D4 4 4 4 4nF( F( F( F( F()9= F( F( F( F( F(r*   