
    M/Phz                         d Z ddlZddlmZ ddlZddlmc m	Z
 ddlmc mZ ddlmZ ddlmZmZmZ ddlmZ dZ G d d	e          Z G d
 dee          Z G d dej                  Z e
j        ee           dS )u  
Beta regression for modeling rates and proportions.

References
----------
Grün, Bettina, Ioannis Kosmidis, and Achim Zeileis. Extended beta regression
in R: Shaken, stirred, mixed, and partitioned. No. 2011-22. Working Papers in
Economics and Statistics, 2011.

Smithson, Michael, and Jay Verkuilen. "A better lemon squeezer?
Maximum-likelihood regression with beta-distributed dependent variables."
Psychological methods 11.1 (2006): 54.
    N)gammaln)cache_readonly)GenericLikelihoodModelGenericLikelihoodModelResults	_LLRMixin)familiesa  

    Beta regression with default of logit-link for exog and log-link
    for precision.

    >>> mod = BetaModel(endog, exog)
    >>> rslt = mod.fit()
    >>> print(rslt.summary())

    We can also specify a formula and a specific structure and use the
    identity-link for precision.

    >>> from sm.families.links import identity
    >>> Z = patsy.dmatrix('~ temp', dat, return_type='dataframe')
    >>> mod = BetaModel.from_formula('iyield ~ C(batch, Treatment(10)) + temp',
    ...                              dat, exog_precision=Z,
    ...                              link_precision=identity())

    In the case of proportion-data, we may think that the precision depends on
    the number of measurements. E.g for sequence data, on the number of
    sequence reads covering a site:

    >>> Z = patsy.dmatrix('~ coverage', df)
    >>> formula = 'methylation ~ disease + age + gender + coverage'
    >>> mod = BetaModel.from_formula(formula, df, Z)
    >>> rslt = mod.fit()

