a
    �ù»j×   ã                
   @   sÔ  d Z ddlZddlZddlZddlZddlmZmZ ddlZ	ddl
mZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZ ddlmZmZmZ ddlmZmZm Z m!Z!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-m.Z. dd„ Z/dd„ Z0dddddde	 1e	j2¡j3dœdd„Z4dd„ Z5edgd gd gd!œdd"�dddddde	 1e	j2¡j3dd#œd$d%„ƒZ6G d&d'„ d'e,ƒZ7G d(d)„ d)e7ƒZ8ddddddde	 1e	j2¡j3fd*d+„Z9G d,d-„ d-e7ƒZ:dS ).zUGraphicalLasso: sparse inverse covariance estimation with an l1-penalized
estimator.
é    N)ÚIntegralÚReal)Úlinalgé   )Ú_fit_context)ÚConvergenceWarning)Ú_cd_fast)Úlars_path_gram)Úcheck_cvÚcross_val_score)ÚBunch)ÚIntervalÚ
StrOptionsÚvalidate_params)ÚMetadataRouterÚMethodMappingÚ_raise_for_paramsÚ_routing_enabledÚprocess_routing)ÚParallelÚdelayed)Ú_is_arraylike_not_scalarÚcheck_random_stateÚcheck_scalarÚvalidate_dataé   )ÚEmpiricalCovarianceÚempirical_covarianceÚlog_likelihoodc                 C   sZ   |j d }dt| |ƒ |t dtj ¡  }||t |¡ ¡ t t |¡¡ ¡   7 }|S )zùEvaluation of the graphical-lasso objective function

    the objective function is made of a shifted scaled version of the
    normalized log-likelihood (i.e. its empirical mean over the samples) and a
    penalisation term to promote sparsity
    r   ç       Àr   )Úshaper   ÚnpÚlogÚpiÚabsÚsumÚdiag)ZmleÚ
precision_ÚalphaÚpÚcost© r+   úEE:\soccer\ml_env\Lib\site-packages\sklearn/covariance/_graph_lasso.pyÚ
_objective-   s    
"*r-   c                 C   sJ   t  | | ¡}||jd 8 }||t  |¡ ¡ t  t  |¡¡ ¡   7 }|S )z§Expression of the dual gap convergence criterion

    The specific definition is given in Duchi "Projected Subgradient Methods
    for Learning Sparse Gaussians".
    r   )r!   r%   r    r$   r&   )Úemp_covr'   r(   Úgapr+   r+   r,   Ú	_dual_gap:   s    *r0   Úcdç-Cëâ6?éd   F)Úcov_initÚmodeÚtolÚenet_tolÚmax_iterÚverboseÚepsc                C   sê  | j \}	}
|dkrdt | ¡}dt| |ƒ }||
t dtj ¡ 7 }t | | ¡|
 }| |||fdfS |d u rv|  ¡ }n| ¡ }|d9 }| j	d d |
