
    -iC                     f   S r SSKrSSKrSSKJr  SSKrSSKJrJ	r	  SSK
Jr  SSKJr  SSKJrJr  SS	KJrJrJrJr  SS
KJrJr  SSKJrJrJr  SSKJrJr  SSK J!r!J"r"  / SQr#\" S/S/S.SS9S 5       r$\" S/SS/\" \SSSS9S/\" \SSSS9S/S/S.SS9SSSSS.S j5       r% " S S\\\5      r&g)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)IsotonicRegressioncheck_increasingisotonic_regressionz
array-likexyTprefer_skip_nested_validationc                    [        X5      u  p#US:  nUS;  a  [        U 5      S:  a  S[        R                  " SU-   SU-
  -  5      -  nS[        R                  " [        U 5      S-
  5      -  n[        R
                  " USU-  -
  5      n[        R
                  " USU-  -   5      n[        R                  " U5      [        R                  " U5      :w  a  [        R                  " S5        U$ )	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_1s	            C/var/www/html/venv/lib/python3.13/site-packages/sklearn/isotonic.pyr   r      s    f q_FCQhO +#a&1*$((C#I#)455499SVaZ(( 		!dTk/*		!dTk/* 775>RWWU^+MM     bothclosedboolean)r   sample_weighty_miny_max
increasingr9   r:   r;   r<   c                   [        U SS[        R                  [        R                  /S9n [        [        S5      :  a?  [        R                  " XUS9n[        R                  " UR                  U R                  S9n OU(       a  [        R                  SS O[        R                  SSS2   n[        R                  " X   U R                  S9n [        XU R                  S	S
9n[        R                  " X   5      n[        X5        X   n Uc  Ub>  Uc  [        R                   * nUc  [        R                   n[        R"                  " XX05        U $ )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_ : 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   weightsr<   rA   NT)rA   copy)r   r(   float64float32r   r   r   r   asarrayr   rA   s_arrayr   ascontiguousarrayr	   infclip)r   r9   r:   r;   r<   resorders          r3   r   r   f   s   n 	A3rzz2::>VWA-11**:
 JJsuuAGG, 'aBEE$B$KHHQXQWW-,]QWWSWX,,]-AB/AHE-=VVGE=FFE
%#Hr4   c                   @  ^  \ rS rSr% SrS\R                  0rS\R                  0r\	" \
SSSS9S/\	" \
SSSS9S/S\" S15      /\" 1 S	k5      /S
.r\\S'   SSSSS
.S jrS rS rSS jr\" SS9SS j5       rS rS rS rSS jrU 4S jrU 4S jrU 4S jrSrU =r$ )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])
TNr5   r6   r8   auto>   nanrM   raiser:   r;   r<   out_of_bounds_parameter_constraintsTrT   c                4    Xl         X l        X0l        X@l        g NrV   )selfr:   r;   r<   rW   s        r3   __init__IsotonicRegression.__init__   s    

$*r4   c                     UR                   S:X  d1  UR                   S:X  a  UR                  S   S:X  d  Sn[        U5      eg g )Nr      zKIsotonic regression input X should be a 1d array or 2d array with 1 feature)ndimshape
ValueError)r[   Xmsgs      r3   _check_input_data_shape*IsotonicRegression._check_input_data_shape&  sC    !!
a*  S/! 1@r4   c                    ^ U R                   S:H  n[        T5      S:X  a  U4S jU l        g[        R                  " UTSUS9U l        g)zBuild the f_ interp1d function.rU   r   c                 :   > TR                  U R                  5      $ rZ   )repeatra   r   s    r3   <lambda>-IsotonicRegression._build_f.<locals>.<lambda>4  s     1r4   linear)kindbounds_errorN)rW   r#   f_r   interp1d)r[   rc   r   rn   s     ` r3   _build_fIsotonicRegression._build_f.  sB     ))W4q6Q;1DG!**18,DGr4   c           	      N   U R                  U5        UR                  S5      nU R                  S:X  a  [        X5      U l        OU R                  U l        [        X1UR                  S9nUS:  nX   X%   X5   p2n[        R                  " X!45      nXU4 Vs/ s H  owU   PM	     snu  pn[        XU5      u  pn
Un[        U	U
U R                  U R                  U R                  S9n[        R                  " U5      [        R                  " U5      sU l        U l        U(       a{  [        R"                  " [%        U5      4[&        S9n[        R(                  " [        R*                  " USS USS 5      [        R*                  " USS US	S 5      5      USS& X   X+   4$ X4$ s  snf )
z Build the y_ IsotonicRegression.rD   rS   rC   r   r=   r   Nr_   )re   reshaper<   r   increasing_r   rA   r(   lexsortr
   r   r:   r;   minmaxX_min_X_max_onesr#   bool
logical_or	not_equal)r[   rc   r   r9   trim_duplicatesmaskrO   rJ   unique_Xunique_yunique_sample_weight	keep_datas               r3   _build_yIsotonicRegression._build_y:  s   $$Q'IIbM ??f$/5D#D -]QWWMq gqw0Cm

A6":;9NO9NU|9NOm3?m3T00.****''
 $&66!9bffQi T[Q	6I !mmQqWaf-r||AaGQqrU/KIaO <-- 4K; Ps   F"r   c                 $   [        SSS9n[        U4S[        R                  [        R                  /S.UD6n[        U4SUR
                  S.UD6n[        XU5        U R                  XU5      u  pXsU l        U l	        U R                  X5        U $ )aF  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?   rc   )r@   rA   r   )dictr   r(   rF   rG   rA   r   r   X_thresholds_y_thresholds_rq   )r[   rc   r   r9   check_paramss        r3   fitIsotonicRegression.fitk  s    : %5A
bjj"**%=
AM
 IcILIm4 }}Q=1 23.D. 	ar4   c                    [        U S5      (       a  U R                  R                  nO[        R                  n[        XSS9nU R                  U5        UR                  S5      nU R                  S:X  a+  [        R                  " XR                  U R                  5      nU R                  U5      nUR                  UR                  5      nU$ )aW  `_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)rA   r?   rD   rM   )hasattrr   rA   r(   rF   r   re   ru   rW   rM   rz   r{   ro   astype)r[   rR   rA   rN   s       r3   
_transformIsotonicRegression._transform  s     4))&&,,EJJE%8$$Q'IIbM';;4Aggaj jj!
r4   c                 $    U R                  U5      $ )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   r[   rR   s     r3   	transformIsotonicRegression.transform  s      q!!r4   c                 $    U R                  U5      $ )zPredict 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     r3   predictIsotonicRegression.predict  s     q!!r4   c                     [        U S5        U R                  R                  R                  5       n[        R
                  " U S3/[        S9$ )a  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"].
ro   0rC   )r   	__class____name__lowerr(   rH   object)r[   input_features
class_names      r3   get_feature_names_out(IsotonicRegression.get_feature_names_out  sA     	d#^^,,224
zzj\+,F;;r4   c                 H   > [         TU ]  5       nUR                  SS5        U$ )z0Pickle-protocol - return state of the estimator.ro   N)super__getstate__popr[   stater   s     r3   r   IsotonicRegression.__getstate__  s#    $&		$r4   c                    > [         TU ]  U5        [        U S5      (       a9  [        U S5      (       a'  U R                  U R                  U R
                  5        ggg)z^Pickle-protocol - set state of the estimator.

We need to rebuild the interpolation function.
r   r   N)r   __setstate__r   rq   r   r   r   s     r3   r   IsotonicRegression.__setstate__  sN    
 	U#4))gdO.L.LMM$,,d.@.@A /M)r4   c                 h   > [         TU ]  5       nSUR                  l        SUR                  l        U$ )NTF)r   __sklearn_tags__
input_tagsone_d_arraytwo_d_array)r[   tagsr   s     r3   r   #IsotonicRegression.__sklearn_tags__  s-    w')&*#&+#r4   )
r{   rz   r   ro   r<   rv   rW   r;   r:   r   )TrZ   )r   
__module____qualname____firstlineno____doc__r   UNUSED._IsotonicRegression__metadata_request__predict0_IsotonicRegression__metadata_request__transformr   r   r   rX   r   __annotations__r\   re   rq   r   r   r   r   r   r   r   r   r   r   __static_attributes____classcell__)r   s   @r3   r   r      s    [| $'(8(?(?"@%(*:*A*A$B! 4tF;TB4tF;TB *fX"67$%=>?	$D  !%DTQV +"
/b 5/ 6/b<"$"&<"B r4   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    r4   r3   <module>r      s    >
     ' ! * L O O 7 J J 7 C
K ^^ #'BBJ ^&-4tF;TB4tF;TB k #'	 DD	DNN)9= Nr4   