c                   b    e Zd Zd                    e          Zdej                                        ej        	                                f fd	Z
ed fd	            Zd Zd dZdd	Zd!d
Zd Zd Zd Z fdZddZ	 	 d"dZd ZddZd#dZd$dZ	 	 d% fd	Zd Zd Zd!dZd!dZ xZ S )&	BetaModelaM  Beta Regression.

    The Model is parameterized by mean and precision. Both can depend on
    explanatory variables through link functions.

    Parameters
    ----------
    endog : array_like
        1d array of endogenous response variable.
    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`.
    exog_precision : array_like
        2d array of variables for the precision.
    link : link
        Any link in sm.families.links for mean, should have range in
        interval [0, 1]. Default is logit-link.
    link_precision : link
        Any link in sm.families.links for precision, should have
        range in positive line. Default is log-link.
    **kwds : extra keywords
        Keyword options that will be handled by super classes.
        Not all general keywords will be supported in this class.

    Notes
    -----
    Status: experimental, new in 0.13.
    Core results are verified, but api can change and some extra results
    specific to Beta regression are missing.

    Examples
    --------
    {example}

    See Also
    --------
    :ref:`links`

    )exampleNc                 ~   t          j        |          }t          j        d|k     |dk     z            sJ |)dg}t          j        t	          |          dfd          }n?d t          |d          r|j        nt          d|j        d         dz             D             }||d<    t                      j
        ||fd	|i| || _        || _        | j        j        d         | _        d| _        | j        d
z
  | _        | j        | j        z
  | _        t	          | j                  t	          | j                  k    sJ d| _        d	| j        vr| j                            d	g           | j                            ddg           d	g| _        |d= |                     |           t2          | _        t6          | _        d S )Nr      	precisionf)dtypec                     g | ]}d |z  S )zprecision-%s ).0zcs     \/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/othermod/betareg.py
<listcomp>z&BetaModel.__init__.<locals>.<listcomp>n   s/     I I I2>B. I I I    columnsextra_params_namesexog_precision   oimlinklink_precision)nparrayalloneslenhasattrr   rangeshapesuper__init__r   r   endognobsk_extranparamsdf_modeldf_residr   	hess_type
_init_keysextend_null_drop_keys_check_kwargsBetaResultsresults_classBetaResultsWrapperresults_class_wrapper)
selfr)   exogr   r   r   kwdsetmpextra_names	__class__s
            r   r(   zBetaModel.__init__d   s    xvq4xD1H-.....!&-KWc%jj!_C@@@NNI I&~yAAGN22!&q.*>q*AA*E!F!FI I IK
 &1!"LL^LtLLL	, J$Q'	q(	DL04&''3tz??::::4?22O""$4#5666(89::: 01%&4   (%7"""r   c                     |Gd|v r)|j         |d                  }t          j        ||          }nt          j        ||          }||d<    t                      j        ||g|R i |S )Nsubsetr   )ixpatsydmatrixr'   from_formula)	clsformuladataexog_precision_formulaargskwargsdZr=   s	           r   rC   zBetaModel.from_formula   s     "-6!!GF8,-M"8!<<M"8$??'(F#$#uww#GTCDCCCFCCCr   c                     | j         | j        fS Nr9   r   r8   s    r   
_get_exogszBetaModel._get_exogs   s    	4.//r   meanc                    |dk    rd}|dv rd}| j         j        d         }|dv rN|| j         }|d|         }t          j        ||          }|dk    r| j                            |          }|}	n|}	n|d	v rN|| j        }||d         }
t          j        ||
          }|d
k    r| j                            |          }|}	n4|}	n1|dk    r|                     |||          }	nt          d|z            |	S )a  Predict values for mean or precision

        Parameters
        ----------
        params : array_like
            The model parameters.
        exog : array_like
            Array of predictor variables for mean.
        exog_precision : array_like
            Array of predictor variables for precision parameter.
        which : str

            - "mean" : mean, conditional expectation E(endog | exog)
            - "precision" : predicted precision
            - "linear" : linear predictor for the mean function
            - "linear-precision" : linear predictor for the precision parameter

        Returns
        -------
        ndarray, predicted values
        linpredlinear)linpred_precisionlinear_precisionlinear-precisionr   )rQ   rT   NrQ   )r   rW   r   varrN   zwhich = %s is not available)
r9   r&   r   dotr   inverser   r   _predict_var
ValueError)r8   paramsr9   r   whichk_meanparams_meanrS   muresparams_preclinpred_precphis                r   predictzBetaModel.predict   sE   . IE===&E#'''|y &/KfT;//GY&&w//777%!%!4 /K6.+>>L##)11,??"e^^##- $  CC :UBCCC
r   c                     || j         }| j        j        d         }||d         }t          j        ||          }| j                            |          }|S )aG  Predict values for precision function for given exog_precision.

        Parameters
        ----------
        params : array_like
            The model parameters.
        exog_precision : array_like
            Array of predictor variables for precision.

        Returns
        -------
        Predicted precision.
        Nr   )r   r9   r&   r   rY   r   rZ   )r8   r]   r   r_   params_precisionrd   re   s          r   _predict_precisionzBetaModel._predict_precision   s[     !!0N#!&''?vn.>??!)),77
r   c                 ~    |                      ||          }|                     ||          }|d|z
  z  d|z   z  }|S )a  predict values for conditional variance V(endog | exog)

        Parameters
        ----------
        params : array_like
            The model parameters.
        exog : array_like
            Array of predictor variables for mean.
        exog_precision : array_like
            Array of predictor variables for precision.

        Returns
        -------
        Predicted conditional variance.
        r9   )r   r   )rf   ri   )r8   r]   r9   r   rQ   r   	var_endogs          r   r[   zBetaModel._predict_var   sY      ||F|..++F;I , K K	 AH%Y7	r   c                 P    |                      | j        | j        | j        |          S )a  
        Loglikelihood for observations of the Beta regressionmodel.

        Parameters
        ----------
        params : ndarray
            The parameters of the model, coefficients for linear predictors
            of the mean and of the precision function.

        Returns
        -------
        loglike : ndarray
            The log likelihood for each observation of the model evaluated
            at `params`.
        )_llobsr)   r9   r   )r8   r]   s     r   
loglikeobszBetaModel.loglikeobs
  s#      {{4:ty$2EvNNNr   c                    |||}}}|j         d         }|d|          }	|| d         }
t          j        ||	          }t          j        ||
          }| j                            |          }| j                            |          }d}t          j        ||z  |t          j                  }t          j        d|z
  |z  |t          j                  }t          |          t          |          z
  t          |          z
  ||z  dz
  t          j	        |          z  z   d|z
  |z  dz
  t          j	        d|z
            z  z   }|S )a  
        Loglikelihood for observations with data arguments.

        Parameters
        ----------
        endog : ndarray
            1d array of endogenous variable.
        exog : ndarray
            2d array of explanatory variables.
        exog_precision : ndarray
            2d array of explanatory variables for precision.
        params : ndarray
            The parameters of the model, coefficients for linear predictors
            of the mean and of the precision function.

        Returns
        -------
        loglike : ndarray
            The log likelihood for each observation of the model evaluated
            at `params`.
        r   NN~h)
r&   r   rY   r   rZ   r   clipinflgammalog)r8   r)   r9   r   r]   yXrK   nzr`   rc   rS   rd   ra   re   eps_lbalphabetalls                      r   rn   zBetaModel._llobs  s2   , ~a1WQZTrcTlbSTTl&K((va--Yw''!)),77S&"&11wB#~vrv66SkkF5MM)tcA*+ r6S.A%A67
 	r   c                     |                      |          \  }}t          j        || j                  }t          j        || j                  }t          j        ||f          S )ak  
        Returns the score vector of the log-likelihood.

        http://www.tandfonline.com/doi/pdf/10.1080/00949650903389993

        Parameters
        ----------
        params : ndarray
            Parameter at which score is evaluated.

        Returns
        -------
        score : ndarray
            First derivative of loglikelihood function.
        )score_factorr   rY   r9   r   concatenater8   r]   sf1sf2d1d2s         r   scorezBetaModel.scoreH  sV      $$V,,SVC##VC,--~r2h'''r   c                 F    t                                          |          S )zInherited score with finite differences

        Parameters
        ----------
        params : ndarray
            Parameter at which score is evaluated.

        Returns
        -------
        score based on numerical derivatives
        )r'   r   )r8   r]   r=   s     r   _score_checkzBetaModel._score_check^  s     ww}}V$$$r   c                 B   ddl m} |j        }|| j        n|}| j        | j        }}|j        d         }|d|          }	|| d         }