d … }||j	d d |
d …< t 
|¡}t |
¡}d}tƒ }|dkrâtddd	�}n
tdd
�}�z®tj}tj|dd …dd …f dd�}t|ƒD �]f}t|
ƒD �]Ê}|dk�r||d }|| ||k ||< |d d …|f ||k |d d …|f< n|dd …dd …f |d d …< | |||kf }tjf i |¤Ž�’ |dk�r|||k|f |||f d|    }t ||d|||||td ƒd¡
\}}	}	}	n(t|||j||
d  d|ddd�\}	}	}W d   ƒ n1 �sR0    Y  d|||f t |||k|f |¡  |||f< |||f  | |||k|f< |||f  | ||||kf< t ||¡}|||||kf< ||||k|f< �q*t | ¡ ¡�stdƒ‚t| ||ƒ}t| ||ƒ}|�r@td|||f ƒ | ||f¡ t |¡|k �rd �qšt |¡�s|dk�rtdƒ‚�qt d||f t ¡ W n< t�yØ } z"|j!d d f|_!|‚W Y d }~n
d }~0 0 ||||d fS )Nr   r   r   gffffffî?r   r1   ÚraiseÚignore)ZoverÚinvalid)r=   ÚC)Úorderiè  FTÚlars)ZXyZGramZ	n_samplesZ	alpha_minZ	copy_Gramr:   ÚmethodZreturn_pathg      ð?z1The system is too ill-conditioned for this solverz<[graphical_lasso] Iteration % 3i, cost % 3.2e, dual gap %.3ezANon SPD result: the system is too ill-conditioned for this solverzDgraphical_lasso: did not converge after %i iteration: dual gap: %.3ez3. The system is too ill-conditioned for this solver)"r    r   Úinvr   r!   r"   r#   r%   ÚcopyÚflatZpinvhZarangeÚlistÚdictÚinfÚrangeZerrstateÚcd_fastZenet_coordinate_descent_gramr   r	   ÚsizeÚdotÚisfiniteÚFloatingPointErrorr0   r-   ÚprintÚappendr$   ÚwarningsÚwarnr   Úargs)r.   r(   r4   r5   r6   r7   r8   r9   r:   Ú_Z
n_featuresr'   r*   Zd_gapÚcovariance_ZdiagonalÚindicesÚiZcostsÚerrorsZsub_covarianceÚidxZdiÚrowZcoefsÚer+   r+   r,   Ú_graphical_lassoG   sÄ    






&
ÿÿö
ø,
ÿÿÿÿÿÿÿýr[   c                 C   s4   t  | ¡}d|jdd|jd d …< t  t  |¡¡S )a³  Find the maximum alpha for which there are some non-zeros off-diagonal.

    Parameters
    ----------
    emp_cov : ndarray of shape (n_features, n_features)
        The sample covariance matrix.

    Notes
    -----
    This results from the bound for the all the Lasso that are solved
    in GraphicalLasso: each time, the row of cov corresponds to Xy. As the
    bound for alpha is given by `max(abs(Xy))`, the result follows.
    r   Nr   )r!   rC   rD   r    Úmaxr$   )r.   ÚAr+   r+   r,   Ú	alpha_maxÌ   s    
