
    M/Ph&'                     8    d Z ddlZddlmZ  G d d          ZdS )z(
Author: Josef Perktold
License: BSD-3

    N)statsc                   X    e Zd ZdZddZddZd Zd Zd Zd Z	d	 Z
	 	 ddZ	 	 ddZdS )NonlinearDeltaCova  Asymptotic covariance by Deltamethod

    The function is designed for 2d array, with rows equal to
    the number of equations or constraints and columns equal to the number
    of parameters. 1d params work by chance ?

    fun: R^{m*k) -> R^{m}  where m is number of equations and k is
    the number of parameters.

    equations follow Greene

    This class does not use any caching. The intended usage is as a helper
    function. Extra methods have been added for convenience but might move
    to calling functions.

    The naming in this class uses params for the original random variable, and
    cov_params for it's covariance matrix. However, this class is independent
    of the use cases in support of the models.

    Parameters
    ----------
    func : callable, f(params)
        Nonlinear function of the estimation parameters. The return of
        the function can be vector valued, i.e. a 1-D array.
    params : ndarray
        Parameters at which function `func` is evaluated.
    cov_params : ndarray
        Covariance matrix of the parameters `params`.
    deriv : function or None
        First derivative or Jacobian of func. If deriv is None, then a
        numerical derivative will be used. If func returns a 1-D array,
        then the `deriv` should have rows corresponding to the elements
        of the return of func.
    func_args : None
        Not yet implemented.


    Nc                 v    || _         || _        || _        || _        ||nd| _        |t          d          d S )N zfunc_args not yet implemented)funparams
cov_params_grad	func_argsNotImplementedError)selffuncr	   r
   derivr   s         _/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/stats/_delta_method.py__init__zNonlinearDeltaCov.__init__2   sK    $
&/&; %&EFFF !     c                     || j         }| j        |                     |          S 	 ddlm}  ||| j        fi |}n%# t
          $ r ddlm}  ||| j        fi |}Y nw xY w|S )ai  First derivative, jacobian of func evaluated at params.

        Parameters
        ----------
        params : None or ndarray
            Values at which gradient is evaluated. If params is None, then
            the attached params are used.
            TODO: should we drop this
        kwds : keyword arguments
            This keyword arguments are used without changes in the calulation
            of numerical derivatives. These are only used if a `deriv` function
            was not provided.

        Returns
        -------
        grad : ndarray
            gradient or jacobian of the function
        Nr   )approx_fprime_cs)approx_fprime)r	   r   statsmodels.tools.numdiffr   r   	TypeErrorr   )r   r	   kwdsr   jacr   s         r   gradzNonlinearDeltaCov.grad;   s    & >[F:!::f%%%>FFFFFF&&vtx@@4@@ > > >CCCCCC#mFDH====> Js   = AAc                     |                                  }t          j        t          j        || j                  |j                  }|S )z>Covariance matrix of the transformed random variable.
        )r   npdotr
   T)r   gcovars      r   covzNonlinearDeltaCov.cov]   s7     IIKKrva111377r   c                 x    |                      | j                  }|j        dk    r|                                }|S )a=  Value of the function evaluated at the attached params.

        Note: This is not equal to the expected value if the transformation is
        nonlinear. If params is the maximum likelihood estimate, then
        `predicted` is the maximum likelihood estimate of the value of the
        nonlinear function.
           )r   r	   ndimsqueeze)r   	predicteds     r   r'   zNonlinearDeltaCov.predictedd   s=     HHT[))	 >A!))++Ir   c                 \   |                                  }|                                 }t          j        |          }||z
  }t          j        t          j        |j        t          j                            |                    |          }|t          j	        
                    ||          fS )a  Joint hypothesis tests that H0: f(params) = value.

        The alternative hypothesis is two-sided H1: f(params) != value.

        Warning: this might be replaced with more general version that returns
        ContrastResults.
        currently uses chisquare distribution, use_f option not yet implemented

        Parameters
        ----------
        value : float or ndarray
            value of f(params) under the Null Hypothesis

        Returns
        -------
        statistic : float
            Value of the test statistic.
        pvalue : float
            The p-value for the hypothesis test, based and chisquare
            distribution and implies a two-sided hypothesis test
        )r'   r"   r   sizer   r   linalginvr   chi2sf)r   valuemvdf_constraintsdifflmstats          r   	wald_testzNonlinearDeltaCov.wald_testt   s~    . NNHHJJ5ytvry}}Q'7'788$??uz}}V^<<<<r   c                     |                                  }t          j        || j                  |z                      d          }|j        dk    r|j        }|S )Cstandard error for each equation (row) treated separately

           )r   r   r   r
   sumr%   r   )r   r    vars      r   r:   zNonlinearDeltaCov.var   sN     IIKKva))A-222668q==%C