| j                            t          j
        ||	                    }| j                            t          j
        ||
                    }d}t          j        ||z  |t          j                  }t          j        d|z
  |z  |t          j                  }t          j        |d|z
  z            } ||          } ||          |z
  }t          j        d|z
            }| ||          z
  }d| j                            |          z  }d| j                            |          z  }||z  ||z
  z  }||||z
  z  |z   |z
  z  }||fS )aK  Derivative of loglikelihood function w.r.t. linear predictors.

        This needs to be multiplied with the exog to obtain the score_obs.

        Parameters
        ----------
        params : ndarray
            Parameter at which score is evaluated.

        Returns
        -------
        score_factor : ndarray, 2-D
            A 2d weight vector used in the calculation of the score_obs.

        Notes
        -----
        The score_obs can be obtained from score_factor ``sf`` using

            - d1 = sf[:, :1] * exog
            - d2 = sf[:, 1:2] * exog_precision

        r   specialNr   rq         ?)scipyr   psir)   r9   r   r&   r   rZ   r   rY   r   rr   rs   ru   deriv)r8   r]   r)   r   digammarv   rw   rK   rx   XparamsZparamsra   re   ry   rz   r{   ystardig_betamustarytmutthr   r   s                            r   r~   zBetaModel.score_factorl  s   . 	"!!!!!+-DJJUy$-1WQZ2#,", Yrva1122!))"&G*<*<==S&"&11wB#~vrv66qBF|$$74==(*VAE]]%$$$$**3///Ag(2(2-34Szr   FTc                   $ ddl m$ $j        }| j        | j        | j        }}}|j        d         }|d|          }	|| d         }