r^   ú
array-likeÚboolean)r.   Úreturn_costsÚreturn_n_iter©Zprefer_skip_nested_validation)r5   r6   r7   r8   r9   ra   r:   rb   c                C   sT   t ||d|||||dd�	 | ¡}
|
j|
jg}|r<| |
j¡ |	rL| |
j¡ t|ƒS )a<  L1-penalized covariance estimator.

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

    .. versionchanged:: v0.20
        graph_lasso has been renamed to graphical_lasso

    Parameters
    ----------
    emp_cov : array-like of shape (n_features, n_features)
        Empirical covariance from which to compute the covariance estimate.

    alpha : float
        The regularization parameter: the higher alpha, the more
        regularization, the sparser the inverse covariance.
        Range is (0, inf].

    mode : {'cd', 'lars'}, default='cd'
        The Lasso solver to use: coordinate descent or LARS. Use LARS for
        very sparse underlying graphs, where p > n. Elsewhere prefer cd
        which is more numerically stable.

    tol : float, default=1e-4
        The tolerance to declare convergence: if the dual gap goes below
        this value, iterations are stopped. Range is (0, inf].

    enet_tol : float, default=1e-4
        The tolerance for the elastic net solver used to calculate the descent
        direction. This parameter controls the accuracy of the search direction
        for a given column update, not of the overall parameter estimate. Only
        used for mode='cd'. Range is (0, inf].

    max_iter : int, default=100
        The maximum number of iterations.

    verbose : bool, default=False
        If verbose is True, the objective function and dual gap are
        printed at each iteration.

    return_costs : bool, default=False
        If return_costs is True, the objective function and dual gap
        at each iteration are returned.

    eps : float, default=eps
        The machine-precision regularization in the computation of the
        Cholesky diagonal factors. Increase this for very ill-conditioned
        systems. Default is `np.finfo(np.float64).eps`.

    return_n_iter : bool, default=False
        Whether or not to return the number of iterations.

    Returns
    -------
    covariance : ndarray of shape (n_features, n_features)
        The estimated covariance matrix.

    precision : ndarray of shape (n_features, n_features)
        The estimated (sparse) precision matrix.

    costs : list of (objective, dual_gap) pairs
        The list of values of the objective function and the dual gap at
        each iteration. Returned only if return_costs is True.

    n_iter : int
        Number of iterations. Returned only if `return_n_iter` is set to True.

    See Also
    --------
    GraphicalLasso : Sparse inverse covariance estimation
        with an l1-penalized estimator.
    GraphicalLassoCV : Sparse inverse covariance with
        cross-validated choice of the l1 penalty.

    Notes
    -----
    The algorithm employed to solve this problem is the GLasso algorithm,
    from the Friedman 2008 Biostatistics paper. It is the same algorithm
    as in the R `glasso` package.

    One possible difference with the `glasso` R package is that the
    diagonal coefficients are not penalized.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.datasets import make_sparse_spd_matrix
    >>> from sklearn.covariance import empirical_covariance, graphical_lasso
    >>> true_cov = make_sparse_spd_matrix(n_dim=3,random_state=42)
    >>> rng = np.random.RandomState(42)
    >>> X = rng.multivariate_normal(mean=np.zeros(3), cov=true_cov, size=3)
    >>> emp_cov = empirical_covariance(X, assume_centered=True)
    >>> emp_cov, _ = graphical_lasso(emp_cov, alpha=0.05)
    >>> emp_cov
    array([[ 1.68...,  0.21..., -0.20...],
           [ 0.21...,  0.22..., -0.08...],
           [-0.20..., -0.08...,  0.23...]])
    ÚprecomputedT)	r(   r5   Ú
covariancer6   r7   r8   r9   r:   Úassume_centered)ÚGraphicalLassoÚfitrT   r'   rO   Úcosts_Ún_iter_Útuple)r.   r(   r5   r6   r7   r8   r9   ra   r:   rb   ÚmodelÚoutputr+   r+   r,   Úgraphical_lassoß   s&    v÷
örn   c                       sª   e Zd ZU i ej¥eedddd�geedddd�geedddd�geddhƒgdgeeddd	d�gd
œ¥Ze	e
d< e d¡ ddddde ej¡jdf‡ fdd„	Z‡  ZS )ÚBaseGraphicalLassor   NÚright©ÚclosedÚleftr1   r@   r9   Úboth)r6   r7   r8   r5   r9   r:   Ú_parameter_constraintsZstore_precisionr2   r3   Fc                    s6   t ƒ j|d� || _|| _|| _|| _|| _|| _d S )N©rf   )ÚsuperÚ__init__r6   r7   r8   r5   r9   r:   )Úselfr6   r7   r8   r5   r9   r:   rf   ©Ú	__class__r+   r,   rx   u  s    
zBaseGraphicalLasso.__init__)Ú__name__Ú
__module__Ú__qualname__r   ru   r   r   r   r   rF   Ú__annotations__Úpopr!   ÚfinfoÚfloat64r:   rx   Ú__classcell__r+   r+   rz   r,   ro   i  s&   
ÿù	
øro   c                
       sŠ   e Zd ZU dZi ej¥eedddd�gedhƒdgdœ¥Ze	e
