U
    3d[                     @   s   d Z ddlZddlmZ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 dddZG dd de	ZdddZdddddZG dd de	ZddddZG dd de	ZdS )z
Covariance estimators using shrinkage.

Shrinkage corresponds to regularising `cov` using a convex combination:
shrunk_cov = (1-shrinkage)*cov + shrinkage*structured_estimate.

    N)RealIntegral   )empirical_covarianceEmpiricalCovariance   )config_context)check_array)Interval皙?c                 C   sP   t | } | jd }t| | }d| |  }|jdd|d   || 7  < |S )a  Calculate a covariance matrix shrunk on the diagonal.

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

    Parameters
    ----------
    emp_cov : array-like of shape (n_features, n_features)
        Covariance matrix to be shrunk.

    shrinkage : float, default=0.1
        Coefficient in the convex combination used for the computation
        of the shrunk estimate. Range is [0, 1].

    Returns
    -------
    shrunk_cov : ndarray of shape (n_features, n_features)
        Shrunk covariance.

    Notes
    -----
    The regularized (shrunk) covariance is given by::

        (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features)

    where `mu = trace(cov) / n_features`.
    r         ?Nr   )r	   shapenptraceflat)emp_cov	shrinkage
n_featuresmu
shrunk_cov r   I/tmp/pip-unpacked-wheel-zrfo1fqw/sklearn/covariance/_shrunk_covariance.pyshrunk_covariance   s    
 r   c                       sZ   e Zd ZU dZejdeeddddgiZee	d< dd	d