| j                            t          j
        ||	                    }| j                            t          j
        ||
                    }d}t          j        ||z  |t          j                  }t          j        d|z
  |z  |t          j                  }t          j        |d|z
  z            } ||          } ||          |z
  }t          j        d|z
            }| ||          z
  }d| j                            |          z  }d| j                            |          z  }||z
  }||z  |z  }|||z  |z   |z
  z  }|r$fd} ||          } ||          |z   }| ||          z
  }| }| j                            |          }| j                            |          } ||z  |z  }!|r|!||dz  z  |z  z  }!|!||z  z  }!||z  |z  ||z  |z   z  }"|r|"||z  |z  z  }"|dz  |dz  |z  d|z  |z  z   |z   z  }#|r|#||z  |z   |z
  | z  |d	z  z  z  }#||f|! |" |# ffS ||fS )
a  Derivatives of loglikelihood function w.r.t. linear predictors.

        This calculates score and hessian factors at the same time, because
        there is a large overlap in calculations.

        Parameters
        ----------
        params : ndarray
            Parameter at which score is evaluated.
        return_hessian : bool
            If False, then only score_factors are returned
            If True, the both score and hessian factors are returned
        observed : bool
            If True, then the observed Hessian is returned (default).
            If False, then the expected information matrix is returned.

        Returns
        -------
        score_factor : ndarray, 2-D
            A 2d weight vector used in the calculation of the score_obs.
        (-jbb, -jbg, -jgg) : tuple
            A tuple with 3 hessian factors, corresponding to the upper
            triangle of the Hessian matrix.
            TODO: check why there are minus
        r   r   r   Nrq   r   c                 0                         d|           S )Nr   )	polygamma)xr   s    r   <lambda>z0BetaModel.score_hessian_factor.<locals>.<lambda>  s    !2!21a!8!8 r   r      )r   r   r   r)   r9   r   r&   r   rZ   r   rY   r   rr   rs   ru   r   deriv2)%r8   r]   return_hessianobservedr   rv   rw   rK   rx   r   r   ra   re   ry   rz   r{   r   r   r   r   r   r   r   ymu_starr   r   trigamma	trig_betavar_starvar_tcsqjbbjbgjggr   s%                                       @r   score_hessian_factorzBetaModel.score_hessian_factor  s   6 	"!!!!!+*di)<a1WQZ2#,", Yrva1122!))"&G*<*<== S&"&11wB#~vrv66qBF|$$74==(*VAE]]%$$$$**3///FNAg 2=2%+, 	8888H Ix2H-EA	  $$A#**3//A7h&C +q1a4x(**1s7NC'A+h!23C (x!|a''Q$"a%(*QVaZ7%?@C =X*S0A51<<:sdSD111:r   c                     |                      |          \  }}|dddf         | j        z  }|dddf         | j        z  }t          j        ||f          S )a}  
        Score, first derivative of the loglikelihood for each observation.

        Parameters
        ----------
        params : ndarray
            Parameter at which score is evaluated.

        Returns
        -------
        score_obs : ndarray, 2d
            The first derivative of the loglikelihood function evaluated at
            params for each observation.
        N)r~   r9   r   r   column_stackr   s         r   	score_obszBetaModel.score_obs  sb     $$V,,S D\DI%D\D//Bx(((r   c                    | j         dk    rd}nd}|                     |d|          \  }}|\  }}}| j        j        |z                      | j                  }| j        j        |z                      | j                  }	| j        j        |z                      | j                  }
t          j        ||	g|	j        |
gg          S )a  Hessian, second derivative of loglikelihood function

        Parameters
        ----------
        params : ndarray
            Parameter at which Hessian is evaluated.
        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.
        eimFTr   r   )r/   r   r9   TrY   r   r   block)r8   r]   r   _hfhf11hf12hf22d11d12d22s              r   hessianzBetaModel.hessian  s      >U""HHH))&3; * = =2 dD y{T!&&ty11y{T!&&t':;;"$t+001DEEx#sceS\2333r   c                 <    |                      |d|          \  }}|S )zHDerivatives of loglikelihood function w.r.t. linear predictors.
        Tr   )r   )r8   r]   r   r   r   s        r   hessian_factorzBetaModel.hessian_factor,  s.     ))&3; * = =2	r   r   c                    ddl m}m}  ||                     | j                  | j                                                  }| j                            |j                  }| j        |z
  }|d|z
  z  t          j
        t          j        |          d          dz  z  dz
  } ||                     |          | j                                                  }	| j                            |	j                  }