r   c                 R    |                                  }t          j        |          S )r6   )r:   r   sqrt)r   r:   s     r   se_vectorizedzNonlinearDeltaCov.se_vectorized   s     hhjjws||r   皙?Fc                    |st           j        }d}n |t          d          t           j        }|f}||                                 }||                                 }|t          j        |dz  |z             } |j        d|dz  z
  g|R  }	||	|z  z
  }
||	|z  z   }t          j	        |
|f          }|j
        d         dk    rt          d          |S )a  
        Confidence interval for predicted based on delta method.

        Parameters
        ----------
        alpha : float, optional
            The significance level for the confidence interval.
            ie., The default `alpha` = .05 returns a 95% confidence interval.
        use_t : boolean
            If use_t is False (default), then the normal distribution is used
            for the confidence interval, otherwise the t distribution with
            `df` degrees of freedom is used.
        df : int or float
            degrees of freedom for t distribution. Only used and required if
            use_t is True.
        var_extra : None or array_like float
            Additional variance that is added to the variance based on the
            delta method. This can be used to obtain confidence intervalls for
            new observations (prediction interval).
        predicted : ndarray (float)
            Predicted value, can be used to avoid repeated calculations if it
            is already available.
        se : ndarray (float)
            Standard error, can be used to avoid repeated calculations if it
            is already available.

        Returns
        -------
        conf_int : array
            Each row contains [lower, upper] limits of the confidence interval
            for the corresponding parameter. The first column contains all
            lower, the second column contains all upper limits.
        r   Nzt distribution requires dfr8   r$   g       @z!something wrong: ci not 2 columns)r   norm
ValueErrortr'   r=   r   r<   ppfcolumn_stackshapeRuntimeError)r   alphause_tdf	var_extrar'   sedist	dist_argsqloweruppercis                r   conf_intzNonlinearDeltaCov.conf_int   s    L  	:DIIz !=>>>7DI((I:##%%B Q*++BDHQ^0i000AF"AF"_eU^,,8A;!BCCC	r   c                 n   ddl m} |                                 }|                                 }t	          j        |          }|j        dk    r|                                }t	          j        |          }||z  }	|r|}
 |||	||
          }n |||	|dd          }|                    |||          S )	a  Summarize the Results of the nonlinear transformation.

        This provides a parameter table equivalent to `t_test` and reuses
        `ContrastResults`.

        Parameters
        -----------
        xname : list of strings, optional
            Default is `c_##` for ## in p the number of regressors
        alpha : float
            Significance level for the confidence intervals. Default is
            alpha = 0.05 which implies a confidence level of 95%.
        title : string, optional
            Title for the params table. If not None, then this replaces the
            default title
        use_t : boolean
            If use_t is False (default), then the normal distribution is used
            for the confidence interval, otherwise the t distribution with
            `df` degrees of freedom is used.
        df : int or float
            degrees of freedom for t distribution. Only used and required if
            use_t is True.

        Returns
        -------
        smry : string or Summary instance
            This contains a parameter results table in the case of t or z test
            in the same form as the parameter results table in the model
            results summary.
            For F or Wald test, the return is a string.
        r   )ContrastResultsr$   )effectrB   sddf_denomNr@   )rU   	statisticrV   rW   distribution)xnamerG   title)	statsmodels.stats.contrastrT   r'   r=   r   
atleast_1dr%   r&   summary)r   rZ   rG   r[   rH   rI   rT   r'   rK   rX   df_residcrs               r   r^   zNonlinearDeltaCov.summary   s    D 	?>>>>>NN$$	!!M),,	>A!))++I]2N	 	EH 	Y2*24 4 4BB !	Y2*.VE E EB zzU%z@@@r   )NN)N)r>   FNNNN)Nr>   NFN)__name__
__module____qualname____doc__r   r   r"   r'   r4   r:   r=   rR   r^   r   r   r   r   r      s        % %LG G G G       D     = = =<	 	 	   DH$(< < < <| AF4A 4A 4A 4A 4A 4Ar   r   )rd   numpyr   scipyr   r   r   r   r   <module>rg      su              KA KA KA KA KA KA KA KA KA KAr   