d fdd
Z
dddZ  ZS )ShrunkCovariancea
  Covariance estimator with shrinkage.

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

    Parameters
    ----------
    store_precision : bool, default=True
        Specify if the estimated precision is stored.

    assume_centered : bool, default=False
        If True, data will not be centered before computation.
        Useful when working with data whose mean is almost, but not exactly
        zero.
        If False, data will be centered before computation.

    shrinkage : float, default=0.1
        Coefficient in the convex combination used for the computation
        of the shrunk estimate. Range is [0, 1].

    Attributes
    ----------
    covariance_ : ndarray of shape (n_features, n_features)
        Estimated covariance matrix

    location_ : ndarray of shape (n_features,)
        Estimated location, i.e. the estimated mean.

    precision_ : ndarray of shape (n_features, n_features)
        Estimated pseudo inverse matrix.
        (stored only if store_precision is True)

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

        .. versionadded:: 1.0

    See Also
    --------
    EllipticEnvelope : An object for detecting outliers in
        a Gaussian distributed dataset.
    EmpiricalCovariance : Maximum likelihood covariance estimator.
    GraphicalLasso : Sparse inverse covariance estimation
        with an l1-penalized estimator.
    GraphicalLassoCV : Sparse inverse covariance with cross-validated
        choice of the l1 penalty.
    LedoitWolf : LedoitWolf Estimator.
    MinCovDet : Minimum Covariance Determinant
        (robust estimator of covariance).
    OAS : Oracle Approximating Shrinkage Estimator.

    Notes
    -----
    The regularized covariance is given by:

    (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features)

    where mu = trace(cov) / n_features

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.covariance import ShrunkCovariance
    >>> from sklearn.datasets import make_gaussian_quantiles
    >>> real_cov = np.array([[.8, .3],
    ...                      [.3, .4]])
    >>> rng = np.random.RandomState(0)
    >>> X = rng.multivariate_normal(mean=[0, 0],
    ...                                   cov=real_cov,
    ...                                   size=500)
    >>> cov = ShrunkCovariance().fit(X)
    >>> cov.covariance_
    array([[0.7387..., 0.2536...],
           [0.2536..., 0.4110...]])
    >>> cov.location_
    array([0.0622..., 0.0193...])
    r   r   r   Zbothclosed_parameter_constraintsTFr   )store_precisionassume_centeredr   c                   s   t  j||d || _d S N)r   r   )super__init__r   )selfr   r   r   	__class__r   r   r!      s
     zShrunkCovariance.__init__Nc                 C   s`   |    | |}| jr,t|jd | _n|d| _t|| jd}t	|| j
}| | | S )a  Fit the shrunk covariance model to X.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Training data, where `n_samples` is the number of samples
            and `n_features` is the number of features.

        y : Ignored
            Not used, present for API consistency by convention.

        Returns
        -------
        self : object
            Returns the instance itself.
        r   r   r   )_validate_params_validate_datar   r   zerosr   	location_meanr   r   r   _set_covariance)r"   Xy
covariancer   r   r   fit   s    

zShrunkCovariance.fit)N)__name__
__module____qualname____doc__r   r   r
   r   dict__annotations__r!   r/   __classcell__r   r   r#   r   r   B   s   
T r   F  c                 C   s4  t | } t| jdkr(| jd dkr(dS | jdkr>t| d} | jd dkrVtd | j\}}|sr| | d } t	|| }| d }tj
|dd| }t
|| }d}	d}
t|D ]}t|D ]}t|| ||d  }t|| ||d  }|	t
t|j| |dd|f 7 }	|
t
t| j| | dd|f d 7 }
qt|| ||d  }|	t
t|j| |dd|| df 7 }	|
t
t| j| | dd|| df d 7 }
qt|D ]}t|| ||d  }|	t
t|j|| d |dd|f 7 }	|
t
t| j|| d | dd|f d 7 }
q|
t
t| j|| d | dd|| df d 7 }
|
|d  }
|	t
t|j|| d |dd|| df 7 }	d	||  |	| |
  }|
d
| |
   ||d   }|| }t||}|dkr(dn|| }|S )a  Estimate the shrunk Ledoit-Wolf covariance matrix.

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

    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Data from which to compute the Ledoit-Wolf shrunk covariance shrinkage.

    assume_centered : bool, default=False
        If True, data will not be centered before computation.
        Useful to work with data whose mean is significantly equal to
        zero but is not exactly zero.
        If False, data will be centered before computation.

    block_size : int, default=1000
        Size of blocks into which the covariance matrix will be split.

    Returns
    -------
    shrinkage : float
        Coefficient in the convex combination used for the computation
        of the shrunk estimate.

    Notes
    -----
    The regularized (shrunk) covariance is:

    (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features)

    where mu = trace(cov) / n_features
    r   r           r   r   BOnly one sample available. You may want to reshape your data array)ZaxisNr   g       @)r	   lenr   ndimr   reshapewarningswarnr*   intsumrangeslicedotTmin)r,   r   
block_size	n_samplesr   Zn_splitsZX2Zemp_cov_tracer   Zbeta_Zdelta_ijZrowscolsbetadeltar   r   r   r   ledoit_wolf_shrinkage   sX    !

(.06080, 
rO   r   rH   c          	      C   s   t | } t| jdkrJ| jd dkrJ|s4| |   } t| d  dfS | jdkrrt| d} t	d | j
}n
| j\}}t| ||d}t| |d}tt|| }d| | }|jd	d	|d   || 7  < ||fS )
af  Estimate the shrunk Ledoit-Wolf covariance matrix.

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

    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Data from which to compute the covariance estimate.

    assume_centered : bool, default=False
        If True, data will not be centered before computation.
        Useful to work with data whose mean is significantly equal to
        zero but is not exactly zero.
        If False, data will be centered before computation.

    block_size : int, default=1000
        Size of blocks into which the covariance matrix will be split.
        This is purely a memory optimization and does not affect results.

    Returns
    -------
    shrunk_cov : ndarray of shape (n_features, n_features)
        Shrunk covariance.

    shrinkage : float
        Coefficient in the convex combination used for the computation
        of the shrunk estimate.

    Notes
    -----
    The regularized (shrunk) covariance is:

    (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features)

    where mu = trace(cov) / n_features
    r   r   r8   r9   r;   rP   r%   r   N)r	   r<   r   r*   r   
atleast_2dr=   r>   r?   r@   sizerO   r   rB   r   r   )	r,   r   rH   r   _r   r   r   r   r   r   r   ledoit_wolf#  s,    %

   rT   c                       sZ   e Zd ZU dZejdeeddddgiZee	d< dd	d
d fdd
Z
dddZ  ZS )
LedoitWolfa  LedoitWolf Estimator.

    Ledoit-Wolf is a particular form of shrinkage, where the shrinkage
    coefficient is computed using O. Ledoit and M. Wolf's formula as
    described in "A Well-Conditioned Estimator for Large-Dimensional
    Covariance Matrices", Ledoit and Wolf, Journal of Multivariate
    Analysis, Volume 88, Issue 2, February 2004, pages 365-411.

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

    Parameters
    ----------
    store_precision : bool, default=True
        Specify if the estimated precision is stored.

    assume_centered : bool, default=False
        If True, data will not be centered before computation.
        Useful when working with data whose mean is almost, but not exactly
        zero.
        If False (default), data will be centered before computation.

    block_size : int, default=1000
        Size of blocks into which the covariance matrix will be split
        during its Ledoit-Wolf estimation. This is purely a memory
        optimization and does not affect results.

    Attributes
    ----------
    covariance_ : ndarray of shape (n_features, n_features)
        Estimated covariance matrix.

    location_ : ndarray of shape (n_features,)
        Estimated location, i.e. the estimated mean.

    precision_ : ndarray of shape (n_features, n_features)
        Estimated pseudo inverse matrix.
        (stored only if store_precision is True)

    shrinkage_ : float
        Coefficient in the convex combination used for the computation
        of the shrunk estimate. Range is [0, 1].

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

        .. versionadded:: 1.0

    See Also
    --------
    EllipticEnvelope : An object for detecting outliers in
        a Gaussian distributed dataset.
    EmpiricalCovariance : Maximum likelihood covariance estimator.
    GraphicalLasso : Sparse inverse covariance estimation
        with an l1-penalized estimator.
    GraphicalLassoCV : Sparse inverse covariance with cross-validated
        choice of the l1 penalty.
    MinCovDet : Minimum Covariance Determinant
        (robust estimator of covariance).
    OAS : Oracle Approximating Shrinkage Estimator.
    ShrunkCovariance : Covariance estimator with shrinkage.

    Notes
    -----
    The regularised covariance is:

    (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features)

    where mu = trace(cov) / n_features
    and shrinkage is given by the Ledoit and Wolf formula (see References)

    References
    ----------
    "A Well-Conditioned Estimator for Large-Dimensional Covariance Matrices",
    Ledoit and Wolf, Journal of Multivariate Analysis, Volume 88, Issue 2,
    February 2004, pages 365-411.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.covariance import LedoitWolf
    >>> real_cov = np.array([[.4, .2],
    ...                      [.2, .8]])
    >>> np.random.seed(0)
    >>> X = np.random.multivariate_normal(mean=[0, 0],
    ...                                   cov=real_cov,
    ...                                   size=50)
    >>> cov = LedoitWolf().fit(X)
    >>> cov.covariance_
    array([[0.4406..., 0.1616...],
           [0.1616..., 0.8022...]])
    >>> cov.location_
    array([ 0.0595... , -0.0075...])
    rH   r   Nleftr   r   TFr7   )r   r   rH   c                   s   t  j||d || _d S r   )r    r!   rH   )r"   r   r   rH   r#   r   r   r!     s
     zLedoitWolf.__init__c              	   C   s|   |    | |}| jr,t|jd | _n|d| _tdd  t	|| j d| j
d\}}W 5 Q R X || _| | | S )a  Fit the Ledoit-Wolf shrunk covariance model to X.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Training data, where `n_samples` is the number of samples
            and `n_features` is the number of features.
        y : Ignored
            Not used, present for API consistency by convention.

        Returns
        -------
        self : object
            Returns the instance itself.
        r   r   T)Zassume_finiterP   )r&   r'   r   r   r(   r   r)   r*   r   rT   rH   
shrinkage_r+   r"   r,   r-   r.   r   r   r   r   r/     s    
  
zLedoitWolf.fit)N)r0   r1   r2   r3   r   r   r
   r   r4   r5   r!   r/   r6   r   r   r#   r   rU   c  s   
e rU   r%   c                C   s  t | } t| jdkrL| jd dkrL|s6| |   } t | d  dfS | jdkrxt | d} t	d d}| j
}n
| j\}}t| |d}t || }t |d }||d  }|d ||d |   }|dkrdnt|| d}	d|	 | }
|
jd	d	|d   |	| 7  < |
|	fS )
a  Estimate covariance with the Oracle Approximating Shrinkage algorithm.

    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Data from which to compute the covariance estimate.

    assume_centered : bool, default=False
      If True, data will not be centered before computation.
      Useful to work with data whose mean is significantly equal to
      zero but is not exactly zero.
      If False, data will be centered before computation.

    Returns
    -------
    shrunk_cov : array-like of shape (n_features, n_features)
        Shrunk covariance.

    shrinkage : float
        Coefficient in the convex combination used for the computation
        of the shrunk estimate.

    Notes
    -----
    The regularised (shrunk) covariance is:

    (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features)

    where mu = trace(cov) / n_features

    The formula we used to implement the OAS is slightly modified compared
    to the one given in the article. See :class:`OAS` for more details.
    r   r   r8   r9   r;   r%   r   r   N)r   Zasarrayr<   r   r*   rQ   r=   r>   r?   r@   rR   r   r   rG   r   )r,   r   rI   r   r   r   alphanumZdenr   r   r   r   r   oas  s,    "


 r[   c                   @   s   e Zd ZdZdddZdS )OASa  Oracle Approximating Shrinkage Estimator.

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

    OAS is a particular form of shrinkage described in
    "Shrinkage Algorithms for MMSE Covariance Estimation"
    Chen et al., IEEE Trans. on Sign. Proc., Volume 58, Issue 10, October 2010.

    The formula used here does not correspond to the one given in the
    article. In the original article, formula (23) states that 2/p is
    multiplied by Trace(cov*cov) in both the numerator and denominator, but
    this operation is omitted because for a large p, the value of 2/p is
    so small that it doesn't affect the value of the estimator.

    Parameters
    ----------
    store_precision : bool, default=True
        Specify if the estimated precision is stored.

    assume_centered : bool, default=False
        If True, data will not be centered before computation.
        Useful when working with data whose mean is almost, but not exactly
        zero.
        If False (default), data will be centered before computation.

    Attributes
    ----------
    covariance_ : ndarray of shape (n_features, n_features)
        Estimated covariance matrix.

    location_ : ndarray of shape (n_features,)
        Estimated location, i.e. the estimated mean.

    precision_ : ndarray of shape (n_features, n_features)
        Estimated pseudo inverse matrix.
        (stored only if store_precision is True)

    shrinkage_ : float
      coefficient in the convex combination used for the computation
      of the shrunk estimate. Range is [0, 1].

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

        .. versionadded:: 1.0

    See Also
    --------
    EllipticEnvelope : An object for detecting outliers in
        a Gaussian distributed dataset.
    EmpiricalCovariance : Maximum likelihood covariance estimator.
    GraphicalLasso : Sparse inverse covariance estimation
        with an l1-penalized estimator.
    GraphicalLassoCV : Sparse inverse covariance with cross-validated
        choice of the l1 penalty.
    LedoitWolf : LedoitWolf Estimator.
    MinCovDet : Minimum Covariance Determinant
        (robust estimator of covariance).
    ShrunkCovariance : Covariance estimator with shrinkage.

    Notes
    -----
    The regularised covariance is:

    (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features)

    where mu = trace(cov) / n_features
    and shrinkage is given by the OAS formula (see References)

    References
    ----------
    "Shrinkage Algorithms for MMSE Covariance Estimation"
    Chen et al., IEEE Trans. on Sign. Proc., Volume 58, Issue 10, October 2010.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.covariance import OAS
    >>> from sklearn.datasets import make_gaussian_quantiles
    >>> real_cov = np.array([[.8, .3],
    ...                      [.3, .4]])
    >>> rng = np.random.RandomState(0)
    >>> X = rng.multivariate_normal(mean=[0, 0],
    ...                             cov=real_cov,
    ...                             size=500)
    >>> oas = OAS().fit(X)
    >>> oas.covariance_
    array([[0.7533..., 0.2763...],
           [0.2763..., 0.3964...]])
    >>> oas.precision_
    array([[ 1.7833..., -1.2431... ],
           [-1.2431...,  3.3889...]])
    >>> oas.shrinkage_
    0.0195...
    Nc                 C   sb   |    | |}| jr,t|jd | _n|d| _t|| j dd\}}|| _	| 
| | S )a  Fit the Oracle Approximating Shrinkage covariance model to X.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Training data, where `n_samples` is the number of samples
            and `n_features` is the number of features.
        y : Ignored
            Not used, present for API consistency by convention.

        Returns
        -------
        self : object
            Returns the instance itself.
        r   r   Tr%   )r&   r'   r   r   r(   r   r)   r*   r[   rW   r+   rX   r   r   r   r/     s    

zOAS.fit)N)r0   r1   r2   r3   r/   r   r   r   r   r\   7  s   fr\   )r   )Fr7   )r3   r?   Znumbersr   r   Znumpyr    r   r   _configr   utilsr	   Zutils._param_validationr
   r   r   rO   rT   rU   r[   r\   r   r   r   r   <module>   s    
% 
_@ A