
    M/Ph<                     V    d Z ddlZddlmZ 	 ddZ	 	 	 ddZ	 	 ddZd	 Zd
 Z	ddZ
dS )z5
Created on Wed May 30 15:11:09 2018

@author: josef
    N)statsc                 n   ||||f\  }}}}t           j                            |          }	|                    |          }
|
                    |           }|+|)|                     |                    |                     }n|.|
                    |                              |
j                  }n-|                    |                              |j                  }|                    t           j                            ||                    }t          j                            ||	          }|||	fS )a  general formula for score/LM test

    generalized score or lagrange multiplier test for implicit constraints

    `r(params) = 0`, with gradient `R = d r / d params`

    linear constraints are given by `R params - q = 0`

    It is assumed that all arrays are evaluated at the constrained estimates.


    Parameters
    ----------
    score : ndarray, 1-D
        derivative of objective function at estimated parameters
        of constrained model
    constraint_matrix R : ndarray
        Linear restriction matrix or Jacobian of nonlinear constraints
    score_deriv_inv, Ainv : ndarray, symmetric, square
        inverse of second derivative of objective function
        TODO: could be inverse of OPG or any other estimator if information
        matrix equality holds
    cov_score B :  ndarray, symmetric, square
        covariance matrix of the score. This is the inner part of a sandwich
        estimator.
    cov_params V :  ndarray, symmetric, square
        covariance of full parameter vector evaluated at constrained parameter
        estimate. This can be specified instead of cov_score B.

    Returns
    -------
    lm_stat : float
        score/lagrange multiplier statistic
    p-value : float
        p-value of the LM test based on chisquare distribution

    Notes
    -----

    )	nplinalgmatrix_rankdotTsolver   chi2sf)scoreconstraint_matrixscore_deriv_inv	cov_score
cov_paramsRAinvBVk_constraintstmpwscorelm_statinnerpvals                  e/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/base/_parameter_inference.py
_lm_robustr      s    V &	:MMAtQI))!,,M
%%++CWWU^^FyQY ))DHHUOO,, 9GGAJJNN35))EEEE!HHLL%%E **RY__UF;;<<:==-00DD-''    jointTc
                 L	   t          | d          r| j        } | j        }
|
j        j        d         }|| j        }||n| j        }|	du rddi}ni }|t          | d          rBt          | j        t                    r| j        d         }n| j        j
        }|j        d         }n|t          d          |
d|i}||d<   ni } |
j        |fi |} |
j        |fi |} |
j        |fi |}n|d	k    rt          d
          t          | d          rt          d          t          |t                    r/t!          | |g|R d|i}|\  }}}}|                    d          }nDt%          j        |          }d}t%          j        |
j        |f          }||j        d         |
j        j        d         z
  z  }t%          j        t/          | j                  |z             | d         }|
                    |          }|j        dk    r|dddf         |z  }n3|}t%          j        |ddddf         |z  |ddddf         f          }|                    d          } |
