
p7]c           @   s  d  Z  d d l Z d d l m Z d d l m Z d d l j j	 Z d d l
 j j Z d d l j j Z d d l j j Z d d l m Z m Z m Z d d l m Z d d l m Z d d	 l m Z m Z m Z d d
 l  m! Z! d d g Z" d   Z# d e j$ f d     YZ% d e j& f d     YZ' d e j( f d     YZ) e j* e) e'  e+ d k rd d l, j- Z. e. j/ j0 j1 d e2  Z3 e% e3 j4 e3 j5  j6   Z7 e7 j8 d d  Z9 e7 j8 d d  Z: n  d S(   s  
Generalized linear models currently supports estimation using the one-parameter
exponential families

References
----------
Gill, Jeff. 2000. Generalized Linear Models: A Unified Approach.
    SAGE QASS Series.

Green, PJ. 1984.  "Iteratively reweighted least squares for maximum
    likelihood estimation, and some robust and resistant alternatives."
    Journal of the Royal Statistical Society, Series B, 46, 149-192.

Hardin, J.W. and Hilbe, J.M. 2007.  "Generalized Linear Models and
    Extensions."  2nd ed.  Stata Press, College Station, TX.

McCullagh, P. and Nelder, J.A.  1989.  "Generalized Linear Models." 2nd ed.
    Chapman & Hall, Boca Rotan.