d< dd
ddddde ej¡jddœ‡ fdd„Zedd�ddd„ƒZ‡  ZS )rg   ag  Sparse inverse covariance estimation with an l1-penalized estimator.

    For a usage example see
    :ref:`sphx_glr_auto_examples_applications_plot_stock_market.py`.

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

    .. versionchanged:: v0.20
        GraphLasso has been renamed to GraphicalLasso

    Parameters
    ----------
    alpha : float, default=0.01
        The regularization parameter: the higher alpha, the more
        regularization, the sparser the inverse covariance.
        Range is (0, inf].

    mode : {'cd', 'lars'}, default='cd'
        The Lasso solver to use: coordinate descent or LARS. Use LARS for
        very sparse underlying graphs, where p > n. Elsewhere prefer cd
        which is more numerically stable.

    covariance : "precomputed", default=None
        If covariance is "precomputed", the input data in `fit` is assumed
        to be the covariance matrix. If `None`, the empirical covariance
        is estimated from the data `X`.

        .. versionadded:: 1.3

    tol : float, default=1e-4
        The tolerance to declare convergence: if the dual gap goes below
        this value, iterations are stopped. Range is (0, inf].

    enet_tol : float, default=1e-4
        The tolerance for the elastic net solver used to calculate the descent
        direction. This parameter controls the accuracy of the search direction
        for a given column update, not of the overall parameter estimate. Only
        used for mode='cd'. Range is (0, inf].

    max_iter : int, default=100
        The maximum number of iterations.

    verbose : bool, default=False
        If verbose is True, the objective function and dual gap are
        plotted at each iteration.

    eps : float, default=eps
        The machine-precision regularization in the computation of the
        Cholesky diagonal factors. Increase this for very ill-conditioned
        systems. Default is `np.finfo(np.float64).eps`.

        .. versionadded:: 1.3

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

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

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

    precision_ : ndarray of shape (n_features, n_features)
        Estimated pseudo inverse matrix.

    n_iter_ : int
        Number of iterations run.

    costs_ : list of (objective, dual_gap) pairs
        The list of values of the objective function and the dual gap at
        each iteration. Returned only if return_costs is True.

        .. versionadded:: 1.3

    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
    --------
    graphical_lasso : L1-penalized covariance estimator.
    GraphicalLassoCV : Sparse inverse covariance with
        cross-validated choice of the l1 penalty.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.covariance import GraphicalLasso
    >>> true_cov = np.array([[0.8, 0.0, 0.2, 0.0],
    ...                      [0.0, 0.4, 0.0, 0.0],
    ...                      [0.2, 0.0, 0.3, 0.1],
    ...                      [0.0, 0.0, 0.1, 0.7]])
    >>> np.random.seed(0)
    >>> X = np.random.multivariate_normal(mean=[0, 0, 0, 0],
    ...                                   cov=true_cov,
    ...                                   size=200)
    >>> cov = GraphicalLasso().fit(X)
    >>> np.around(cov.covariance_, decimals=3)
    array([[0.816, 0.049, 0.218, 0.019],
           [0.049, 0.364, 0.017, 0.034],
           [0.218, 0.017, 0.322, 0.093],
           [0.019, 0.034, 0.093, 0.69 ]])
    >>> np.around(cov.location_, decimals=3)
    array([0.073, 0.04 , 0.038, 0.143])
    r   Nrt   rq   rd   )r(   re   ru   ç{®Gáz„?r1   r2   r3   F)r5   re   r6   r7   r8   r9   r:   rf   c          
   	      s*   t ƒ j|||||||	d� || _|| _d S ©N)r6   r7   r8   r5   r9   r:   rf   )rw   rx   r(   re   )