j        |fi |}ddlm} t          |
|          r|dz  }t%          j        |j        |z  |          }|dk    r| }n|                                dk    rRt$          j         !                    |           }|t%          j"        |j                  z  }tG          ||||d          }|S |                                d	k    r{t$          j         !                    |           }|t%          j"        |j                  z  }| j$        }tG          |||||          }tJ          j&        '                    ||          }||fS d}t          |          |dk    rb|                    t$          j         (                    ||dddf                             }tJ          j&        '                    ||          }|||fS |dk    re|}t%          j)        t%          j*        |                    } || z  }!tJ          j+        '                    t%          j,        |!                    dz  }|!|fS t          d          )a  score test for restrictions or for omitted variables

    Null Hypothesis : constraints are satisfied

    Alternative Hypothesis : at least one of the constraints does not hold

    This allows to specify restricted and unrestricted model properties in
    three different ways

    - fit_constrained result: model contains score and hessian function for
      the full, unrestricted model, but the parameter estimate in the results
      instance is for the restricted model. This is the case if the model
      was estimated with fit_constrained.
    - restricted model with variable addition: If exog_extra is not None, then
      it is assumed that the current model is a model with zero restrictions
      and the unrestricted model is given by adding exog_extra as additional
      explanatory variables.
    - unrestricted model with restricted parameters explicitly provided. If
      params_constrained is not None, then the model is assumed to be for the
      unrestricted model, but the provided parameters are for the restricted
      model.
      TODO: This case will currently only work for `nonrobust` cov_type,
      otherwise we will also need the restriction matrix provided by the user.


    Parameters
    ----------
    exog_extra : None or array_like
        Explanatory variables that are jointly tested for inclusion in the
        model, i.e. omitted variables.
    params_constrained : array_like
        estimated parameter of the restricted model. This can be the
        parameter estimate for the current when testing for omitted
        variables.
    hypothesis : str, 'joint' (default) or 'separate'
        If hypothesis is 'joint', then the chisquare test results for the
        joint hypothesis that all constraints hold is returned.
        If hypothesis is 'joint', then z-test results for each constraint
        is returned.
        This is currently only implemented for cov_type="nonrobust".
    cov_type : str
        Warning: only partially implemented so far, currently only "nonrobust"
        and "HC0" are supported.
        If cov_type is None, then the cov_type specified in fit for the Wald
        tests is used.
        If the cov_type argument is not None, then it will be used instead of
        the Wald cov_type given in fit.
    k_constraints : int or None
        Number of constraints that were used in the estimation of params
        restricted relative to the number of exog in the model.
        This must be provided if no exog_extra are given. If exog_extra is
        not None, then k_constraints is assumed to be zero if it is None.
    observed : bool
        If True, then the observed Hessian is used in calculating the
        covariance matrix of the score. If false then the expected
        information matrix is used. This currently only applies to GLM where
        EIM is available.
        Warning: This option might still change.

    Returns
    -------
    chi2_stat : float
        chisquare statistic for the score test
    p-value : float
        P-value of the score test based on the chisquare distribution.
    df : int
        Degrees of freedom used in the p-value calculation. This is equal
        to the number of constraints.

    Notes
    -----
    Status: experimental, several options are not implemented yet or are not
    verified yet. Currently available ptions might also still change.

    cov_type is 'nonrobust':

    The covariance matrix for the score is based on the Hessian, i.e.
    observed information matrix or optionally on the expected information
    matrix.

    cov_type is 'HC0'

    The covariance matrix of the score is the simple empirical covariance of
    score_obs without degrees of freedom correction.
    _resultsr   NFobservedconstraintsz:if exog_extra is None, then k_constraintsneeds to be givenscaler   z4if exog_extra is not None, then cov_type cannot be VzJif exog_extra is not None, then selfshould not be a constrained fit result	hess_kwds   )GLM	nonrobustHC0)r   z2Only cov_type "nonrobust" and "HC0" are available.r   separate   z$only hypothesis "joint" is available)-hasattrr!   modelendogshapeparamscov_type
isinstancer#   tuplecoefs
ValueErrorr   	score_obshessianNotImplementedError_scorehess_extrasumr   asarraycolumn_stackexogeyelenscore_factorndimhessian_factor+statsmodels.genmod.generalized_linear_modelr'   r   r	   upperr   invcovr   cov_params_defaultr   r   r   r
   sqrtdiagnormabs)"self