t          |          D ]d}d|
z   |d|z
  z  z  }|| j                            |          dz  z  } ||                     | j                  | j        |                                          }| j                            |j                  }| j        |z
  }|d|z
  z  t          j
        t          j        |          d          dz  z  dz
  }d| j                            |
          dz  z  } ||                     |          | j        |                                          }| j                            |j                  }
t          j        |j        |j        f          }f|r|||fS |S )a  find starting values

        Parameters
        ----------
        niter : int
            Number of iterations of WLS approximation
        return_intermediate : bool
            If False (default), then only the preliminary parameter estimate
            will be returned.
            If True, then also the two results instances of the WLS estimate
            for mean parameters and for the precision parameters will be
            returned.

        Returns
        -------
        sp : ndarray
            start parameters for the optimization
        res_m2 : results instance (optional)
            Results instance for the WLS regression of the mean function.
        res_p2 : results instance (optional)
            Results instance for the WLS regression of the precision function.

        Notes
        -----
        This calculates a few iteration of weighted least squares. This is not
        a full scoring algorithm.
        r   )OLSWLSr   g{Gz?r   )weightsr   )#statsmodels.regression.linear_modelr   r   r   r)   r9   fitrZ   fittedvaluesr   maximumabsr   r   r%   r   r   r]   )r8   niterreturn_intermediater   r   res_mfittedresidprec_ires_pprec_fittedr   	y_var_invylink_var_invres_m2resid2prec_i2w_pres_p2sp2s                       r   _start_paramszBetaModel._start_params3  sp   > 	A@@@@@@@DIIdj))495599;;""5#566
V#1v:&BF5MM4)H)H!)KKaOD''//1DEEIIKK)11%2DEE u 	A 	AA[Vq6z-BCI &	(?(?(BBMS4:..	!.0 0 003 Y&&v':;;FZ&(FV,z"&..$77:;=>?Gt*00==q@@CS,,W55t7J!$& & &&)cee -55f6IJJK.&-!?@@CC 	'&&
r     bfgsc                     ||                                  }d|v r)|d                                         dk    r
d| _        |d= nd| _         t                      j        d||||d|}t          |t                    st          |          }|S )a2  
        Fit the model by maximum likelihood.

        Parameters
        ----------
        start_params : array-like
            A vector of starting values for the regression
            coefficients.  If None, a default is chosen.
        maxiter : integer
            The maximum number of iterations
        disp : bool
            Show convergence stats.
        method : str
            The optimization method to use.
        kwds :
            Keyword arguments for the optimizer.

        Returns
        -------
        BetaResults instance.
        Ncov_typer   r   )start_paramsmaxitermethoddispr   )r   lowerr/   r'   r   