ry   r(   r5   re   r6   r7   r8   r9   r:   rf   rz   r+   r,   rx     s    ù	zGraphicalLasso.__init__Trc   c                 C   s¦   t | |ddd�}| jdkr6| ¡ }t |jd ¡| _n4t|| jd�}| jr^t |jd ¡| _n| 	d¡| _t
|| jd| j| j| j| j| j| jd�	\| _| _| _| _| S )	a€  Fit the GraphicalLasso model to X.

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

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

        Returns
        -------
        self : object
            Returns the instance itself.
        r   )Úensure_min_featuresZensure_min_samplesrd   r   rv   r   N©r(   r4   r5   r6   r7   r8   r9   r:   )r   re   rC   r!   Úzerosr    Ú	location_r   rf   Úmeanr[   r(   r5   r6   r7   r8   r9   r:   rT   r'   ri   rj   )ry   ÚXÚyr.   r+   r+   r,   rh     s(    
÷zGraphicalLasso.fit)r„   )N)r|   r}   r~   Ú__doc__ro   ru   r   r   r   rF   r   r!   r�   r‚   r:   rx   r   rh   rƒ   r+   r+   rz   r,   rg   ˆ  s(   
vÿý þõrg   c
                 C   s`  t d|d ƒ}
t| ƒ}|du r(| ¡ }n|}tƒ }tƒ }tƒ }|durNt|ƒ}|D ]ð}zLt||||||||
|	d�	\}}}}| |¡ | |¡ |dur t||ƒ}W n2 tyÔ   tj	 }| tj
¡ | tj
¡ Y n0 |durút |¡sðtj	 }| |¡ |dk�rtj d¡ qR|dkrR|du�r6td||f ƒ qRtd| ƒ qR|du�rX|||fS ||fS )aŠ	  l1-penalized covariance estimator along a path of decreasing alphas

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

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

    alphas : array-like of shape (n_alphas,)
        The list of regularization parameters, decreasing order.

    cov_init : array of shape (n_features, n_features), default=None
        The initial guess for the covariance.

    X_test : array of shape (n_test_samples, n_features), default=None
        Optional test matrix to measure generalisation error.

    mode : {'cd', 'lars'}, default='cd'
        The Lasso solver to use: coordinate descent or LARS. Use LARS for
        very sparse underlying graphs, where p > n. Elsewhere prefer cd
        which is more numerically stable.

    tol : float, default=1e-4
        The tolerance to declare convergence: if the dual gap goes below
        this value, iterations are stopped. The tolerance must be a positive
        number.

    enet_tol : float, default=1e-4
        The tolerance for the elastic net solver used to calculate the descent
        direction. This parameter controls the accuracy of the search direction
        for a given column update, not of the overall parameter estimate. Only
        used for mode='cd'. The tolerance must be a positive number.

    max_iter : int, default=100
        The maximum number of iterations. This parameter should be a strictly
        positive integer.

    verbose : int or bool, default=False
        The higher the verbosity flag, the more information is printed
        during the fitting.

    eps : float, default=eps
        The machine-precision regularization in the computation of the
        Cholesky diagonal factors. Increase this for very ill-conditioned
        systems. Default is `np.finfo(np.float64).eps`.

        .. versionadded:: 1.3

    Returns
    -------
    covariances_ : list of shape (n_alphas,) of ndarray of shape             (n_features, n_features)
        The estimated covariance matrices.

    precisions_ : list of shape (n_alphas,) of ndarray of shape             (n_features, n_features)
        The estimated (sparse) precision matrices.

    scores_ : list of shape (n_alphas,), dtype=float
        The generalisation error (log-likelihood) on the test data.
        Returned only if test data is passed.
    r   r   Nr‡   Ú.z/[graphical_lasso_path] alpha: %.2e, score: %.2ez"[graphical_lasso_path] alpha: %.2e)r\   r   rC   rE   r[   rO   r   rM   r!   rG   ÚnanrL   ÚsysÚstderrÚwriterN   )r‹   Úalphasr4   ÚX_testr5   r6   r7   r8   r9   r:   Úinner_verboser.   rT   Zcovariances_Zprecisions_Zscores_Ztest_emp_covr(   r'   rS   Ú
this_scorer+   r+   r,   Úgraphical_lasso_pathK  s`    K
÷





ÿÿ

r—   c                       s¦   e Zd ZU dZi ej¥eedddd�dgeedddd�gdgedgd	œ¥Zee	d
< ddddddddde
 e
j¡jddœ‡ fdd„
Zedd�ddd„ƒZdd„ Z‡  ZS )ÚGraphicalLassoCVa?  Sparse inverse covariance w/ cross-validated choice of the l1 penalty.

    See glossary entry for :term:`cross-validation estimator`.

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

    .. versionchanged:: v0.20
        GraphLassoCV has been renamed to GraphicalLassoCV

    Parameters
    ----------
    alphas : int or array-like of shape (n_alphas,), dtype=float, default=4
        If an integer is given, it fixes the number of points on the
        grids of alpha to be used. If a list is given, it gives the
        grid to be used. See the notes in the class docstring for
        more details. Range is [1, inf) for an integer.
        Range is (0, inf] for an array-like of floats.

    n_refinements : int, default=4
        The number of times the grid is refined. Not used if explicit
        values of alphas are passed. Range is [1, inf).

    cv : int, cross-validation generator or iterable, default=None
        Determines the cross-validation splitting strategy.
        Possible inputs for cv are:

        - None, to use the default 5-fold cross-validation,
        - integer, to specify the number of folds.
        - :term:`CV splitter`,
        - An iterable yielding (train, test) splits as arrays of indices.

        For integer/None inputs :class:`~sklearn.model_selection.KFold` is used.

        Refer :ref:`User Guide <cross_validation>` for the various
        cross-validation strategies that can be used here.

        .. versionchanged:: 0.20
            ``cv`` default value if None changed from 3-fold to 5-fold.

    tol : float, default=1e-4
        The tolerance to declare convergence: if the dual gap goes below
        this value, iterations are stopped. Range is (0, inf].

    enet_tol : float, default=1e-4
        The tolerance for the elastic net solver used to calculate the descent
        direction. This parameter controls the accuracy of the search direction
        for a given column update, not of the overall parameter estimate. Only
        used for mode='cd'. Range is (0, inf].

    max_iter : int, default=100
        Maximum number of iterations.

    mode : {'cd', 'lars'}, default='cd'
        The Lasso solver to use: coordinate descent or LARS. Use LARS for
        very sparse underlying graphs, where number of features is greater
        than number of samples. Elsewhere prefer cd which is more numerically
        stable.

    n_jobs : int, default=None
        Number of jobs to run in parallel.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

        .. versionchanged:: v0.20
           `n_jobs` default changed from 1 to None

    verbose : bool, default=False
        If verbose is True, the objective function and duality gap are
        printed at each iteration.

    eps : float, default=eps
        The machine-precision regularization in the computation of the
        Cholesky diagonal factors. Increase this for very ill-conditioned
        systems. Default is `np.finfo(np.float64).eps`.

        .. versionadded:: 1.3

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

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

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

    precision_ : ndarray of shape (n_features, n_features)
        Estimated precision matrix (inverse covariance).

    costs_ : list of (objective, dual_gap) pairs
        The list of values of the objective function and the dual gap at
        each iteration. Returned only if return_costs is True.

        .. versionadded:: 1.3

    alpha_ : float
        Penalization parameter selected.

    cv_results_ : dict of ndarrays
        A dict with keys:

        alphas : ndarray of shape (n_alphas,)
            All penalization parameters explored.

        split(k)_test_score : ndarray of shape (n_alphas,)
            Log-likelihood score on left-out data across (k)th fold.

            .. versionadded:: 1.0

        mean_test_score : ndarray of shape (n_alphas,)
            Mean of scores over the folds.

            .. versionadded:: 1.0

        std_test_score : ndarray of shape (n_alphas,)
            Standard deviation of scores over the folds.

            .. versionadded:: 1.0

    n_iter_ : int
        Number of iterations run for the optimal alpha.

    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
    --------
    graphical_lasso : L1-penalized covariance estimator.
    GraphicalLasso : Sparse inverse covariance estimation
        with an l1-penalized estimator.

    Notes
    -----
    The search for the optimal penalization parameter (`alpha`) is done on an
    iteratively refined grid: first the cross-validated scores on a grid are
    computed, then a new refined grid is centered around the maximum, and so
    on.

    One of the challenges which is faced here is that the solvers can
    fail to converge to a well-conditioned estimate. The corresponding
    values of `alpha` then come out as missing values, but the optimum may
    be close to these missing values.

    In `fit`, once the best parameter `alpha` is found through
    cross-validation, the model is fit again using the entire training set.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.covariance import GraphicalLassoCV
    >>> true_cov = np.array([[0.8, 0.0, 0.2, 0.0],
    ...                      [0.0, 0.4, 0.0, 0.0],
    ...                      [0.2, 0.0, 0.3, 0.1],
    ...                      [0.0, 0.0, 0.1, 0.7]])
    >>> np.random.seed(0)
    >>> X = np.random.multivariate_normal(mean=[0, 0, 0, 0],
    ...                                   cov=true_cov,
    ...                                   size=200)
    >>> cov = GraphicalLassoCV().fit(X)
    >>> np.around(cov.covariance_, decimals=3)
    array([[0.816, 0.051, 0.22 , 0.017],
           [0.051, 0.364, 0.018, 0.036],
           [0.22 , 0.018, 0.322, 0.094],
           [0.017, 0.036, 0.094, 0.69 ]])
    >>> np.around(cov.location_, decimals=3)
    array([0.073, 0.04 , 0.038, 0.143])
    r   Nrs   rq   r_   r   Z	cv_object)r“   Ún_refinementsÚcvÚn_jobsru   é   r2   r3   r1   F)r“   r™   rš   r6   r7   r8   r5   r›   r9   r:   rf   c             	      s6   t ƒ j|||||	|
