
\c           @   sO  d  Z  d d l Z d d l Z d d l Z d d l Z d d l Z d d l Z d d l Z d d l	 Z d d l m
 Z
 d d l m Z y$ d d l m Z d d l m Z Wn1 e k
 r d d l m Z d d l m Z n Xd d l Z d d l Z d d l j Z d d l Z d d l Z y e Wn e k
 r>d Z n Xd 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# d d l$ Z% d d l& Z& d d l' m( Z( m) Z) m* Z* m+ Z+ m, Z, d d l- m. Z. m/ Z/ m0 Z0 d d l1 m2 Z2 d d l3 m4 Z4 d d l5 m6 Z6 g  Z7 y9 d d l8 m9 Z: d Z; e. e;  e:  Z9 e7 j< d  Wn e k
 r}n Xy9 d d l8 m= Z> d Z; e. e;  e>  Z= e7 j< d  Wn e k
 rn Xd d d d d d d d d  d! d" d# d$ d% d& d' d( g Z? e? j@ e7  e4 d)  ZA eA jB ZC eA jD ZE eA jF ZG eA jH ZI eA jJ ZK e jL jM ZM eA jN ZO eA jP ZQ eA jR ZS eA jT ZU eA jV ZW eA jX ZY eA jZ Z[ eA j\ Z] e] Z^ d*   Z_ d+   Z` d,   Za d-   Zb d ec d.  Zd d/ ee f d0     YZf d1   Zg d2 d3 d4 d5  Zh e. d6  d d7   Zi e. d6  d8 ee f d9     Y Zj d:   Zk d;   Zl d< d= d> d? d@ dA dB dC dD dE dF g Zm dG dH dI dJ dK dL g Zn dM dN dO dP dQ dR dS dT dU dV dW dX dY dZ d[ d\ d] d^ d_ d` da db dc dd de df dg dh di g Zo ep ep d ep dj  Zq dk dl  Zr dm   Zs y d d lt Zt et ju jv e0 dn do Zw et ju jv e jx jy dp  dq k dn dr Zz et ju j{ e/ d e| dn ds Z} et ju jv e2 j~ j dn dt Z et ju jv e j du k dn dv Z Wn e k
 rn Xdw   Z dx   Z ep dy  Z dz ee f d{     YZ d| ep d}  Z ep d~  Z d d  Z d d d d  Z d S(   s   Testing utilities.iN(   t   wraps(   t
   itemgetter(   t   urlopen(   t	   HTTPError(   t   assert_allclose(   t   assert_almost_equal(   t   assert_approx_equal(   t   assert_array_equal(   t   assert_array_almost_equal(   t   assert_array_less(   t   BaseEstimatort   ClassifierMixint   ClusterMixint   RegressorMixint   TransformerMixin(   t
   deprecatedt   IS_PYPYt	   _IS_32BIT(   t   joblib(   t   TestCase(   t	   signature(   t   raisess   sklearn.utils.testing.raises has been deprecated in version 0.20 and will be removed in 0.22. Please use sklearn.utils.testing.assert_raises instead.R   (   t
   with_setups   sklearn.utils.testing.with_setup has been deprecated in version 0.20 and will be removed in 0.22.If your code relies on with_setup, please use nose.tools.with_setup instead.R   t   assert_equalt   assert_not_equalt   assert_raisest   assert_raises_regexpt   assert_truet   assert_falseR   R   R   R	   t   assert_lesst   assert_less_equalt   assert_greatert   assert_greater_equalR   R   t   SkipTestt   __init__c      	      s   t    t j d t   } t j d  | | |   } t t d  ru g  | D] } | j t j k	 rN | ^ qN } n  t	 |  d k s t
 d | j   n  t   f d   | D  } | s t
 d | j   | f   n  Wd QX| S(	   s  Test that a certain warning occurs.

    Parameters
    ----------
    warning_class : the warning class
        The class to test for, e.g. UserWarning.

    func : callable
        Callable object to trigger warnings.

    *args : the positional arguments to `func`.

    **kw : the keyword arguments to `func`

    Returns
    -------

    result : the return value of `func`

    t   recordt   alwayst   VisibleDeprecationWarningi    s!   No warning raised when calling %sc         3   s   |  ] } | j    k Vq d  S(   N(   t   category(   t   .0t   warning(   t   warning_class(    s4   lib/python2.7/site-packages/sklearn/utils/testing.pys	   <genexpr>   s    s#   %s did not give warning: %s( is %s)N(   t   clean_warning_registryt   warningst   catch_warningst   Truet   simplefiltert   hasattrt   npR&   R%   t   lent   AssertionErrort   __name__t   any(   R)   t   funct   argst   kwt   wt   resultt   et   found(    (   R)   s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   assert_warnst   s    !c      	      s  t    t j d t  } t j d  t t d  rN t j d t j  n  | | |   } t |  d k s t	 d | j
   n  g  | D] } t | j |   ^ q } t |  s t	 d | j
 |  f   n  t }	 x g  t |  D] \ }
 } | r |
 ^ q D]u } | | j } t t | d  r6| j d n |  } t    rT  } n   f d	   } | |  rt }	 PqqW|	 st	 d
   | j
 | f   n  Wd QX| S(   s{  Test that a certain warning occurs and with a certain message.

    Parameters
    ----------
    warning_class : the warning class
        The class to test for, e.g. UserWarning.

    message : str | callable
        The message or a substring of the message to test for. If callable,
        it takes a string as the argument and will trigger an AssertionError
        if the callable returns `False`.

    func : callable
        Callable object to trigger warnings.

    *args : the positional arguments to `func`.

    **kw : the keyword arguments to `func`.

    Returns
    -------
    result : the return value of `func`

    R#   R$   R%   t   ignorei    s!   No warning raised when calling %ss&   No warning raised for %s with class %sR6   c            s
     |  k S(   N(    (   t   msg(   t   message(    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   <lambda>   s    sC   Did not receive the message you expected ('%s') for <%s>, got: '%s'N(   R*   R+   R,   R-   R.   R/   R0   R%   R1   R2   R3   t
   issubclassR&   R4   t   Falset	   enumerateR?   t   strR6   t   callable(   R)   R?   R5   R6   R7   R8   R9   R(   R;   t   message_foundt   it   xt   indexR>   t   check_in_message(    (   R?   s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   assert_warns_message   s6    %2(	c      
   O   sz   t  j d d d d  \ y# t t t  j d t  j d   Wn t k
 rY |  | |   SXt t d |  | |  SWd QXd S(   s   Assume that numpy's warning for divide by zero is raised

    Handles the case of platforms that do not support warning on divide by zero

    Parameters
    ----------
    func
    *args
    **kw
    t   dividet   warnt   invalidi   s   invalid value encounteredN(   R0   t   errstateR<   t   RuntimeWarningRL   t   zerosR2   RK   (   R5   R6   R7   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   assert_warns_div0   s    #c      
   O   s   t    t j d t   } t j d  |  | |   } t t d  ru g  | D] } | j t j k	 rN | ^ qN } n  t	 |  d k r t
 d |  j d j d   | D  f   n  Wd QX| S(	   s?   
    Parameters
    ----------
    func
    *args
    **kw
    R#   R$   R%   i    s"   Got warnings when calling %s: [%s]s   , c         s   s   |  ] } t  |  Vq d  S(   N(   RD   (   R'   R(   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pys	   <genexpr>  s    N(   R*   R+   R,   R-   R.   R/   R0   R&   R%   R1   R2   R3   t   join(   R5   R6   R7   R8   R9   R:   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   assert_no_warnings   s    	!)c         C   sr   t  |  t  rB t |  t  rB |  j } t d j d |    n, t |   ra t d |  |   St d |  Sd S(   s  Context manager and decorator to ignore warnings.

    Note: Using this (in both variants) will clear all warnings
    from all python modules loaded. In case you need to test
    cross-module-warning-logging, this is not your tool of choice.

    Parameters
    ----------
    obj : callable or None
        callable where you want to ignore the warnings.
    category : warning class, defaults to Warning.
        The category to filter. If Warning, all categories will be muted.

    Examples
    --------
    >>> with ignore_warnings():
    ...     warnings.warn('buhuhuhu')

    >>> def nasty_warn():
    ...    warnings.warn('buhuhuhu')
    ...    print(42)

    >>> ignore_warnings(nasty_warn)()
    42
    s   'obj' should be a callable where you want to ignore warnings. You passed a warning class instead: 'obj={warning_name}'. If you want to pass a warning class to ignore_warnings, you should use 'category={warning_name}'t   warning_nameR&   N(	   t
   isinstancet   typeRA   t   WarningR3   t
   ValueErrort   formatRE   t   _IgnoreWarnings(   t   objR&   RU   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   ignore_warnings  s    		R[   c           B   s;   e  Z d  Z d   Z d   Z d   Z d   Z d   Z RS(   sw  Improved and simplified Python warnings context manager and decorator.

    This class allows the user to ignore the warnings raised by a function.
    Copied from Python 2.7.5 and modified as required.

    Parameters
    ----------
    category : tuple of warning class, default to Warning
        The category to filter. By default, all the categories will be muted.

    c         C   s8   t  |  _ t j d |  _ t |  _ g  |  _ | |  _ d  S(   NR+   (	   R-   t   _recordt   syst   modulest   _moduleRB   t   _enteredt   logR&   (   t   selfR&   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyR"   N  s
    			c            s"   t        f d    } | S(   s<   Decorator to catch and hide warnings without visual nesting.c             s>   t    t j   % t j d  j    |  |   SWd  QXd  S(   NR=   (   R*   R+   R,   R.   R&   (   R6   t   kwargs(   t   fnRd   (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   wrapperW  s    (   R    (   Rd   Rf   Rg   (    (   Rf   Rd   s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   __call__U  s    c         C   sr   g  } |  j  r | j d  n  |  j t j d k	 rL | j d |  j  n  t |   j } d | d j |  f S(   Ns   record=TrueR+   s	   module=%rs   %s(%s)s   , (   R^   t   appendRa   R_   R`   RW   R3   RS   (   Rd   R6   t   name(    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   __repr__`  s    	c         C   sq   |  j  r t d |    n  t |  _  |  j j |  _ |  j |  j _ |  j j |  _ t   t	 j
 d |  j  d  S(   Ns   Cannot enter %r twiceR=   (   Rb   t   RuntimeErrorR-   Ra   t   filterst   _filterst   showwarningt   _showwarningR*   R+   R.   R&   (   Rd   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt	   __enter__i  s    		c         G   sO   |  j  s t d |    n  |  j |  j _ |  j |  j _ g  |  j (t   d  S(   Ns%   Cannot exit %r without entering first(	   Rb   Rl   Rn   Ra   Rm   Rp   Ro   Rc   R*   (   Rd   t   exc_info(    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   __exit__s  s    	
(   R3   t
   __module__t   __doc__R"   Rh   Rk   Rq   Rs   (    (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyR[   A  s   					
c         O   s   y | | |   WnD |  k
 rW } t  |  } | | k r t d | | f   q nN Xt |  t  r d j d   |  D  } n	 |  j } t d | | j f   d S(   s  Helper function to test the message raised in an exception.

    Given an exception, a callable to raise the exception, and
    a message string, tests that the correct exception is raised and
    that the message is a substring of the error thrown. Used to test
    that the specific message thrown during an exception is correct.

    Parameters
    ----------
    exceptions : exception or tuple of exception
        An Exception object.

    message : str
        The error message or a substring of the error message.

    function : callable
        Callable object to raise error.

    *args : the positional arguments to `function`.

    **kwargs : the keyword arguments to `function`.
    sR   Error message does not include the expected string: %r. Observed error message: %rs    or c         s   s   |  ] } | j  Vq d  S(   N(   R3   (   R'   R:   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pys	   <genexpr>  s    s   %s not raised by %sN(   RD   R2   RV   t   tupleRS   R3   (   t
   exceptionsR?   t   functionR6   Re   R:   t   error_messaget   names(    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   assert_raise_message|  s    	gHz>g&.>t    c      	   C   s  t  j j |   r t  j j |  r |  j   }  | j   } |  j   | j   t |  j | j d | t |  j | j d | t |  j	 | j	 d | d | d | nT t  j j |   r t  j j |  r t |  | d | d | d | n t
 d   d S(   s}  Assert allclose for sparse and dense data.

    Both x and y need to be either sparse or dense, they
    can't be mixed.

    Parameters
    ----------
    x : array-like or sparse matrix
        First array to compare.

    y : array-like or sparse matrix
        Second array to compare.

    rtol : float, optional
        relative tolerance; see numpy.allclose

    atol : float, optional
        absolute tolerance; see numpy.allclose. Note that the default here is
        more tolerant than the default for numpy.testing.assert_allclose, where
        atol=0.

    err_msg : string, default=''
        Error message to raise.
    t   err_msgt   rtolt   atolsG   Can only compare two sparse matrices, not a sparse matrix and an array.N(   t   spt   sparset   issparset   tocsrt   sum_duplicatesR   t   indicest   indptrR   t   dataRY   (   RH   t   yR~   R   R}   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   assert_allclose_dense_sparse  s    $

(&"s8   deprecated in version 0.20 to be removed in version 0.22c         C   s   t  |   } x | D] } | | j | | <q W| d k rU t t | j     } n  t j d t |  f d d | d <x. t	 |  D]  \ } } | | d d | f <q Wt
 j j | | d d d S(	   s  Create a fake mldata data set.

    .. deprecated:: 0.20
        Will be removed in version 0.22

    Parameters
    ----------
    columns_dict : dict, keys=str, values=ndarray
        Contains data as columns_dict[column_name] = array of data.

    dataname : string
        Name of data set.

    matfile : string or file object
        The file name string or the file-like object of the output file.

    ordering : list, default None
        List of column_names, determines the ordering in the data set.

    Notes
    -----
    This function transposes all arrays, while fetch_mldata only transposes
    'data', keep that into account in the tests.
    i   t   dtypet   objectt   mldata_descr_orderingi    t   oned_ast   columnN(   t   dictt   Tt   Nonet   sortedt   listt   keysR   t   emptyR1   RC   t   scipyt   iot   savemat(   t   columns_dictt   datanamet   matfilet   orderingt   datasetsRj   RG   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   fake_mldata  s    t   mock_mldata_urlopenc           B   s    e  Z d  Z d   Z d   Z RS(   s  Object that mocks the urlopen function to fake requests to mldata.

    When requesting a dataset with a name that is in mock_datasets, this object
    creates a fake dataset in a StringIO object and returns it. Otherwise, it
    raises an HTTPError.

    .. deprecated:: 0.20
        Will be removed in version 0.22

    Parameters
    ----------
    mock_datasets : dict
        A dictionary of {dataset_name: data_dict}, or
        {dataset_name: (data_dict, ordering). `data_dict` itself is a
        dictionary of {column_name: data_array}, and `ordering` is a list of
        column_names to determine the ordering in the data set (see
        :func:`fake_mldata` for details).
    c         C   s   | |  _  d  S(   N(   t   mock_datasets(   Rd   R   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyR"     s    c         C   s   | j  d  d } | |  j k r d | } d d l m } |   } |  j | } d } t | t  rv | \ } } n  t | | | |  | j d  | St	 | d | d g  d   d S(	   s\   
        Parameters
        ----------
        urlname : string
            The url
        t   /it   _(   t   BytesIOi    i  s    is not availableN(
   t   splitR   R   R   R   RV   Rv   R   t   seekR   (   Rd   t   urlnamet   dataset_namet   resource_nameR   R   t   datasetR   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyRh     s    
	(   R3   Rt   Ru   R"   Rh   (    (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyR     s   	c         C   s&   d d l  m } t |   | j _ d S(   ss  
    Parameters
    ----------
    mock_datasets : dict
        A dictionary of {dataset_name: data_dict}, or
        {dataset_name: (data_dict, ordering). `data_dict` itself is a
        dictionary of {column_name: data_array}, and `ordering` is a list of
        column_names to determine the ordering in the data set (see
        :func:`fake_mldata` for details).
    i(   R   N(   t   sklearnR   R   t   mldataR   (   R   R   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   install_mldata_mock,  s    c          C   s    d d l  m }  t |  j _ d  S(   Ni(   R   (   R   R   R   R   (   R   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   uninstall_mldata_mock<  s    t   OneVsOneClassifiert   MultiOutputEstimatort   MultiOutputRegressort   MultiOutputClassifiert   OutputCodeClassifiert   OneVsRestClassifiert   RFEt   RFECVt   BaseEnsemblet   ClassifierChaint   RegressorChaint   Pipelinet   FeatureUniont   GridSearchCVt   RandomizedSearchCVt   SelectFromModelt   ColumnTransformert   SparseCodert   DictVectorizert   LabelBinarizert   LabelEncodert   MultiLabelBinarizert   TfidfTransformert   TfidfVectorizert   IsotonicRegressiont   OneHotEncodert   RandomTreesEmbeddingt   OrdinalEncodert   FeatureHashert   DummyClassifiert   DummyRegressort   TruncatedSVDt   PolynomialFeaturest   GaussianRandomProjectionHasht   HashingVectorizert   CheckingClassifiert   PatchExtractort   CountVectorizert   ZeroEstimatort   ScaledLogOddsEstimatort   QuantileEstimatort   MeanEstimatort   LogOddsEstimatort   PriorProbabilityEstimatort   _SigmoidCalibrationt   VotingClassifierc         C   s  d   } g  } t  j } x t j d | d d d d    D]y \ } } }	 d | k r[ q: n  t r d | k s: d	 | k r q: n  t | d
 d }
 t j |
 t j  } | j	 |  q: Wt
 |  } g  | D]/ } t | d t  r | d d k r | ^ q } g  | D] } | | d  s| ^ q} | sZg  | D] } | d t k r5| ^ q5} n  | sg  | D] } | d t k rg| ^ qg} n  |  sg  | D] } | d t k r| ^ q} n  | d k	 rt | t  s| g } n t |  } g  } i t d 6t d 6t d 6t d 6} xi | j   D][ \ } } | | k r&| j |  | j	 g  | D] } t | d |  rX| ^ qX q&q&W| } | rt d t |    qn  t t
 |  d t d  S(   s  Get a list of all estimators from sklearn.

    This function crawls the module and gets all classes that inherit
    from BaseEstimator. Classes that are defined in test-modules are not
    included.
    By default meta_estimators such as GridSearchCV are also not included.

    Parameters
    ----------
    include_meta_estimators : boolean, default=False
        Whether to include meta-estimators that can be constructed using
        an estimator as their first argument. These are currently
        BaseEnsemble, OneVsOneClassifier, OutputCodeClassifier,
        OneVsRestClassifier, RFE, RFECV.

    include_other : boolean, default=False
        Wether to include meta-estimators that are somehow special and can
        not be default-constructed sensibly. These are currently
        Pipeline, FeatureUnion and GridSearchCV

    type_filter : string, list of string,  or None, default=None
        Which kind of estimators should be returned. If None, no filter is
        applied and all estimators are returned.  Possible values are
        'classifier', 'regressor', 'cluster' and 'transformer' to get
        estimators only of these specific types, or a list of these to
        get the estimators that fit at least one of the types.

    include_dont_test : boolean, default=False
        Whether to include "special" label estimator or test processors.

    Returns
    -------
    estimators : list of tuples
        List of (name, class), where ``name`` is the class name as string
        and ``class`` is the actuall type of the class.
    c         S   s*   t  |  d  s t St |  j  s& t St S(   Nt   __abstractmethods__(   R/   RB   R1   R   R-   (   t   c(    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   is_abstract  s
    t   patht   prefixs   sklearn.t   onerrorc         S   s   d  S(   N(   R   (   RH   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyR@     s    s   .tests.t   _svmlight_formats   feature_extraction._hashingt   fromlistt   dummyi   i    R
   t
   classifiert	   regressort   transformert   clustersb   Parameter type_filter must be 'classifier', 'regressor', 'transformer', 'cluster' or None, got %s.t   keyN(   R   t   __path__t   pkgutilt   walk_packagesR   t
   __import__t   inspectt
   getmemberst   isclasst   extendt   setRA   R
   t	   DONT_TESTt   OTHERt   META_ESTIMATORSR   RV   R   R   R   R   R   t   itemst   removeRY   t   reprR   R   (   t   include_meta_estimatorst   include_othert   type_filtert   include_dont_testR   t   all_classesR   t   importert   modnamet   ispkgt   modulet   classesR   t
   estimatorst   filtered_estimatorsRm   Rj   t   mixint   est(    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   all_estimators_  sV    '		%),,,

'i    c         C   s)   d |  j    k r% |  j d |  n  d S(   s  Set random state of an estimator if it has the `random_state` param.

    Parameters
    ----------
    estimator : object
        The estimator
    random_state : int, RandomState instance or None, optional, default=0
        Pseudo random number generator state.  If int, random_state is the seed
        used by the random number generator; If RandomState instance,
        random_state is the random number generator; If None, the random number
        generator is the RandomState instance used by `np.random`.
    t   random_stateN(   t
   get_paramst
   set_params(   t	   estimatorR  (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   set_random_state  s    c            s   t       f d    } | S(   sh   Test decorator that skips test if matplotlib not installed.

    Parameters
    ----------
    func
    c             sm   y< d d  l  } | j d d t d d  l j } | j   Wn t k
 r[ t d   n X  |  |   Sd  S(   Nit   AggRM   s   Matplotlib not available.(   t
   matplotlibt   useRB   t   matplotlib.pyplott   pyplott   figuret   ImportErrorR!   (   R6   Re   R  t   plt(   R5   (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   run_test  s    (   R    (   R5   R  (    (   R5   s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   if_matplotlib  s    t   reasons   skipped on 32bit platformst   TRAVISt   trues   skip on traviss   not compatible with PyPys   joblib is in serial modet   darwins)   Possible multi-process bug with some BLASc          C   sg   d }  xZ t  t j j    D]C \ } } d | k r: q n  t | |   r t | |   j   q q Wd S(   s  Clean Python warning registry for easier testing of warning messages.

    We may not need to do this any more when getting rid of Python 2, not
    entirely sure. See https://bugs.python.org/issue4180 and
    https://bugs.python.org/issue21724 for more details.

    t   __warningregistry__s	   six.movesN(   R   R_   R`   R   R/   t   getattrt   clear(   t   regt   mod_namet   mod(    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyR*     s    "c           C   s.   t  t j j d d   r* t d   n  d  S(   Nt   SKLEARN_SKIP_NETWORK_TESTSi    s-   Text tutorial requires large dataset download(   t   intt   ost   environt   getR!   (    (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   check_skip_network$  s    c         C   sX   y& t  j j |   r% t j |   n  Wn+ t k
 rS | rT t j d |   qT n Xd S(   su   Utility function to cleanup a temporary folder if still existing.

    Copy from joblib.pool (for independence).
    s$   Could not delete temporary folder %sN(   R#  R   t   existst   shutilt   rmtreet   WindowsErrorR+   RM   (   t   folder_pathRM   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   _delete_folder)  s    t
   TempMemmapc           B   s,   e  Z d  Z d d  Z d   Z d   Z RS(   s:   
    Parameters
    ----------
    data
    mmap_mode
    t   rc         C   s   | |  _  | |  _ d  S(   N(   t	   mmap_modeR   (   Rd   R   R/  (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyR"   ?  s    	c         C   s+   t  |  j d |  j d t \ } |  _ | S(   NR/  t   return_folder(   t   create_memmap_backed_dataR   R/  R-   t   temp_folder(   Rd   t   data_read_only(    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyRq   C  s    $c         C   s   t  |  j  d  S(   N(   R,  R2  (   Rd   t   exc_typet   exc_valt   exc_tb(    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyRs   H  s    (   R3   Rt   Ru   R"   Rq   Rs   (    (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyR-  8  s   	R.  c         C   s   t  j d d  } t j t j t | d t  t j	 | d  } t
 j |  |  t
 j | d | } | st | n	 | | f } | S(   sL   
    Parameters
    ----------
    data
    mmap_mode
    return_folder
    R   t   sklearn_testing_RM   s   data.pklR/  (   t   tempfilet   mkdtempt   atexitt   registert	   functoolst   partialR,  R-   t   opRS   R   t   dumpt   load(   R   R/  R0  R2  t   filenamet   memmap_backed_dataR9   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyR1  L  s    c         C   s   y t  |   j } Wn t k
 r' g  SXg  | j   D]- \ } } | j | j | j f k r5 | ^ q5 } | r g  | j   D]! } | j | j k r{ | j ^ q{ } t	 |  d k r d } n  | | f S| Sd S(   s    Helper to get function argumentsi    N(   R   t
   parametersRY   R   t   kindt   VAR_POSITIONALt   VAR_KEYWORDt   valuesRj   R1   R   (   Rx   t   varargst   paramsR   t   paramR6   (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt	   _get_argsa  s    '!	
c         C   s   g  } t  j |   } | r. | j | j  n  | d k	 rJ | j |  n% t |  d  ro | j |  j j  n  | j |  j  d j |  S(   sR  Get function full name

    Parameters
    ----------
    func : callable
        The function object.
    class_name : string, optional (default: None)
       If ``func`` is a class method and the class name is known specify
       class_name for the error message.

    Returns
    -------
    name : str
        The function name.
    t   im_classt   .N(   R   t	   getmoduleRi   R3   R   R/   RL  RS   (   R5   t
   class_namet   partsR  (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   _get_func_nameu  s    c      	      s=  d d l  m } g  }   d k r( g  n     t |  d | } | j d  s_ | j d  rc | St j |   rv | S| j d  d d k r | S| j d  d	 d
 k r | St t	   f d   t
 |     } t |  d k r| d d k r| j d  n  | d k rt j d t  L } y | j |   } Wn/ t k
 rk}	 | | d t |	  g 7} | SXWd QXt |  rt d | | d f   qn  g  }
 x | d D] \ } } } | j   sAd | k r| | j d   d j   r| | d | g 7} qA| j   j d  rA| | d | j   g 7} qAn  d | k r|
 j | j d  d j d   qqWt t	   f d   |
   }
 t |
  t |  k rt t t t |
  t |  A   } | | d | g 7} nL xI t |
 |  D]8 \ } } | | k r| | d | d | g 7} qqW| S(   s  Helper to check docstring

    Parameters
    ----------
    func : callable
        The function object to test.
    doc : str, optional (default: None)
        Docstring if it is passed manually to the test.
    ignore : None | list
        Parameters to ignore.
    class_name : string, optional (default: None)
       If ``func`` is a class method and the class name is known specify
       class_name for the error message.

    Returns
    -------
    incorrect : list
        A list of string describing the incorrect results.
    i(   t	   docscrapeRO  s   sklearn.s   sklearn.externalsRM  t   setup_modulet   teardown_modulei   t   estimator_checksc            s
   |    k S(   N(    (   RH   (   R=   (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyR@     s    i    Rd   R#   s    parsing error: Ns   Error for %s:
%st
   Parameterst   :s9    There was no space between the param name and colon (%r)s6    Parameter %r has an empty type spec. Remove the colont   *s   ` c            s
   |    k S(   N(    (   RH   (   R=   (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyR@     s    s    arg mismatch: t    s    != (   RS  RT  (   t   numpydocRR  R   RQ  t
   startswithR   t   isdatadescriptorR   R   t   filterRK  R1   R   R+   R,   R-   t   FunctionDoct	   ExceptionRD   Rl   t   stripRI   t   rstript   endswitht   lstripRi   R   R   t   zip(   R5   t   docR=   RO  RR  t	   incorrectt	   func_nameR6   R8   t   expt   param_namesRj   t   type_definitiont	   param_doct   badt   n1t   n2(    (   R=   s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   check_docstring_parameters  s\    $" )*($(   Ru   R#  R   R   R+   R_   R<  R   R   t   scipy.ioR    t   operatorR   t   urllib2R   R   R  t   urllib.requestt   urllib.errorR8  R(  t   os.pathR   R>  R:  t   unittestR*  t	   NameErrorR   t   numpy.testingR   R   R   R   R   R	   t   numpyR0   R   t   sklearn.baseR
   R   R   R   R   t   sklearn.utilsR   R   R   t   sklearn.utils._joblibR   t    sklearn.utils._unittest_backportR   t   sklearn.utils.fixesR   t   additional_names_in_allt
   nose.toolsR   t   _nose_raisest   deprecation_messageRi   R   t   _with_setupt   __all__R   t   _dummyt   assertEqualR   t   assertNotEqualR   t
   assertTrueR   t   assertFalseR   t   assertRaisesR   t   caseR!   t   assertDictEqualt   assert_dict_equalt   assertInt	   assert_int   assertNotInt   assert_not_int
   assertLessR   t   assertGreaterR   t   assertLessEqualR   t   assertGreaterEqualR    t   assertRaisesRegext   assert_raises_regexR   R<   RK   RR   RT   RX   R]   R   R[   R{   R   R   R   R   R   R   R   R   RB   R  R  R  t   pytestt   markt   skipift   skip_if_32bitR$  R%  t   skip_travist   xfailt   NotImplementedErrort   fails_if_pypyt   parallelt   mpt   skip_if_no_parallelt   platformt!   if_safe_multiprocessing_with_blasR*   R&  R,  R-  R1  RK  RQ  Ro  (    (    (    s4   lib/python2.7/site-packages/sklearn/utils/testing.pyt   <module>   s  
(																,	E		*;	*)	+0						f		!						