isinstancer6   )r8   r   r   r   r   r:   rb   r=   s          r   r   zBetaModel.fits  s    0 --//L J%%''500!&$"DNeggk -|")&#- -'+- - #122 	*$S))C
r   c                     | j         }|                     |d          }|                    |          }| j        |dddf         z  }t	          j        |t	          j        | j        j                  f          S )ag  
        Derivative of the expected endog with respect to the parameters.

        not verified yet

        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.
        rT   r^   N)	r   rf   inverse_derivr9   r   r   zerosr   r&   )r8   r]   r   lin_predidldmats         r   _deriv_mean_dparamszBetaModel._deriv_mean_dparams  sp      y<<h<77  **y3qqq$w<'bht/B/H&I&IJKKKr   c                      ddl m}  fd} | j        dddf         |          }|ddddf          j        z  }|ddddf          j        z  }t          j        ||f          S )a#  derivative of score_obs w.r.t. endog

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

        Returns
        -------
        derivative : ndarray_2d
            The derivative of the score_obs with respect to endog.
        r   )_approx_fprime_cs_scalarc                     | j         dk    r| j        d         dk    r| d d df         }                     |           }t          j        |          S )Nr   r   r   )r)   )ndimr&   r~   r   r   )rv   sfr]   r8   s     r   r   z,BetaModel._deriv_score_obs_dendog.<locals>.f  sU    v{{qwqzQaaadG""6"33B?2&&&r   Nr   r   )statsmodels.tools.numdiffr   r)   r9   r   r   r   )r8   r]   r   r   dsfr   r   s   ``     r   _deriv_score_obs_dendogz!BetaModel._deriv_score_obs_dendog  s     	GFFFFF	' 	' 	' 	' 	' 	' '&tz!!!T'':A>>BQBZ$)#AaC[4..Bx(((r   c                 z    |                      ||          }|                      ||d          }||z  |d|z
  z  fS )a  
        Return distribution parameters converted from model prediction.

        Parameters
        ----------
        params : array_like
            The model parameters.
        exog : array_like
            Array of predictor variables for mean.
        exog_precision : array_like
            Array of predictor variables for mean.

        Returns
        -------
        (alpha, beta) : tuple of ndarrays
            Parameters for the scipy distribution to evaluate predictive
            distribution.
        rk   r   )r   r^   r   rf   )r8   r]   r9   r   rQ   r   s         r   get_distribution_paramsz!BetaModel.get_distribution_params  sQ    & ||F|..LL'2 ! 4 4	4a$h!777r   c                 V    ddl m} |                     |||          } |j        | }|S )a  
        Return a instance of the predictive distribution.

        Parameters
        ----------
        params : array_like
            The model parameters.
        exog : array_like
            Array of predictor variables for mean.
        exog_precision : array_like
            Array of predictor variables for mean.

        Returns
        -------
        Instance of a scipy frozen distribution based on estimated
        parameters.

        See Also
        --------
        predict

        Notes
        -----
        This function delegates to the predict method to handle exog and
        exog_precision, which in turn makes any required transformations.

        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.
        r   statsrN   r   r   r   r{   )r8   r]   r9   r   r   rH   distrs          r   get_distributionzBetaModel.get_distribution  sM    B 	 ++F;I , K K
D!r   rM   )NNrQ   )NN)FT)T)r   F)Nr   Fr   )!__name__
__module____qualname__format_init_example__doc__r   linksLogitLogr(   classmethodrC   rP   rf   ri   r[   ro   rn   r   r   r~   r   r   r   r   r   r   r   r   r   r   __classcell__)r=   s   @r   r
   r
   9   s<       (P 	}%%Q T 48n**,, ( 2 2 4 4$8 $8 $8 $8 $8 $8L 
D 
D 
D 
D 
D [
D0 0 0? ? ? ?B   0   .O O O$* * *X( ( (,% % % % %4 4 4 4l ;@&*S S S Sj) ) ),4 4 4 4>   > > > >@ 9>+ + + + + +ZL L L,) ) )88 8 8 80% % % % % % % %r   r
   c                       e Zd ZdZed             Zed             Zed             Zed             Zed             Z		 	 dd	Z