|d� || _|| _|| _|| _d S r…   )rw   rx   r“   r™   rš   r›   )ry   r“   r™   rš   r6   r7   r8   r5   r›   r9   r:   rf   rz   r+   r,   rx   Š  s    ù	zGraphicalLassoCV.__init__Trc   c              
      sn  t |ˆdƒ tˆˆ dd�‰ ˆjr4t ˆ jd ¡ˆ_nˆ  d¡ˆ_tˆ ˆjd�}t	ˆj
|dd�}tƒ }ˆj}tdˆjd ƒ‰t|ƒr°ˆjD ]}t|d	tdtjd
d� qˆˆj‰d}	n:ˆj}	t|ƒ}
d|
 }t t |¡t |
¡|¡ddd… ‰tƒ �rtˆdfi |¤Ž}ntti d�d�}t ¡ }t|	ƒD �]>}t ¡ �X t dt¡ t ˆj!ˆjd�‡ ‡‡‡fdd„|j"ˆ |fi |j#j"¤ŽD ƒƒ}W d  ƒ n1 �s”0    Y  t$|Ž \}}}t$|Ž }t$|Ž }| %t$ˆ||ƒ¡ t&|t' (d¡dd�}tj }d}t)|ƒD ]Z\}\}}}t |¡}|dt *tj+¡j, k�r,tj-}t .|¡�r<|}||k�rö|}|}�qö|dk�rv|d d }
|d d }nŠ||k�r°|t/|ƒd k�s°|| d }
||d  d }nP|t/|ƒd k�rà|| d }
d|| d  }n ||d  d }
||d  d }t|ƒ�s4t t |
¡t |¡|d ¡‰ˆdd… ‰ˆj�r&|	dk�r&t0d|d |	t ¡ | f ƒ �q&tt$|Ž ƒ}t|d ƒ}t|d ƒ‰ˆ 1d¡ | 1t2t3ƒ ˆ |ˆj!ˆ|d�¡ t 4|¡}dt 4ˆ¡iˆ_5t|jd ƒD ]$}|dd…|f ˆj5d|› d�< �qÜtj|dd�ˆj5d< tj6|dd�ˆj5d< ˆ| }|ˆ_7t8||ˆj9ˆj:ˆj;ˆj<ˆˆj,d �\ˆ_=ˆ_>ˆ_?ˆ_@ˆS )!aX  Fit the GraphicalLasso covariance model to X.

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

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

        **params : dict, default=None
            Parameters to be passed to the CV splitter and the
            cross_val_score function.

            .. versionadded:: 1.5
                Only available if `enable_metadata_routing=True`,
                which can be set by using
                ``sklearn.set_config(enable_metadata_routing=True)``.
                See :ref:`Metadata Routing User Guide <metadata_routing>` for
                more details.

        Returns
        -------
        self : object
            Returns the instance itself.
        rh   r   )r†   r   r   rv   F)Ú