iNi   (   t   families(   t   cache_readonly(   t   _plot_added_variable_doct   _plot_partial_residuals_doct   _plot_ceres_residuals_doc(   t   _prediction(   t   PredictionResults(   t   PerfectSeparationErrort   DomainWarningt   HessianInversionWarning(   t   LinAlgErrort   GLMR   c         C   s(   t  j |  | |  | d d | d | S(   Ni   t   atolt   rtol(   t   npt   allclose(   t	   criteriont	   iterationR   R   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   _check_convergence/   s    c           B   s  e  Z d  i e j d 6Z d- d- d- d- d- d d  Z d   Z d   Z d   Z	 d d  Z
 d- d	  Z d- d
  Z d- d  Z d- d  Z d- e d  Z d- d- d  Z d- d  Z d   Z d- d  Z d- d- e d  Z d   Z d   Z d   Z d d d d  Z d- d- d- e d  Z d d- d- d- d  Z d   Z d- d d d  d- d! d- d- e e d" d#  Z d- d$ d d  e e d- d! d- d- d" d%  Z d- d d  d- d! d- d- d&  Z  d' d( d- e d)  Z! d* d+  Z" d- d,  Z# RS(.   s&  
    Generalized Linear Models class

    GLM inherits from statsmodels.base.model.LikelihoodModel

    Parameters
    ----------
    endog : array-like
        1d array of endogenous response variable.  This array can be 1d or 2d.
        Binomial family models accept a 2d array with two columns. If
        supplied, each observation is expected to be [success, failure].
    exog : array-like
        A nobs x k array where `nobs` is the number of observations and `k`
        is the number of regressors. An intercept is not included by default
        and should be added by the user (models specified using a formula
        include an intercept by default). See `statsmodels.tools.add_constant`.
    family : family class instance
        The default is Gaussian.  To specify the binomial distribution
        family = sm.family.Binomial()
        Each family can take a link instance as an argument.  See
        statsmodels.family.family for more information.
    offset : array-like or None
        An offset to be included in the model.  If provided, must be
        an array whose length is the number of rows in exog.
    exposure : array-like or None
        Log(exposure) will be added to the linear prediction in the model.
        Exposure is only valid if the log link is used. If provided, it must be
        an array with the same length as endog.
    freq_weights : array-like
        1d array of frequency weights. The default is None. If None is selected
        or a blank value, then the algorithm will replace with an array of 1's
        with length equal to the endog.
        WARNING: Using weights is not verified yet for all possible options
        and results, see Notes.
    var_weights : array-like
        1d array of variance (analytic) weights. The default is None. If None
        is selected or a blank value, then the algorithm will replace with an
        array of 1's with length equal to the endog.
        WARNING: Using weights is not verified yet for all possible options
        and results, see Notes.
    %(extra_params)s

    Attributes
    ----------
    df_model : float
        Model degrees of freedom is equal to p - 1, where p is the number
        of regressors.  Note that the intercept is not reported as a
        degree of freedom.
    df_resid : float
        Residual degrees of freedom is equal to the number of observation n
        minus the number of regressors p.
    endog : array
        See Notes.  Note that `endog` is a reference to the data so that if
        data is already an array and it is changed, then `endog` changes
        as well.
    exposure : array-like
        Include ln(exposure) in model with coefficient constrained to 1. Can
        only be used if the link is the logarithm function.
    exog : array
        See Notes.  Note that `exog` is a reference to the data so that if
        data is already an array and it is changed, then `exog` changes
        as well.
    freq_weights : array
        See Notes. Note that `freq_weights` is a reference to the data so that
        if data is already an array and it is changed, then `freq_weights`
        changes as well.
    var_weights : array
        See Notes. Note that `var_weights` is a reference to the data so that
        if data is already an array and it is changed, then `var_weights`
        changes as well.
    iteration : int
        The number of iterations that fit has run.  Initialized at 0.
    family : family class instance
        The distribution family of the model. Can be any family in
        statsmodels.families.  Default is Gaussian.
    mu : array
        The mean response of the transformed variable.  `mu` is the value of
        the inverse of the link function at lin_pred, where lin_pred is the
        linear predicted value of the WLS fit of the transformed variable.
        `mu` is only available after fit is called.  See
        statsmodels.families.family.fitted of the distribution family for more
        information.
    n_trials : array
        See Notes. Note that `n_trials` is a reference to the data so that if
        data is already an array and it is changed, then `n_trials` changes
        as well. `n_trials` is the number of binomial trials and only available
        with that distribution. See statsmodels.families.Binomial for more
        information.
    normalized_cov_params : array
        The p x p normalized covariance of the design / exogenous data.
        This is approximately equal to (X.T X)^(-1)
    offset : array-like
        Include offset in model with coefficient constrained to 1.
    scale : float
        The estimate of the scale / dispersion of the model fit.  Only
        available after fit is called.  See GLM.fit and GLM.estimate_scale
        for more information.
    scaletype : str
        The scaling used for fitting the model.  This is only available after
        fit is called.  The default is None.  See GLM.fit for more information.
    weights : array
        The value of the weights after the last iteration of fit.  Only
        available after fit is called.  See statsmodels.families.family for
        the specific distribution weighting functions.

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> data = sm.datasets.scotland.load(as_pandas=False)
    >>> data.exog = sm.add_constant(data.exog)

    Instantiate a gamma family model with the default link function.

    >>> gamma_model = sm.GLM(data.endog, data.exog,
    ...                      family=sm.families.Gamma())

    >>> gamma_results = gamma_model.fit()
    >>> gamma_results.params
    array([-0.01776527,  0.00004962,  0.00203442, -0.00007181,  0.00011185,
           -0.00000015, -0.00051868, -0.00000243])
    >>> gamma_results.scale
    0.0035842831734919055
    >>> gamma_results.deviance
    0.087388516416999198
    >>> gamma_results.pearson_chi2
    0.086022796163805704
    >>> gamma_results.llf
    -83.017202161073527

    See Also
    --------
    statsmodels.genmod.families.family.Family
    :ref:`families`
    :ref:`links`

    Notes
    -----
    Only the following combinations make sense for family and link:

     ============= ===== === ===== ====== ======= === ==== ====== ====== ====
     Family        ident log logit probit cloglog pow opow nbinom loglog logc
     ============= ===== === ===== ====== ======= === ==== ====== ====== ====
     Gaussian      x     x   x     x      x       x   x     x      x
     inv Gaussian  x     x                        x
     binomial      x     x   x     x      x       x   x           x      x
     Poission      x     x                        x
     neg binomial  x     x                        x        x
     gamma         x     x                        x
     Tweedie       x     x                        x
     ============= ===== === ===== ====== ======= === ==== ====== ====== ====

    Not all of these link functions are currently available.

    Endog and exog are references so that if the data they refer to are already
    arrays and these arrays are changed, endog and exog will change.

    Statsmodels supports two separte definitions of weights: frequency weights
    and variance weights.

    Frequency weights produce the same results as repeating observations by the
    frequencies (if those are integers). Frequency weights will keep the number
    of observations consistent, but the degrees of freedom will change to
    reflect the new weights.

    Variance weights (referred to in other packages as analytic weights) are
    used when ``endog`` represents an an average or mean. This relies on the
    assumption that that the inverse variance scales proportionally to the
    weight--an observation that is deemed more credible should have less
    variance and therefore have more weight. For the ``Poisson`` family--which
    assumes that occurences scale proportionally with time--a natural practice
    would be to use the amount of time as the variance weight and set ``endog``
    to be a rate (occurrances per period of time). Similarly, using a
    compound Poisson family, namely ``Tweedie``, makes a similar assumption
    about the rate (or frequency) of occurences having variance proportional to
    time.

    Both frequency and variance weights are verified for all basic results with
    nonrobust or heteroscedasticity robust ``cov_type``. Other robust
    covariance types have not yet been verified, and at least the small sample
    correction is currently not based on the correct total frequency count.

    Currently, all residuals are not weighted by frequency, although they may
    incorporate ``n_trials`` for ``Binomial`` and ``var_weights``

    +---------------+----------------------------------+
    | Residual Type | Applicable weights               |
    +===============+==================================+
    | Anscombe      | ``var_weights``                  |
    +---------------+----------------------------------+
    | Deviance      | ``var_weights``                  |
    +---------------+----------------------------------+
    | Pearson       | ``var_weights`` and ``n_trials`` |
    +---------------+----------------------------------+
    | Reponse       | ``n_trials``                     |
    +---------------+----------------------------------+
    | Working       | ``n_trials``                     |
    +---------------+----------------------------------+

    WARNING: Loglikelihood and deviance are not valid in models where
    scale is equal to 1 (i.e., ``Binomial``, ``NegativeBinomial``, and
    ``Poisson``). If variance weights are specified, then results such as
    ``loglike`` and ``deviance`` are based on a quasi-likelihood
    interpretation. The loglikelihood is not correctly specified in this case,
    and statistics based on it, such AIC or likelihood ratio tests, are not
    appropriate.

    t   extra_paramst   nonec	         K   sK  | d  k	 r` t | j t | j   r` d d  l }
 |
 j d | j j j | j j f t	  n  | d  k	 r~ t
 j |  } n  | d  k	 r t
 j |  } n  | d  k	 r t
 j |  } n  | d  k	 r t
 j |  } n  | |  _ | |  _ t t |   j | | d | d | d | d | d | |	 |  j | |  j |  j |  j |  j |  j  | d  k rkt |  d  n  | d  k rt |  d  n  |  j j d |  _ |  j j d	 d
 d d d d d g  |  j j d  |  j   d |	 k r|	 d |  _ n  d } t |  d  r|  j } n  t |  d  r5| |  j } n  | |  _  d  |  _! d  S(   NisB   The %s link function does not respect the domain of the %s family.t   missingt   offsett   exposuret   freq_weightst   var_weightsi    t   weightst   mut   iweightst   _offset_exposuret   n_trialst   familyg        ("   t   Nonet
   isinstancet   linkt   tuplet
   safe_linkst   warningst   warnt	   __class__t   __name__R   R   t   logt   asarrayR   R   t   superR   t   __init__t   _check_inputsR   R   t   endogt   delattrt   shapet   nobst
   _data_attrt   extendt
   _init_keyst   appendt   _setup_binomialR   t   hasattrR   t	   scaletype(   t   selfR.   t   exogR   R   R   R   R   R   t   kwargsR%   t   offset_exposure(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR,     sT    	
		
	

	c         C   s   t  j j |  j  d |  _ |  j d k	 rw |  j j d |  j j d k rw |  j j	   |  _
 |  j
 |  j d |  _ n1 |  j j d |  _
 |  j j d |  j d |  _ d S(   s8   
        Initialize a generalized linear model.
        i   i    N(   R   t   linalgt   matrix_rankR:   t   df_modelR   R    R0   R.   t   sumt   wnobst   df_resid(   R9   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt
   initializeD  s     c         C   sT  | d  k r t j   } n  | |  _ | d  k	 r t |  j j t j j  sZ t d   q | j	 d | j	 d k r t d   q n  | d  k	 r | j	 d | j	 d k r t d   q n  | d  k	 r| j	 d | j	 d k r t d   n  t
 | j	  d k rt d   qn  |  j d  k	 |  _ |  j d  k rWt j | j	 d  |  _ n  t j	 |  j  d
 k r|  j d k r|  j t j | j	 d  |  _ n  | d  k	 r| j	 d | j	 d k rt d   n  t
 | j	  d k rt d	   qn  | d  k	 |  _ | d  k r4t j | j	 d  |  _ n  t j |  j |  j  |  _ d  S(   Ns4   exposure can only be used with the log link functioni    s(   exposure is not the same length as endogs&   offset is not the same length as endogs)   freq weights not the same length as endogi   s$   freq weights has too many dimensionss(   var weights not the same length as endogs#   var weights has too many dimensions(    (   R    R    t   GaussianR   R!   R"   t   linkst   Logt
   ValueErrorR0   t   lenR   t   _has_freq_weightsR   t   onest   _has_var_weightsR   R*   R   (   R9   R   R   R   R.   R   R   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR-   R  s>    	'c         C   sO   t  t |   j   } d | k rK | d d  k	 rK t j | d  | d <n  | S(   NR   (   R+   R   t   _get_init_kwdsR    R   t   exp(   R9   t   kwds(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyRL     s    g      ?c         C   s%   |  j  j |  j | |  j |  j |  S(   sM   
        Evaluate the log-likelihood for a generalized linear model.
        (   R   t   loglikeR.   R   R   (   R9   R   t   scale(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt
   loglike_mu  s    c         C   sz   t  j |  j |  |  j } |  j j j |  } | d k rO |  j |  } n  |  j j	 |  j
 | |  j |  j |  } | S(   sM   
        Evaluate the log-likelihood for a generalized linear model.
        N(   R   t   dotR:   R   R   R"   t   inverseR    t   estimate_scaleRO   R.   R   R   (   R9   t   paramsRP   t   lin_predt   expvalt   llf(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyRO     s    c         C   s0   |  j  | d | } | d d  d f |  j S(   sg  score first derivative of the loglikelihood for each observation.

        Parameters
        ----------
        params : ndarray
            parameter at which score is evaluated
        scale : None or float
            If scale is None, then the default scale will be calculated.
            Default scale is defined by `self.scaletype` and set in fit.
            If scale is not None, then it is used as a fixed scale.

        Returns
        -------
        score_obs : ndarray, 2d
            The first derivative of the loglikelihood function evaluated at
            params for each observation.

        RP   N(   t   score_factorR    R:   (   R9   RU   RP   RY   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt	   score_obs  s    c         C   s(   |  j  | d | } t j | |  j  S(   sQ  score, first derivative of the loglikelihood function

        Parameters
        ----------
        params : ndarray
            parameter at which score is evaluated
        scale : None or float
            If scale is None, then the default scale will be calculated.
            Default scale is defined by `self.scaletype` and set in fit.
            If scale is not None, then it is used as a fixed scale.

        Returns
        -------
        score : ndarray_1d
            The first derivative of the loglikelihood function calculated as
            the sum of `score_obs`

        RP   (   RY   R   RR   R:   (   R9   RU   RP   RY   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   score  s    c         C   s   |  j  |  } | d k r- |  j |  } n  |  j | |  j j j |  } | |  j j |  :} | |  j |  j	 9} | d k s | | :} n  | S(   s  weights for score for each observation

        This can be considered as score residuals.

        Parameters
        ----------
        params : ndarray
            parameter at which score is evaluated
        scale : None or float
            If scale is None, then the default scale will be calculated.
            Default scale is defined by `self.scaletype` and set in fit.
            If scale is not None, then it is used as a fixed scale.

        Returns
        -------
        score_factor : ndarray_1d
            A 1d weight vector used in the calculation of the score_obs.
            The score_obs are obtained by `score_factor[:, None] * exog`

        i   N(
   t   predictR    RT   R.   R   R"   t   derivt   varianceR   R   (   R9   RU   RP   R   RY   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyRY     s     c   	      C   s  |  j  |  } | d k r- |  j |  } n  d |  j j j |  d |  j j |  } | |  j |  j 9} | s | d k s | | :} n  | S|  j	 | d d } | j
 d k s | j
 d k r t d   n  |  j j |  |  j j j |  } | |  j j j |  |  j j j |  7} | | } | |  j |  j :} | d | } | j
 d k rnt d   n  | d k s| | :} n  | S(   s  Weights for calculating Hessian

        Parameters
        ----------
        params : ndarray
            parameter at which Hessian is evaluated
        scale : None or float
            If scale is None, then the default scale will be calculated.
            Default scale is defined by `self.scaletype` and set in fit.
            If scale is not None, then it is used as a fixed scale.
        observed : bool
            If True, then the observed Hessian is returned. If false then the
            expected information matrix is returned.

        Returns
        -------
        hessian_factor : ndarray, 1d
            A 1d weight vector used in the calculation of the Hessian.
            The hessian is obtained by `(exog.T * hessian_factor).dot(exog)`
        i   i   RP   g      ?s   something wrongN(   R\   R    RT   R   R"   R]   R^   R   R   RY   t   ndimt   RuntimeErrort   deriv2(	   R9   RU   RP   t   observedR   t
   eim_factorRY   t   tmpt
   oim_factor(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   hessian_factor  s.    %,
c         C   s   | d k r6 t |  d d  d k r- t } q6 t } n  t |  d t j |  j   } |  j | d | d | } t j |  j j	 | d | j	 | j	 j
 |  j  S(   s  Hessian, second derivative of loglikelihood function

        Parameters
        ----------
        params : ndarray
            parameter at which Hessian is evaluated
        scale : None or float
            If scale is None, then the default scale will be calculated.
            Default scale is defined by `self.scaletype` and set in fit.
            If scale is not None, then it is used as a fixed scale.
        observed : bool
            If True, then the observed Hessian is returned (default).
            If false then the expected information matrix is returned.

        Returns
        -------
        hessian : ndarray
            Hessian, i.e. observed information, or expected information matrix.
        t   _optim_hessiant   eimt   _tmp_like_exogRP   Rb   t   outN(   R    t   getattrt   Falset   TrueR   t
   empty_likeR:   Rf   t   multiplyt   TRR   (   R9   RU   RP   Rb   Rd   t   factor(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   hessian&  s    		c         C   s   |  j  | d | d t S(   s,   
        Fisher information matrix.
        RP   Rb   (   Rr   Rl   (   R9   RU   RP   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   informationF  s    c         C   sK   |  j  | d t } |  j j j |  } |  j | d d  d f } | S(   sM  
        Derivative of the expected endog with respect to the parameters.

        Parameters
        ----------
        params : ndarray
            parameter at which score is evaluated

        Returns
        -------
        The value of the derivative of the expected endog with respect
        to the parameter vector.
        t   linearN(   R\   Rm   R   R"   t   inverse_derivR:   R    (   R9   RU   RV   t   idlt   dmat(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   _deriv_mean_dparamsL  s    c         C   s   |  j  |  } | d k r- |  j |  } n  d |  j j j |  } | |  j j |  :} | |  j |  j 9} | d k s | | :} n  | d d  d f |  j	 S(   s  derivative of score_obs w.r.t. endog

        Parameters
        ----------
        params : ndarray
            parameter at which score is evaluated
        scale : None or float
            If scale is None, then the default scale will be calculated.
            Default scale is defined by `self.scaletype` and set in fit.
            If scale is not None, then it is used as a fixed scale.

        Returns
        -------
        derivative : ndarray_2d
            The derivative of the score_obs with respect to endog. This
            can is given by `score_factor0[:, None] * exog` where
            `score_factor0` is the score_factor without the residual.

        i   N(
   R\   R    RT   R   R"   R]   R^   R   R   R:   (   R9   RU   RP   R   RY   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   _deriv_score_obs_dendog_  s    c         C   s\  | d k rN | d k r' t d   n  |  j |  } |  j | d | } n | d k rc d } n  t j |  j | f  } | | j d |  j j d 7} |  j |  } | d d  d f | j	 d  } |  j
 | d | }	 t j | j |	 |  } d d l m }
 | j t j j | | d d  d f   } |
 j j | |  } | | | f S(   sX  score test for restrictions or for omitted variables

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

        Parameters
        ----------
        params_constrained : array_like
            estimated parameter of the restricted model. This can be the
            parameter estimate for the current when testing for omitted
            variables.
        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.
        exog_extra : None or array_like
            Explanatory variables that are jointly tested for inclusion in the
            model, i.e. omitted variables.
        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.

        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
        -----
        not yet verified for case with scale not equal to 1.

        s:   if exog_extra is None, then k_constraintsneeds to be givenRb   i    i   Ni(   t   stats(   R    RG   R[   Rr   R   t   column_stackR:   R0   RY   R@   Rf   RR   Rp   t   scipyRz   R=   t   solvet   chi2t   sf(   R9   t   params_constrainedt   k_constraintst
   exog_extraRb   R[   Rr   t   exRY   Rf   Rz   t   chi2statt   pval(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt
   score_test  s$    +	#	/c         C   sM   | d j  | j  | d j  |  j j |  j | |  j |  j |  j   | S(   sG   
        Helper method to update history during iterative fit.
        RU   t   deviance(   R5   RU   R   R   R.   R   R   RP   (   R9   t
   tmp_resultR   t   history(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   _update_history  s    c         C   s#  |  j  sA t |  j t j t j t j f  r1 d S|  j |  Sn  t |  j  t  rc t	 j
 |  j   St |  j  t  r |  j  j   d k r |  j |  S|  j  j   d k r |  j j |  j | |  j |  j d  |  j St d |  j  t |  j   f   n" t d |  j  t |  j   f   d S(   s1  
        Estimates the dispersion/scale.

        Type of scale can be chose in the fit method.

        Parameters
        ----------
        mu : array
            mu is the mean response estimate

        Returns
        -------
        Estimate of scale

        Notes
        -----
        The default scale for Binomial, Poisson and Negative Binomial
        families is 1.  The default for the other families is Pearson's
        Chi-Square estimate.

        See Also
        --------
        statsmodels.genmod.generalized_linear_model.GLM.fit
        g      ?t   x2t   devs$   Scale %s with type %s not understoodN(   R8   R!   R   R    t   Binomialt   Poissont   NegativeBinomialt   _estimate_x2_scalet   floatR   t   arrayt   strt   lowerR   R.   R   R   RB   RG   t   type(   R9   R   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyRT     s$    	c         C   sD   t  j |  j | d  |  j } t  j | |  j j |   |  j S(   Ni   (   R   t   powerR.   R   R@   R   R^   RB   (   R9   R   t   resid(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR     s     t   brentqg)\(?g      @c            sV   | d k rF d d l  m }   f d   } | | | | d | } n t d   | S(   s2  
        Tweedie specific function to estimate scale and the variance parameter.
        The variance parameter is also referred to as p, xi, or shape.

        Parameters
        ----------
        mu : array-like
            Fitted mean response variable
        method : str, defaults to 'brentq'
            Scipy optimizer used to solve the Pearson equation. Only brentq
            currently supported.
        low : float, optional
            Low end of the bracketing interval [a,b] to be used in the search
            for the power. Defaults to 1.01.
        high : float, optional
            High end of the bracketing interval [a,b] to be used in the search
            for the power. Defaults to 5.

        Returns
        -------
        power : float
            The estimated shape or power
        R   i(   R   c            sv     j    j | d | |  j     j } t j   j    j | d | | |  d t j |     j j   S(   Ni   i   (   R   R.   R@   RB   R   R)   R   (   R   R   RP   (   R9   (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   psi_p#  s
    %t   argss!   Only brentq can currently be used(   t   scipy.optimizeR   t   NotImplementedError(   R9   R   t   methodt   lowt   highR   R   R   (    (   R9   sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   estimate_tweedie_power  s    c         C   s&  | d k r3 | d k r3 t |  d  r3 |  j } n | d k rH d } n  | d k	 r t |  j j t j j  r t	 d   n  | d k r | d k r t |  d  r |  j
 } n$ | d k r d } n t j |  } | d k r |  j } n  t j | |  | | } | r| S|  j j |  Sd S(   sw  
        Return predicted values for a design matrix

        Parameters
        ----------
        params : array-like
            Parameters / coefficients of a GLM.
        exog : array-like, optional
            Design / exogenous data. Is exog is None, model exog is used.
        exposure : array-like, optional
            Exposure time values, only can be used with the log link
            function.  See notes for details.
        offset : array-like, optional
            Offset values.  See notes for details.
        linear : bool
            If True, returns the linear predicted values.  If False,
            returns the value of the inverse of the model's link function at
            the linear predicted values.

        Returns
        -------
        An array of fitted values

        Notes
        -----
        Any `exposure` and `offset` provided here take precedence over
        the `exposure` and `offset` used in the model fit.  If `exog`
        is passed as an argument here, then any `exposure` and
        `offset` values in the fit will be ignored.

        Exposure values must be strictly positive.
        R   g        s4   exposure can only be used with the log link functionR   N(   R    R7   R   R!   R   R"   R    RE   RF   RG   R   R   R)   R:   RR   t   fitted(   R9   RU   R:   R   R   Rt   t   linpred(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR\   .  s$    $'	'	i   c   	      C   s  |  j  | | | | d t } d d l j j } t |  j t j  rd | j	 d | d t
 j |   St |  j t j  r | j d d d |  St |  j t j  r | j d	 |  St |  j t j  r | t |  } | j | d | St d
 |  j j   d S(   s=  
        Returns a random number generator for the predictive distribution.

        Parameters
        ----------
        params : array-like
            The model parameters.
        scale : scalar
            The scale parameter.
        exog : array-like
            The predictor variable matrix.

        Returns
        -------
        gen
            Frozen random number generator object.  Use the ``rvs`` method to
            generate random values.

        Notes
        -----
        Due to the behavior of ``scipy.stats.distributions objects``, the
        returned random number generator must be called with ``gen.rvs(n)``
        where ``n`` is the number of observations in the data set used
        to fit the model.  If any other value is used for ``n``, misleading
        results will be produced.
        Rt   iNt   locRP   t   ni   t   pR   s'   get_distribution not implemented for %s(   R\   Rl   t   scipy.stats.distributionsRz   t   distributionsR!   R   R    RD   t   normR   t   sqrtR   t   binomR   t   poissont   GammaR   t   gammaRG   t   name(	   R9   RU   RP   R:   R   R   t   fitt   distt   alpha(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   get_distributionn  s    c         C   s}   t  j |  j j d  |  _ t |  j t j  ry |  j j	 |  j |  j
  } | d |  _ | d |  _ |  j j d  n  d  S(   Ni    i   R   (   R   RJ   R.   R0   R   R!   R   R    R   RC   R   R4   R5   (   R9   Rd   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR6     s    id   t   IRLSg:0yE>t	   nonrobusti   c         K   s   | |  _  | j   d k rm | j   d k r6 d } n  |  j d | d | d | d | d | d	 | d
 | |  S| j d  |  _ t j |  j  |  _ |  j	 d | d | d | d | d | d |	 d |
 d | d	 | d
 | d | |  } |  ` |  ` | Sd S(   s   
        Fits a generalized linear model for a given family.

        Parameters
        ----------
        start_params : array-like, optional
            Initial guess of the solution for the loglikelihood maximization.
            The default is family-specific and is given by the
            ``family.starting_mu(endog)``. If start_params is given then the
            initial mean will be calculated as ``np.dot(exog, start_params)``.
        maxiter : int, optional
            Default is 100.
        method : string
            Default is 'IRLS' for iteratively reweighted least squares.
            Otherwise gradient optimization is used.
        tol : float
            Convergence tolerance.  Default is 1e-8.
        scale : string or float, optional
            `scale` can be 'X2', 'dev', or a float
            The default value is None, which uses `X2` for Gamma, Gaussian,
            and Inverse Gaussian.
            `X2` is Pearson's chi-square divided by `df_resid`.
            The default is 1 for the Binomial and Poisson families.
            `dev` is the deviance divided by df_resid
        cov_type : string
            The type of parameter estimate covariance matrix to compute.
        cov_kwds : dict-like
            Extra arguments for calculating the covariance of the parameter
            estimates.
        use_t : bool
            If True, the Student t-distribution is used for inference.
        full_output : bool, optional
            Set to True to have all available output in the Results object's
            mle_retvals attribute. The output is dependent on the solver.
            See LikelihoodModelResults notes section for more information.
            Not used if methhod is IRLS.
        disp : bool, optional
            Set to True to print convergence messages.  Not used if method is
            IRLS.
        max_start_irls : int
            The number of IRLS iterations used to obtain starting
            values for gradient optimization.  Only relevant if
            `method` is set to something other than 'IRLS'.
        atol : float, optional
            (available with IRLS fits) The absolute tolerance criterion that
            must be satisfied. Defaults to ``tol``. Convergence is attained
            when: :math:`rtol * prior + atol > abs(current - prior)`
        rtol : float, optional
            (available with IRLS fits) The relative tolerance criterion that
            must be satisfied. Defaults to 0 which means ``rtol`` is not used.
            Convergence is attained when:
            :math:`rtol * prior + atol > abs(current - prior)`
        tol_criterion : str, optional
            (available with IRLS fits) Defaults to ``'deviance'``. Can
            optionally be ``'params'``.
        wls_method : str, optional
            (available with IRLS fits) options are 'lstsq', 'pinv' and 'qr'
            specifies which linear algebra function to use for the irls
            optimization. Default is `lstsq` which uses the same underlying
            svd based approach as 'pinv', but is faster during iterations.
            'lstsq' and 'pinv' regularize the estimate in singular and
            near-singular cases by truncating small singular values based
            on `rcond` of the respective numpy.linalg function. 'qr' is
            only valied for cases that are not singular nor near-singular.
        optim_hessian : {'eim', 'oim'}, optional
            (available with scipy optimizer fits) When 'oim'--the default--the
            observed Hessian is used in fitting. 'eim' is the expected Hessian.
            This may provide more stable fits, but adds assumption that the
            Hessian is correctly specified.

        Notes
        -----
        If method is 'IRLS', then an additional keyword 'attach_wls' is
        available. This is currently for internal use only and might change
        in future versions. If attach_wls' is true, then the final WLS
        instance of the IRLS iteration is attached to the results instance
        as `results_wls` attribute.

        t   irlsRh   R   t   start_paramst   maxitert   tolRP   t   cov_typet   cov_kwdst   use_tt   optim_hessianR   t   full_outputt   dispt   max_start_irlsN(
   R8   R   t	   _fit_irlst   getRg   R   Rn   R:   Ri   t   _fit_gradient(   R9   R   R   R   R   RP   R   R   R   R   R   R   R;   t   fit_(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR     s*    R			t   newtonc         K   s7  |  j  } d |  _  | d k rr | d k rr |  j d | d | d | d d d d d	 d d
 d |  } | j } ~ n  t t |   j d | d | d | d | d | d | |  } | |  _  |  j | j  } |  j |  } | j	 d k r d } n | j	 | } | j
   d k rt } d } n t } y- t j j |  j | j d |  | } Wn4 t k
 rd d l m } | d t  d } n Xt |  d t  } t |  d t  } | |  | j | | d | d	 |	 d
 |
 } i d d 6} | r| j | _ d | j k r| j d | d <qn  | | _ | | _ | |  S(   s}   
        Fits a generalized linear model for a given family iteratively
        using the scipy gradient optimizers.
        g      ?i    R   R   R   RP   R   R   R   R   R   R   R   Rh   Rb   i(   R&   s8   Inverting hessian failed, no bse or cov_params availablet   _results_classt   _results_class_wrapperR   t
   iterationsN(   R8   R    R   RU   R+   R   R   R\   RT   t   normalized_cov_paramsR   Rl   Rm   R   R=   t   invRr   R
   R%   R&   R	   Rk   t
   GLMResultst   GLMResultsWrappert   mle_retvalsR   t   fit_history(   R9   R   R   R   R   R   R   RP   R   R   R   R   R;   R8   t	   irls_rsltt   rsltR   t   cov_pt   oimR&   t   results_classt   results_class_wrappert   glm_resultsR   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR     sZ    								-
			c         K   sC  | j  d t  }	 | j d  }
 | j d d  } | j d d  } | j d d  } |
 d k ri | n |
 }
 |  j } |  j } | d k r t j |  j j d	 t j	  } |  j
 j |  j  } |  j
 j |  } n+ t j | |  |  j } |  j
 j |  } |  j |  |  _ |  j
 j |  j | |  j |  j |  j  } t j |  r[t d
   n  t d t j | g d t j | g  } t } | | } | d k r|  j
 j |  } |  j |  |  _ t j |  | d  } d } n  xYt |  D]K} |  j |  j |  j
 j |  |  _ | |  j
 j j  |  |  j | |  j } t! j" | | |  j d t# d t# } | j$ d |  } t j |  j | j%  } | |  j 7} |  j
 j |  } |  j& | | |  } |  j |  |  _ | j'   j( d	 k rt j) | | d  rd } t* |   n  t+ | | d	 |
 |  } | rPqqW| |  _, | d k r| d k rcd n | } t j- | | |  j  } | j$ d |  } n  t. |  | j% | j/ |  j d | d | d | } d | _0 i  | _1 | | j1 d <| j0 | j1 d <| d k r|	 t# k r| | _2 n  | d	 | d <| | _3 | | _4 t5 |  S(   s   
        Fits a generalized linear model for a given family using
        iteratively reweighted least squares (IRLS).
        t
   attach_wlsR   R   g        t   tol_criterionR   t
   wls_methodt   lstsqi   ss   The first guess on the deviance function returned a nan.  This could be a boundary  problem and should be reported.RU   i    t   check_endogt   check_weightsR   s2   Perfect separation detected, results not availablet   pinvR   R   R   R   t	   optimizerR   N(6   t   popRl   R   R    R.   R:   R   t   zerosR0   R   R   t   starting_muR\   RR   R   R   RT   RP   R   R   R   t   isnanRG   t   dictt   inft   lmt   RegressionResultst   rangeR   R   R   R"   R]   t	   reg_toolst   _MinimalWLSRm   R   RU   R   t   squeezeR_   R   R   R   R   t   WLSR   R   R   t   mle_settingst   results_wlsR   t	   convergedR   (   R9   R   R   R   RP   R   R   R   R;   R   R   R   R   R   R.   t   wlsexogR   RV   R   R   R   R   t   wls_resultsR   t   wlsendogt   wls_modt   msgt   wls_method2t	   wls_modelR   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR   \  s    		'
	+	+								t   elastic_netg        c   	      K   s   | j  d d  d k r( |  j | |  Sd d l m } | d k rS t d   n  i d d	 6d d 6d
 d 6d
 d 6} | j |  | |  d | d | d | d | | } |  j | j  |  _ |  j	 |  j  |  _
 | S(   s  
        Return a regularized fit to a linear regression model.

        Parameters
        ----------
        method :
            Only the `elastic_net` approach is currently implemented.
        alpha : scalar or array-like
            The penalty weight.  If a scalar, the same penalty weight
            applies to all variables in the model.  If a vector, it
            must have the same length as `params`, and contains a
            penalty weight for each coefficient.
        start_params : array-like
            Starting values for `params`.
        refit : bool
            If True, the model is refit using only the variables that
            have non-zero coefficients in the regularized fit.  The
            refitted model is not regularized.

        Returns
        -------
        An array, or a GLMResults object of the same type returned by `fit`.

        Notes
        -----
        The penalty is the ``elastic net`` penalty, which is a
        combination of L1 and L2 penalties.

        The function that is minimized is:

        .. math::

            -loglike/n + alpha*((1-L1\_wt)*|params|_2^2/2 + L1\_wt*|params|_1)

        where :math:`|*|_1` and :math:`|*|_2` are the L1 and L2 norms.

        Post-estimation results are based on the same data used to
        select variables, hence may be subject to overfitting biases.

        The elastic_net method uses the following keyword arguments:

        maxiter : int
            Maximum number of iterations
        L1_wt  : float
            Must be in [0, 1].  The L1 penalty has weight L1_wt and the
            L2 penalty has weight 1 - L1_wt.
        cnvrg_tol : float
            Convergence threshold for line searches
        zero_tol : float
            Coefficients below this threshold are treated as zero.
        t   L1_wti   i    i(   t   fit_elasticnetR   s-   method for fit_regularied must be elastic_neti2   R   g|=t	   cnvrg_tolt   zero_tolR   R   R   t   refit(   R   t
   _fit_ridget   statsmodels.base.elastic_netR   RG   t   updateR\   RU   R   RT   RP   (	   R9   R   R   R   R   R;   R   t   defaultst   result(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   fit_regularized  s     6
	s	   newton-cgc            s  | d  k r( t j  j j d  } n     f d   }    f d   } d d l m } d d l m } m	 } | | | d | d | }	 |	 j
 }
 |	 j s d d  l } t j t j |	 j d	   } d
 | } | j |  n  |  |
  } | |  } | S(   Ni   c            s.    j  |    j   t j |  d  d S(   Ni   (   RO   R1   R   R@   (   t   x(   R   R9   (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   fun  s    c            s    j  |    j   |  S(   N(   R[   R1   (   R   (   R   R9   (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   grad	  s    i(   t   minimize(   t   RegularizedResultst   RegularizedResultsWrappert   jacR   i   s1   GLM ridge optimization may have failed, |grad|=%f(   R    R   R   R:   R0   R   R  R   R  R  R   t   successR%   R   R@   R  R&   (   R9   R   R   R   R  R  R  R  R  t   mrRU   R%   t   ngradR   t   results(    (   R   R9   sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR     s     		
c         K   sI  d d l  m } d d l m } | |  j  j |  } | j | j } } | |  | | d | d | \ }	 }
 } |  j d |	 d d  } |	 | j	 _
 |
 | j	 _ | j d d	  } | d	 k r |
 | j | j	 _ n d
 | j	 _ | j | j	 _ t |  } | j	 j | 7_ | j	 j | 8_ | | j	 _ | | j	 _ | | j	 _ | S(   sg  fit the model subject to linear equality constraints

        The constraints are of the form   `R params = q`
        where R is the constraint_matrix and q is the vector of
        constraint_values.

        The estimation creates a new model with transformed design matrix,
        exog, and converts the results back to the original parameterization.


        Parameters
        ----------
        constraints : formula expression or tuple
            If it is a tuple, then the constraint needs to be given by two
            arrays (constraint_matrix, constraint_value), i.e. (R, q).
            Otherwise, the constraints can be given as strings or list of
            strings.
            see t_test for details
        start_params : None or array_like
            starting values for the optimization. `start_params` needs to be
            given in the original parameter space and are internally
            transformed.
        **fit_kwds : keyword arguments
            fit_kwds are used in the optimization of the transformed model.

        Returns
        -------
        results : Results instance

        i(   t
   DesignInfo(   t   fit_constrainedR   t   fit_kwdsR   i    R   R   N(   t   patsyR  t   statsmodels.base._constraintsR  t
   exog_namest   linear_constraintt   coefst	   constantsR   t   _resultsRU   t   cov_params_defaultR   RP   R   R    RH   RB   R?   t   constraintst   k_constrt   results_constrained(   R9   R  R   R  R  R  t   lct   Rt   qRU   t   covt
   res_constrt   resR   R  (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR    s,     N($   R(   t
   __module__t   baset   _missing_param_doct   __doc__R    R,   RC   R-   RL   RQ   RO   RZ   R[   RY   Rm   Rf   Rr   Rs   Rx   Ry   R   R   RT   R   R   Rl   R\   R   R6   R   R   R   R   R   R  (    (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR   4   sT   	=		0	": 	!G		1	&	?	1	h		D		VLR   c           B   s  e  Z d  Z d d" d" d  Z e d    Z e d    Z e d    Z e d    Z	 e d    Z
 e d    Z e d	    Z e d
    Z e d    Z e d    Z e d    Z e d    Z e d    Z e d    Z e d    Z e d    Z e d    Z d" d" d" e e d" d  Z e j j e _ e d  Z e d  Z d   Z e j  j j e _ d" e d" d" d  Z! e" i d d 6e! _ d" d  Z# e$ i d d 6e# _ d d" d" d  Z% e& i d d 6e% _ d" d" d" d d  Z' d" d" d" d d  d!  Z( RS(#   sn  
    Class to contain GLM results.

    GLMResults inherits from statsmodels.LikelihoodModelResults

    Attributes
    ----------
    df_model : float
        See GLM.df_model
    df_resid : float
        See GLM.df_resid
    fit_history : dict
        Contains information about the iterations. Its keys are `iterations`,
        `deviance` and `params`.
    model : class instance
        Pointer to GLM model instance that called fit.
    nobs : float
        The number of observations n.
    normalized_cov_params : array
        See GLM docstring
    params : array
        The coefficients of the fitted model.  Note that interpretation
        of the coefficients often depends on the distribution family and the
        data.
    pvalues : array
        The two-tailed p-values for the parameters.
    scale : float
        The estimate of the scale / dispersion for the model fit.
        See GLM.fit and GLM.estimate_scale for more information.
    stand_errors : array
        The standard errors of the fitted GLM.   #TODO still named bse

    See Also
    --------
    statsmodels.base.model.LikelihoodModelResults
    R   c      	   C   so  t  t |   j | | d | d | | j |  _ | j |  _ | j j d |  _ | j |  _	 | j
 |  _ | j |  _ t |  j t j  r |  j j |  _ n	 d |  _ | j |  _ | j |  _ i  |  _ |  j j d d d d g  t |  d	 g   |  _ |  j j d
 d g  t |  d g   |  _ |  j j d  d d l m } | d  k rYt  |  _! n	 | |  _! | d k p| j"   j# d  }	 |  j j$ r|	 rd d  l% }
 d d l& m' } |
 j( d |  n  |  j j) r|	 rd d  l% }
 d d l& m' } |
 j( d |  n  | d k r7d |  _* i d d d d 6|  _+ n4 | d  k rLi  } n  | |  d | d t, d | | d  S(   NR   RP   i    i   R  t   _freq_weightst   _var_weightst	   _iweightst   data_in_cachet   nullR   t   _data_attr_modeli(   t   get_robustcov_resultsR   t   HC(   t   SpecificationWarnings.   cov_type not fully supported with freq_weightss-   cov_type not fully supported with var_weightss   Standard Errors assume that thes.    covariance matrix of the errors is correctly s
   specified.t   descriptionR   t   use_selfR   (-   R+   R   R,   R   R.   t   _endogR0   R1   R   R#  R   R$  R   R%  R!   R    R   t   modelR   t	   _n_trialsRB   R?   t   _cacheR2   R3   Rk   R&  R(  R5   t   statsmodels.base.covtypeR)  R    Rl   R   t   uppert
   startswithRI   R%   t   statsmodels.tools.sm_exceptionsR+  R&   RK   R   R   Rm   (   R9   R/  RU   R   RP   R   R   R   R)  t   ctR%   R+  (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR,     s^    			!	
	
		c         C   s   |  j  |  j |  j S(   sm   
        Respnose residuals.  The response residuals are defined as
        `endog` - `fittedvalues`
        (   R0  R.  R   (   R9   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   resid_response  s    c         C   sJ   t  j |  j  |  j |  j t  j |  j  t  j |  j j |  j   S(   s  
        Pearson residuals.  The Pearson residuals are defined as
        (`endog` - `mu`)/sqrt(VAR(`mu`)) where VAR is the distribution
        specific variance function.  See statsmodels.families.family and
        statsmodels.families.varfuncs for more information.
        (   R   R   R0  R.  R   R$  R   R^   (   R9   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   resid_pearson  s    	-c         C   s0   |  j  |  j j j |  j  } | |  j 9} | S(   s   
        Working residuals.  The working residuals are defined as
        `resid_response`/link'(`mu`).  See statsmodels.family.links for the
        derivatives of the link functions.  They are defined analytically.
        (   R7  R   R"   R]   R   R0  (   R9   t   val(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   resid_working  s    c         C   sG   d d l  } | j d d t |  j j |  j |  j d |  j d d S(   s   
        Anscombe residuals.  See statsmodels.families.family for distribution-
        specific Anscombe residuals. Currently, the unscaled residuals are
        provided. In a future version, the scaled residuals will be provided.
        iNsP   Anscombe residuals currently unscaled. In a future release, they will be scaled.t   categoryR   RP   g      ?(   R%   R&   t   FutureWarningR   t   resid_anscombeR.  t   fittedvaluesR$  (   R9   R%   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR=    s    	c         C   s+   |  j  j |  j |  j d |  j d |  j S(   s   
        Scaled Anscombe residuals.  See statsmodels.families.family for
        distribution-specific Anscombe residuals.
        R   RP   (   R   R=  R.  R>  R$  RP   (   R9   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   resid_anscombe_scaled  s    	c         C   s(   |  j  j |  j |  j d |  j d d S(   s   
        Unscaled Anscombe residuals.  See statsmodels.families.family for
        distribution-specific Anscombe residuals.
        R   RP   g      ?(   R   R=  R.  R>  R$  (   R9   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   resid_anscombe_unscaled  s    	c         C   s.   |  j  j |  j |  j d |  j d d } | S(   s}   
        Deviance residuals.  See statsmodels.families.family for distribution-
        specific deviance residuals.
        R   RP   g      ?(   R   t	   resid_devR.  R>  R$  (   R9   R   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   resid_deviance  s    		c         C   sN   |  j  |  j d |  j j |  j  } | |  j |  j 9} t j |  } | S(   sx   
        Pearson's Chi-Squared statistic is defined as the sum of the squares
        of the Pearson residuals.
        i   (   R.  R   R   R^   R%  R0  R   R@   (   R9   t   chisqt   chisqsum(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   pearson_chi2  s    'c         C   s   |  j  S(   sY   
        Linear predicted values for the fitted model.
        dot(exog, params)
        (   R   (   R9   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR>    s    c         C   s   |  j  j |  j  S(   s$   
        See GLM docstring.
        (   R/  R\   RU   (   R9   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR   #  s    c         C   s   |  j  } |  j } t j t |  d f  } | j   } | j d  t |  d  rw t | | d |  j	 | j
   j St j | | d |  j |  j } | j
   j Sd S(   s1   
        Fitted values of the null model
        i   R   R   R   N(   R.  R/  R   RJ   RH   RL   R   R7   R   R   R   R>  R   R   R%  R0  (   R9   R.   R/  R:   R;   R   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR'  *  s    		c         C   s%   |  j  j |  j |  j |  j |  j  S(   sk   
        See statsmodels.families.family for the distribution-specific deviance
        functions.
        (   R   R   R.  R   R$  R#  (   R9   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR   >  s    c         C   s%   |  j  j |  j |  j |  j |  j  S(   sc   The value of the deviance function for the model fit with a constant
        as the only regressor.(   R   R   R.  R'  R$  R#  (   R9   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   null_devianceG  s    c      	   C   s4   |  j  j |  j |  j d |  j d |  j d |  j S(   sW   
        Log-likelihood of the model fit with a constant as the only regressor
        R   R   RP   (   R   RO   R.  R'  R$  R#  RP   (   R9   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   llnullN  s    		c      	   C   s   |  j  } t |  j  t j  r t |  j  j t j j  r |  j  j j d k r t j |  j	 |  j
 d  |  j j   } | |  j j :} n	 |  j } | j |  j	 |  j
 d |  j d |  j d | } | S(   s   
        Value of the loglikelihood function evalued at params.
        See statsmodels.families.family for distribution-specific
        loglikelihoods.
        g      ?i   R   R   RP   (   R   R!   R    RD   R"   RE   t   PowerR   R   R.  R   R%  R@   R/  RA   RP   RO   R$  R#  (   R9   t   _modelfamilyRP   R9  (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyRX   X  s    	)				c         C   s   d |  j  d |  j d S(   sV   
        Akaike Information Criterion
        -2 * `llf` + 2*(`df_model` + 1)
        ii   i   (   RX   R?   (   R9   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   aicm  s    c         C   s/   |  j  |  j j |  j d t j |  j j  S(   s[   
        Bayes Information Criterion
        `deviance` - `df_resid` * log(`nobs`)
        i   (   R   R/  RA   R?   R   R)   (   R9   (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   bicu  s    c         C   s   d d  l  j j } i | d 6| d 6t d 6} | j |  d | d | d | d | }	 t | d <t j |  d | d | d | d	 |	 d
 |  j j	 j
 d | }
 |
 S(   NiR   R   Rt   R:   t	   transformt
   row_labelst	   pred_kwdsR   R"   (   t"   statsmodels.regression._predictiont
   regressionR   Rm   t   get_predictionRl   t   predt   get_prediction_glmR/  R   R"   (   R9   R:   R   R   RL  Rt   RM  R   RN  t   res_linpredR  (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyRQ    s    	
	c         C   sj   |  j  j |  j d | } t j |  d d  d f |  j  j } | t j j |  j	 j
 d  } | S(   s  
        Compute the diagonal of the hat matrix

        Parameters
        ----------
        observed : bool
            If true, then observed hessian is used in the hat matrix
            computation. If false, then the expected hessian is used.
            In the case of a canonical link function both are the same.

        Returns
        -------
        hat_matrix_diag : ndarray
            The diagonal of the hat matrix computed from the observed
            or expected hessian.
        Rb   Ni   (   R/  Rf   RU   R   R   R    R:   R=   R   Rp   R@   (   R9   Rb   R   t   wexogt   hd(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   get_hat_matrix_diag  s    )"c   	   
   C   s   d d l  m } |  j j |  j d | } t j |  } | d d  d f |  j j } | |  j j	 } |  j
 d |  } | |  d | d | d |  j d | } | S(	   s  
        Get an instance of GLMInfluence with influence and outlier measures

        Parameters
        ----------
        observed : bool
            If true, then observed hessian is used in the hat matrix
            computation. If false, then the expected hessian is used.
            In the case of a canonical link function both are the same.

        Returns
        -------
        infl : GLMInfluence instance
            The instance has methods to calculate the main influence and
            outlier measures as attributes.

        See Also
        --------
        statsmodels.stats.outliers_influence.GLMInfluence
        i(   t   GLMInfluenceRb   NR.   R:   R   t   hat_matrix_diag(   t$   statsmodels.stats.outliers_influenceRX  R/  Rf   RU   R   R   R    R:   R.   RW  R8  (	   R9   Rb   RX  R   t   weights_sqrtRU  t   wendogRY  t   infl(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   get_influence  s     		c         C   s|   |  j  j g  |  j j  D] } d | k r | ^ q  t |  j |   j   d  |  _ d  |  _ d  |  _	 d  |  _
 d  |  _ d  S(   Ns   _data.(   R2   R3   R/  R+   R'   t   remove_dataR    R.  R#  R$  R%  R0  (   R9   t   i(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR_    s    				c         C   s;   d d l  m } | |  | d | d | d | d | } | S(   Ni(   t   plot_added_variablet
   resid_typet   use_glm_weightst
   fit_kwargst   ax(   t$   statsmodels.graphics.regressionplotsRa  (   R9   t
   focus_exogRb  Rc  Rd  Re  Ra  t   fig(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyRa    s    t    t   extra_params_docc         C   s#   d d l  m } | |  | d | S(   Ni(   t   plot_partial_residualsRe  (   Rf  Rk  (   R9   Rg  Re  Rk  (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyRk    s    gQ?c         C   s,   d d l  m } | |  | | d | d | S(   Ni(   t   plot_ceres_residualst
   cond_meansRe  (   Rf  Rl  (   R9   Rg  t   fracRm  Re  Rl  (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyRl    s    g?c   	      C   s  d# d$ d |  j j j g f d |  j j j j g f d |  j g f d% d& d d	 |  j d
 g f g } d' d( d) d d |  j g f d* d d |  j g f d d |  j	 g f g } t
 |  d  r | j d |  j g f  n  | d" k r d } n  d d l m } |   } | j |  d | d | d | d | d | | j |  d | d | d | d |  j t
 |  d   r~| j d! g  n  | S(+   s  
        Summarize the Regression Results

        Parameters
        ----------
        yname : string, optional
            Default is `y`
        xname : list of strings, optional
            Default is `var_##` for ## in p the number of regressors
        title : string, optional
            Title for the top table. If not None, then this replaces the
            default title
        alpha : float
            significance level for the confidence intervals

        Returns
        -------
        smry : Summary instance
            this holds the summary tables and text, which can be printed or
            converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary.Summary : class to hold summary results
        s   Dep. Variable:s   Model:s   Model Family:s   Link Function:s   Method:s   Date:s   Time:s   No. Iterations:s   %dR   s   No. Observations:s   Df Residuals:s	   Df Model:s   Scale:s   %#8.5gs   Log-Likelihood:s	   Deviance:s   Pearson chi2:s   %#6.3gR   s   Covariance Type:s+   Generalized Linear Model Regression Resultsi(   t   Summaryt   gleftt   grightt   ynamet   xnamet   titleR   R   R  s@   Model has been estimated subject to linear equality constraints.N(   s   Dep. Variable:N(   s   Model:N(   s   Date:N(   s   Time:N(   s   No. Observations:N(   s   Df Residuals:N(   s	   Df Model:N(   s   Log-Likelihood:N(   R    R   R'   R(   R"   R   R   RP   R   RE  R7   R5   R   t   statsmodels.iolib.summaryRo  t   add_table_2colst   add_table_paramsR   t   add_extra_txt(	   R9   Rr  Rs  Rt  R   t   top_leftt	   top_rightRo  t   smry(    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   summary  s:    		
s   %.4fc         C   sv   d |  _  d d l m } | j   } | j d |  d | d | d | d | d	 |  t |  d
  rr | j d  n  | S(   s  Experimental summary for regression Results

        Parameters
        ----------
        yname : string
            Name of the dependent variable (optional)
        xname : List of strings of length equal to the number of parameters
            Names of the independent variables (optional)
        title : string, optional
            Title for the top table. If not None, then this replaces the
            default title
        alpha : float
            significance level for the confidence intervals
        float_format: string
            print format for floats in parameters summary

        Returns
        -------
        smry : Summary instance
            this holds the summary tables and text, which can be printed or
            converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary2.Summary : class to hold summary results
        R   i(   t   summary2R
  R   t   float_formatRs  Rr  Rt  R  s@   Model has been estimated subject to linear equality constraints.(   R   t   statsmodels.iolibR}  Ro  t   add_baseR7   t   add_text(   R9   Rr  Rs  Rt  R   R~  R}  R{  (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR}  J  s    	N()   R(   R  R"  R    R,   R   R7  R8  R:  R=  R?  R@  RB  RE  R>  R   R'  R   RF  RG  RX   RJ  RK  Rm   Rl   RQ  RR  RS  RW  R^  R_  R   t   LikelihoodModelResultsRa  R   Rk  R   Rl  R   R|  R}  (    (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR   ]  sT   $?

	

	#	BR   c           B   sI   e  Z i d  d 6d  d 6d  d 6d  d 6d  d 6Z e j e j j e  Z RS(   t   rowsR=  RB  R8  R7  R:  (   R(   R  t   _attrst   wrapt   union_dictsR   t   RegressionResultsWrappert   _wrap_attrs(    (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyR   r  s   
t   __main__t	   as_pandast   returnst   tablesRt  s   Test GLM(;   R"  t   numpyR   Ri  R    t   statsmodels.tools.decoratorsR   t   statsmodels.base.modelR   R/  t#   statsmodels.regression.linear_modelRP  t   linear_modelR   t   statsmodels.base.wrappert   wrapperR  t   statsmodels.regression._toolst   _toolsR   t)   statsmodels.graphics._regressionplots_docR   R   R   R   RR  t   statsmodels.genmod._predictionR   R5  R   R   R	   t   numpy.linalg.linalgR
   t   __all__R   t   LikelihoodModelR   R  R   R  R   t   populate_wrapperR(   t   statsmodels.apit   apit   smt   datasetst   longleyt   loadRl   t   dataR.   R:   R   t   GLMmodR|  t   GLMTt   GLMTp(    (    (    sJ   lib/python2.7/site-packages/statsmodels/genmod/generalized_linear_model.pyt   <module>   s@   	     .  #