dd
Zd Zd ZdS )r4   zResults class for Beta regression

    This class inherits from GenericLikelihoodModelResults and not all
    inherited methods might be appropriate in this case.
    c                 @    | j                             | j                  S )z2In-sample predicted mean, conditional expectation.modelrf   r]   rO   s    r   r   zBetaResults.fittedvalues  s     z!!$+...r   c                 D    | j                             | j        d          S )zIn-sample predicted precisionr   r   r  rO   s    r   fitted_precisionzBetaResults.fitted_precision  s!     z!!$+[!AAAr   c                 *    | j         j        | j        z
  S )zResponse residual)r  r)   r   rO   s    r   r   zBetaResults.resid$  s     z$"333r   c                 |    t          j        | j                            | j        d                    }| j        |z  S )zPearson standardize residualrX   r   )r   sqrtr  rf   r]   r   )r8   stds     r   resid_pearsonzBetaResults.resid_pearson)  s7     gdj((E(BBCCzCr   c                 .    |                      d          S )zdCox-Snell Likelihood-Ratio pseudo-R-squared.

        1 - exp((llnull - .llf) * (2 / nobs))
        lr)kind)pseudo_rsquaredrO   s    r   	prsquaredzBetaResults.prsquared/  s     ###...r   NTc                 z    |                      ||          }|                      |d|          }||z  |d|z
  z  fS )ag  
        Return distribution parameters converted from model prediction.

        Parameters
        ----------
        params : array_like
            The model parameters.
        exog : array_like
            Array of predictor variables for mean.
        transform : bool
            If transform is True and formulas have been used, then predictor
            ``exog`` is passed through the formula processing. Default is True.

        Returns
        -------
        (alpha, beta) : tuple of ndarrays
            Parameters for the scipy distribution to evaluate predictive
            distribution.
        )r9   	transformr   )r   r^   r  r   r   )r8   r9   r   r  rQ   r   s         r   r   z#BetaResults.get_distribution_params7  sS    * |||;;LL'2i ! I I	4a$h!777r   c                 n    ddl m} |                     |||          }d |D             } |j        | }|S )ak  
        Return a instance of the predictive distribution.

        Parameters
        ----------
        exog : array_like
            Array of predictor variables for mean.
        exog_precision : array_like
            Array of predictor variables for mean.
        transform : bool
            If transform is True and formulas have been used, then predictor
            ``exog`` is passed through the formula processing. Default is True.

        Returns
        -------
        Instance of a scipy frozen distribution based on estimated
        parameters.

        See Also
        --------
        predict

        Notes
        -----
        This function delegates to the predict method to handle exog and
        exog_precision, which in turn makes any required transformations.

        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.
        r   r   )r9   r   r  c              3   >   K   | ]}t          j        |          V  d S rM   )r   asarray)r   args     r   	<genexpr>z/BetaResults.get_distribution.<locals>.<genexpr>w  s*      00C
3000000r   r   )r8   r9   r   r  r   rH   r   s          r   r   zBetaResults.get_distributionQ  sc    D 	 ++;I6? , A A 104000
D!r   c                 $    ddl m}  ||           S )a  
        Get an instance of MLEInfluence with influence and outlier measures

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

        See Also
        --------
        statsmodels.stats.outliers_influence.MLEInfluence

        Notes
        -----
        Support for mutli-link and multi-exog models is still experimental
        in MLEInfluence. Interface and some definitions might still change.

        Note: Difference to R betareg: Betareg has the same general leverage
        as this model. However, they use a linear approximation hat matrix
        to scale and studentize influence and residual statistics.
        MLEInfluence uses the generalized leverage as hat_matrix_diag.
        Additionally, MLEInfluence uses pearson residuals for residual
        analusis.

        References
        ----------
        todo

        r   )MLEInfluence)$statsmodels.stats.outliers_influencer!  )r8   r!  s     r   get_influencezBetaResults.get_influence{  s'    > 	FEEEEE|D!!!r   c                     t           rM   )NotImplementedError)r8   rH   rI   s      r   	bootstrapzBetaResults.bootstrap  s    !!r   )NNT)r   r   r   r  r   r   r  r   r  r  r   r   r#  r&  r   r   r   r4   r4     s          / / ^/ B B ^B 4 4 ^4     ^ 
 / / ^/ AE*.8 8 8 84( ( ( (T "  "  "D" " " " "r   r4   c                       e Zd ZdS )r6   N)r   r   r   r   r   r   r6   r6     s        Dr   r6   )r  numpyr   scipy.specialr   rt   rA   statsmodels.base.wrapperbasewrapperwrapr   
regressionlinear_modellmstatsmodels.tools.decoratorsr   statsmodels.base.modelr   r   r   statsmodels.genmodr   r  r
   r4   RegressionResultsWrapperr6   populate_wrapperr   r   r   <module>r6     s        + + + + + +  ' ' ' ' ' ' ' ' ' 0 0 0 0 0 0 0 0 0 7 7 7 7 7 7F F F F F F F F F F ' ' ' ' ' '<V V V V V& V V VrL" L" L" L" L"/ L" L" L"^	 	 	 	 	4 	 	 	  (!# # # # #r   