classifierr(   rp   )Zmin_valZmax_valZinclude_boundariesr„   Néÿÿÿÿ)Úsplit)Úsplitterr<   )r›   r9   c                 3   sJ   | ]B\}}t tƒˆ | ˆˆ | ˆjˆjˆjtd ˆj ƒˆˆjd�	V  qdS )çš™™™™™¹?)r“   r”   r5   r6   r7   r8   r9   r:   N)r   r—   r5   r6   r7   Úintr8   r:   )Ú.0ÚtrainÚtest©r‹   r“   r•   ry   r+   r,   Ú	<genexpr>÷  s   õ÷z'GraphicalLassoCV.fit.<locals>.<genexpr>T)ÚkeyÚreverser¡   z8[GraphicalLassoCV] Done refinement % 2i out of %i: % 3is)rš   r›   r9   Úparamsr“   rŸ   Z_test_score)ZaxisZmean_test_scoreZstd_test_score)r(   r5   r6   r7   r8   r9   r:   )Ar   r   rf   r!   rˆ   r    r‰   rŠ   r   r
   rš   rE   r“   r\   r9   r   r   r   rG   r™   r^   ZlogspaceÚlog10r   r   r   ÚtimerH   rP   Úcatch_warningsÚsimplefilterr   r   r›   rŸ   r    ÚzipÚextendÚsortedÚoperatorÚ