exog_extraparams_constrained
hypothesisr2   cov_kwdsr   r_matrixr$   r"   r.   nobshess_kwd	score_kwdr   r7   r8   shexrA   r   rC   r'   cov_score_testhinvr   lmr   chi2statr   msgdiffbsestats"                                     r   
score_testr`   O   sK   r tZ   }JE;QD!![#/xxT]H5&4'' 
	6$*E22 2+A.+1$N1-MM $  "5 6 6 6  %(I %HWI .<<)<<#EO$6DD)DD	%- 2??h?? s?? $ % % %4'' 	P% 'O P P P j%(( 	8!$(: 6Z 6 6 6,46 6B:<7IwxMM!$$EEJ//JM%*j!9::B RXa[5:+;A+>>>Mvc$+..>    !.1H !--.@AAL A%%)!!!T'2R7		!OR2A2Y^R122Y,GHH	MM!$$E1U12D > >4<> >N HGGGGG%%% %"$fRTN2B77G;!			U	"	"	g&&&26)+...	xyTJJJ	
 
		S	 	  	g&&&26)+...	#eXtY1MMMz}}X}55~B!#&&&W99RY__^U111d7^LLMMz}}X}55},,	z	!	!gbgn--..czz}}RVD\\**1,Tz!"HIIIr   c                    |i }| j         }|| j        }|                                \  }}|!t          j        |j        d         df          }|j        d         }|j        d         }	|t          j        ||f          }
n|}
|t          j        ||f          }n|}|
j        d         }|j        d         }||z
  }||	z
  }||z   }t          j        ||          }t          j        ||	z   ||z             }t          j        |t          |          |z   f          }t          j
        |          |d||f<   t          j
        |          ||||z   |f<   t          |d          r |j        |fddi|\  }}n#|                    |          } |j        |fi |}|\  }}|\  }}}|dddf         |
z  }|dddf         |z  }t          j        ||f          }|
j        |z                      |
          }|
j        |z                      |          }|j        |z                      |          } t          j        ||g|j        | gg          }!||!||fS )zExperimental helper function for variable addition score test.

    This uses score and hessian factor at the params which should be the
    params of the restricted model.

    Nr   r&   score_hessian_factorreturn_hessianT)r.   r1   
_get_exogsr   onesr0   r=   arangezerosr@   r?   r-   rb   rA   rC   r	   r   block)"rM   r1   rN   exog2_extrar%   r.   exog_o1exog_o2k_meank_precr>   exog2
k_mean_new
k_prec_newk_cmk_cpr   
index_mean
index_precrR   r   hfsf1sf2hf11hf12hf22d1d2r7   d11d12d22r8   s"                                     r   r:   r:   "  s    	JE~ ''))GW'7=+Q/00]1F]1F455+ 677AJQJDD4KM6:..J:.
Z0GHHJxFm(CDEEH #%&,,HUdUJ.0fTllHT4$;
*+u,-- 7++F 9 94 9.79 9BB ''!U!&66I66HCD$ 
QQQW	B	QQQW	BR))I 6D=

d
#
#C6D=

e
$
$C7T>

u
%
%Chc
SUCL122Gg}h66r   c                 J   t          | d|           }|j                            |j                  }|j        dk    rO|j                            |j                  }|j        |z  }t          j        	                    |           }||z  }n|
                                | z  }|S )Nr!   r)   )getattrr.   r8   r1   r2   r7   r	   r   r   rF   r   )resultsreshessr7   r   hessneg_invim_ratios          r   r   r   l  s    
':w
/
/C9SZ((D
|{""I''
33	K)+	immTE***>>##u-Or   c                     t          | dt          |                     }d| j        z  dt          j        |          z  z   }|S )z<Takeuchi information criterion for misspecified models

    r   r,   )r   r   llfr   trace)r   imrtics      r   r   r   y  s@     ':x'8'8
9
9C

a"(3--/
/CJr   Fc                 R   t          | d|           }|j        dz   }||j        z   }t          | dt          |                     }t          j                            |          d         }d|j        z  |t	          j        |          z  z   |z
  }|t	          j	        |          z   }||fS )u  generalized BIC for misspecified models

    References
    ----------
    Lv, Jinchi, and Jun S. Liu. 2014. "Model Selection Principles in
    Misspecified Models." Journal of the Royal Statistical Society.
    Series B (Statistical Methodology) 76 (1): 141–67.

    r!   r&   r   r   )
r   df_modeldf_residr   r   r   slogdetr   logr   )r   gbicprM   k_paramsrS   r   
imr_logdetgbics           r   r   r     s     7J00D}q Hdm#D
':x'8'8
9
9C""3''*J=8bfTll22Z?D28C== E;r   )N)	NNr   NNNNNT)NNNN)F)__doc__numpyr   scipyr   r   r`   r:   r   r   r    r   r   <module>r      s              
 @( @( @( @(F :>;?GKPJ PJ PJ PJf 4815G7 G7 G7 G7T
 
 
       r   