
    M/Ph                     <    d Z ddlZddlmZ d Zd
dZd
dZdd	ZdS )zTools for multivariate analysis


Author : Josef Perktold
License : BSD-3



TODO:

- names of functions, currently just "working titles"

    N)Bunchc                     | |}}t           j                            |                              |          }|                    |          }||z
  }t	          |||          }|S )a  helper function to get linear projection or partialling out of variables

    endog variables are projected on exog variables

    Parameters
    ----------
    endog : ndarray
        array of variables where the effect of exog is partialled out.
    exog : ndarray
        array of variables on which the endog variables are projected.

    Returns
    -------
    res : instance of Bunch with

        - params : OLS parameter estimates from projection of endog on exog
        - fittedvalues : predicted values of endog given exog
        - resid : residual of the regression, values of endog with effect of
          exog partialled out

    Notes
    -----
    This is no-frills mainly for internal calculations, no error checking or
    array conversion is performed, at least for now.

    )paramsfittedvaluesresid)nplinalgpinvdotr   )endogexogx1x2r   	predictedresidualress           d/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/stats/multivariate_tools.pypartial_projectr      si    6 DBY^^B##B''FvII~H
v&     C J    TFc                 `   |s|r0| |                      d          z
  } ||                     d          z
  }|r0| |                     d          z  } ||                    d          z  }t          j                            |                               |          }t          j                            |                              |           }|                    |          }t          j        t          j                            |                    }|                                 |ddd         S )a  canonical correlation coefficient beween 2 arrays

    Parameters
    ----------
    x1, x2 : ndarrays, 2_D
        two 2-dimensional data arrays, observations in rows, variables in columns
    demean : bool
         If demean is true, then the mean is subtracted from each variable
    standardize : bool
         If standardize is true, then each variable is demeaned and divided by
         its standard deviation. Rescaling does not change the canonical
         correlation coefficients.

    Returns
    -------
    ccorr : ndarray, 1d
        canonical correlation coefficients, sorted from largest to smallest.
        Note, that these are the square root of the eigenvalues.

    Notes
    -----
    This is a helper function for other statistical functions. It only
    calculates the canonical correlation coefficients and does not do a full
    canoncial correlation analysis

    The canonical correlation coefficient is calculated with the generalized
    matrix inverse and does not raise an exception if one of the data arrays
    have less than full column rank.

    See Also
    --------
    cc_ranktest
    cc_stats
    CCA not yet

    r   N)	meanstdr   r	   r
   r   sqrteigvalssort)r   r   demeanstandardizet1t2mccs           r   cancorrr#   <   s    L   2771::o2771::o 
bffQii
bffQii						#	#B						#	#B
r

A	""1%%	&	&BGGIIIddd8Or   c           	         ddl m} | j        \  }}|j        \  }}t          | ||          }	|	|	z  }
|rvt	          j        ||z
            dz   }||
d         z  }||
d         d|
d         z
  z  z  }||j                            ||          ||	||j                            ||          fS t	          j        t          ||                    ddd         }||z
  ||z
  z  }||
ddd         
                                z  }||
d|
z
  z  ddd         
                                z  }||j                            ||          ||	||j                            ||          fS )aj  rank tests based on smallest canonical correlation coefficients

    Anderson canonical correlations test (LM test) and
    Cragg-Donald test (Wald test)
    Assumes homoskedasticity and independent observations, overrejects if
    there is heteroscedasticity or autocorrelation.

    The Null Hypothesis is that the rank is k - 1, the alternative hypothesis
    is that the rank is at least k.


    Parameters
    ----------
    x1, x2 : ndarrays, 2_D
        two 2-dimensional data arrays, observations in rows, variables in columns
    demean : bool
         If demean is true, then the mean is subtracted from each variable.
    fullrank : bool
         If true, then only the test that the matrix has full rank is returned.
         If false, the test for all possible ranks are returned. However, no
         the p-values are not corrected for the multiplicity of tests.

    Returns
    -------
    value : float
        value of the test statistic
    p-value : float
        p-value for the test Null Hypothesis tha the smallest canonical
        correlation coefficient is zero. based on chi-square distribution
    df : int
        degrees of freedom for thechi-square distribution in the hypothesis test
    ccorr : ndarray, 1d
        All canonical correlation coefficients sorted from largest to smallest.

    Notes
    -----
    Degrees of freedom for the distribution of the test statistic are based on
    number of columns of x1 and x2 and not on their matrix rank.
    (I'm not sure yet what the interpretation of the test is if x1 or x2 are of
    reduced rank.)

    See Also
    --------
    cancorr
    cc_stats

    r   )statsr      r   g      ?N)scipyr%   shaper#   r   abschi2sfarangemincumsum)r   r   r   fullrankr%   nobs1k1nobs2k2r"   cc2dfvaluew_valuervaluesw_valuess                    r   cc_ranktestr<   s   sx   b IE2IE2	R	'	'	'B
r'C 
`VBG__q B3r7b3r7l34ejmmE2..BwXZA[A[[[Ic"bkk""44R4(1fa TTrT))+++C28,ddd3::<<<uz}}VR00"b(EJMMRZ\^D_D___r   c                    | j         \  }}|j         \  }}t          | ||          }|dz  }|d|z
  z  }	||z  }
|||z
  |z
  z  }t          |
|          }d|
|z
  z  }d||z
  dz
  z  }||
z  }|}|                                }t	          j        dd|	z   z            }|	                                }|	                                }i }||d<   |	|d<   ||d<   ||d<   ||d	<   ||d
<   ||d<   ||d<   |S )a  MANOVA statistics based on canonical correlation coefficient

    Calculates Pillai's Trace, Wilk's Lambda, Hotelling's Trace and
    Roy's Largest Root.

    Parameters
    ----------
    x1, x2 : ndarrays, 2_D
        two 2-dimensional data arrays, observations in rows, variables in columns
    demean : bool
         If demean is true, then the mean is subtracted from each variable.

    Returns
    -------
    res : dict
        Dictionary containing the test statistics.

    Notes
    -----

    same as `canon` in Stata

    missing: F-statistics and p-values

    TODO: should return a results class instead
    produces nans sometimes, singular, perfect correlation of x1, x2 ?

    r&      r'   g      ?z!canonical correlation coefficienteigenvalueszPillai's TracezWilk's LambdazHotelling's TracezRoy's Largest Rootdf_residdf_m)r)   r#   r.   sumr   productmax)r   r   r   r1   r2   r3   r4   r"   r5   lamdf_modelr@   sr!   ndf1df2pt_valuewl_valueht_valuerm_valuer   s                         r   cc_statsrO      s>   < IE2IE2	R	'	'	'B
a%C!c'?C BwHURZ&()HHbAx"}Ax"}q !A
x-C
C wwyyHz!q3w-((HwwyyHwwyyH C/1C+,C$C#C'C (CC
OCKJr   )TF)T)	__doc__numpyr   statsmodels.tools.toolsr   r   r#   r<   rO    r   r   <module>rT      s          ) ) ) ) ) )# # #N4 4 4 4nB` B` B` B`J> > > > > >r   