itemgetterÚ	enumerater�   r‚   r:   r�   rL   ÚlenrN   rO   r   r   ÚarrayZcv_results_ZstdZalpha_r[   r5   r6   r7   r8   rT   r'   ri   rj   )ry   r‹   rŒ   rª   r.   rš   ÚpathZn_alphasr(   r™   Zalpha_1Zalpha_0Zrouted_paramsÚt0rV   Z	this_pathZcovsrS   ZscoresZ
best_scoreZlast_finite_idxÚindexr–   Z
best_indexZgrid_scoresZ
best_alphar+   r¦   r,   rh   §  sÒ    
ú$
ô(



ÿÿ
úÿ

"ø
zGraphicalLassoCV.fitc                 C   s.   t | jjd�jt| jƒtƒ jddd�d�}|S )aj  Get metadata routing of this object.

        Please check :ref:`User Guide <metadata_routing>` on how the routing
        mechanism works.

        .. versionadded:: 1.5

        Returns
        -------
        routing : MetadataRouter
            A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
            routing information.
        )ÚownerrŸ   rh   )ZcalleeZcaller)r    Zmethod_mapping)r   r{   r|   Úaddr
   rš   r   )ry   Zrouterr+   r+   r,   Úget_metadata_routingb  s
    þz%GraphicalLassoCV.get_metadata_routing)N)r|   r}   r~   r�   ro   ru   r   r   rF   r   r!   r�   r‚   r:   rx   r   rh   r¼   rƒ   r+   r+   rz   r,   r˜   Ë  s4   
 7ÿûó ;r˜   );r�   r²   r�   r¬   rP   Únumbersr   r   Únumpyr!   Zscipyr   Úbaser   Ú
exceptionsr   Zlinear_modelr   rI   r	   Zmodel_selectionr
   r   Úutilsr   Zutils._param_validationr   r   r   Zutils.metadata_routingr   r   r   r   r   Zutils.parallelr   r   Zutils.validationr   r   r   r   Ú r   r   r   r-   r0   r�   r‚   r:   r[   r^   rn   ro   rg   r—   r˜   r+   r+   r+   r,   Ú<module>   sz   ö ýúõ  Gö
 