
    M/Pht                         d Z ddlZddlmZ ddlZ G d d          Z G d de          Z G d d	e          Z	 G d
 de          Z
ddZ	 	 	 ddZ	 	 ddZ	 	 	 ddZ	 	 	 	 	 	 	 ddZ	 	 	 ddZ	 	 ddZdS )zM
Created on Fri Dec 19 11:29:18 2014

Author: Josef Perktold
License: BSD-3

    N)statsc                   n    e Zd ZdZ	 	 ddZed             Zed             ZddZdd	Z	d
ddZ
ddZdS )PredictionResultsBasez+Based class for get_prediction results
    Nc                 :   || _         || _        || _        || _        || _        || _        | j                            |           ||dk    rt          j	        | _
        d| _        d S |dk    r t          j        | _
        | j        f| _        d S || _
        d| _        d S Nnorm t)	predictedvar_predfuncderivdf
row_labels__dict__updater   r   dist	dist_argsr
   )	selfr   r   r   r   r   r   r   kwdss	            f/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/base/_prediction_inference.py__init__zPredictionResultsBase.__init__   s    " 	
$T"""<46>>
DIDNNNS[[DI"gZDNNNDIDNNN    c                 4    t          j        | j                  S N)npsqrtr   r   s    r   sezPredictionResultsBase.se'   s    wt}%%%r   c                      | j         | j        z  S r   )r   r   r   s    r   tvalueszPredictionResultsBase.tvalues+   s    ~''r   r   	two-sidedc                 $   | j         |z
  | j        z  }|dv r. | j        j        t	          j        |          g| j        R  dz  }nI|dv r | j        j        |g| j        R  }n,|dv r | j        j        |g| j        R  }nt          d          ||fS )a0  z- or t-test for hypothesis that mean is equal to value

        Parameters
        ----------
        value : array_like
            value under the null hypothesis
        alternative : str
            'two-sided', 'larger', 'smaller'

        Returns
        -------
        stat : ndarray
            test statistic
        pvalue : ndarray
            p-value of the hypothesis test, the distribution is given by
            the attribute of the instance, specified in `__init__`. Default
            if not specified is the normal distribution.

        )r"   z2-sided2s   )largerl)smallerszinvalid alternative)	r   r   r   sfr   absr   cdf
ValueError)r   valuealternativestatpvalues        r   t_testzPredictionResultsBase.t_test/   s    * &$'1888!TY\"&,,@@@@BFFO++!TY\$8888FF,,,"TY]49$.999FF2333V|r   c                     |d} | j         j        d|dz  z
  g|R  }|||z  z
  }|||z  z   }t          j        ||f          }|S z4internal function to avoid code duplication
        Nr	             @r   ppfr   column_stack	r   centerr   alphar   qloweruppercis	            r   _conf_int_genericz'PredictionResultsBase._conf_int_genericP   f     IDIM!ebj.59555RR_eU^,, 	r   皙?r<   c                V    |                      | j        | j        || j                  }|S )aW  Confidence interval for the predicted value.

        Parameters
        ----------
        alpha : float, optional
            The significance level for the confidence interval.
            ie., The default `alpha` = .05 returns a 95% confidence interval.

        kwds : extra keyword arguments
            Ignored in base class, only for compatibility, consistent signature
            with subclasses

        Returns
        -------
        ci : ndarray, (k_constraints, 2)
            The array has the lower and the upper limit of the confidence
            interval in the columns.
        r   )rA   r   r   r   )r   r<   r   r@   s       r   conf_intzPredictionResultsBase.conf_int^   s2    ( ##DNDGU.2n $ > >	r   c                    |                      |          }i }| j        |d<   | j        |d<   |dddf         |d<   |dddf         |d<   || _        t	          j        || j        |                                	          }|S )
a\  Summary frame

        Parameters
        ----------
        alpha : float, optional
            The significance level for the confidence interval.
            ie., The default `alpha` = .05 returns a 95% confidence interval.

        Returns
        -------
        pandas DataFrame with columns 'predicted', 'se', 'ci_lower', 'ci_upper'
        rD   r   r   Nr   ci_lowerr5   ci_upperindexcolumns)rG   r   r   tablepd	DataFramer   keys)r   r<   r@   
to_includeress        r   summary_framez#PredictionResultsBase.summary_framev   s     ]]]''
"&.
;7
4!#AAAqD
:!#AAAqD
:
 l:T_#-??#4#46 6 6
r   )NNNNN)r   r"   r   rC   )__name__
__module____qualname____doc__r   propertyr   r!   r2   rA   rG   rT   r	   r   r   r   r      s          >B04       ( & & X& ( ( X(   B    !%     0     r   r   c                   *    e Zd Z	 	 ddZddZd	dZdS )
PredictionResultsMonotonicNc
                 "   || _         || _        || _        || _        || _        || _        || _        |	| _        ||dk    rt          j	        | _
        d| _        d S |dk    r t          j        | _
        | j        f| _        d S || _
        d| _        d S r   )r   r   linpred
linpred_ser   r   r   r   r   r   r   r   r
   )
r   r   r   r^   r_   r   r   r   r   r   s
             r   r   z#PredictionResultsMonotonic.__init__   s     # $	
$<46>>
DIDNNNS[[DI"gZDNNNDIDNNNr   c                     |d} | j         j        d|dz  z
  g|R  }|||z  z
  }|||z  z   }t          j        ||f          }|S r4   r7   r:   s	            r   rA   z,PredictionResultsMonotonic._conf_int_generic   rB   r   endpointrC   c                 t   t          j        ddd          }|                     |          |k                                    }|dk    r@|s>|                     | j        | j        || j                  }|                     |          }n0|dk    s|r(|                     | j        | j	        || j                  }|S )U  Confidence interval for the predicted value.

        This is currently only available for t and z tests.

        Parameters
        ----------
        method : {"endpoint", "delta"}
            Method for confidence interval, "m
            If method is "endpoint", then the confidence interval of the
            linear predictor is transformed by the prediction function.
            If method is "delta", then the delta-method is used. The confidence
            interval in this case might reach outside the range of the
            prediction, for example probabilities larger than one or smaller
            than zero.
        alpha : float, optional
            The significance level for the confidence interval.
            ie., The default `alpha` = .05 returns a 95% confidence interval.
        kwds : extra keyword arguments
            currently ignored, only for compatibility, consistent signature

        Returns
        -------
        ci : ndarray, (k_constraints, 2)
            The array has the lower and the upper limit of the confidence
            interval in the columns.
        r   r5      ra   rF   delta)
r   linspacer   allrA   r^   r_   r   r   r   )r   methodr<   r   tmp	is_linear	ci_linearr@   s           r   rG   z#PredictionResultsMonotonic.conf_int   s    6 k!Q""YYs^^s*//11	Z	..t|T_/49= / I II 9%%BBw)''26. ( B BB 	r   )NNNNNNNr   ra   rC   )rV   rW   rX   r   rA   rG   r	   r   r   r\   r\      sV        EIGK       ,   ' ' ' ' ' 'r   r\   c                   "     e Zd ZdZ fdZ xZS )PredictionResultsDeltaz-Prediction results based on delta method
    c                     |                                 }|                                } t                      j        ||fi | d S r   )r   varsuperr   )r   results_deltar   r   r   	__class__s        r   r   zPredictionResultsDelta.__init__   sL    !++--	 $$&&H5555555r   )rV   rW   rX   rY   r   __classcell__)rs   s   @r   rn   rn      sB         6 6 6 6 6 6 6 6 6r   rn   c                   p    e Zd ZdZ	 	 ddZed             Zed             Zed             Zdd	Z	dd
Z
dS )PredictionResultsMeanzPrediction results for GLM.

    This results class is used for backwards compatibility for
    `get_prediction` with GLM. The new PredictionResults classes dropped the
    `_mean` post fix in the attribute names.
    Nc	                    || _         || _        || _        || _        || _        || _        || _        ||dk    rt          j        | _	        d| _
        d S |dk    r t          j        | _	        | j        f| _
        d S || _	        d| _
        d S r   )r   r   r   	var_residr   r^   linkr   r   r   r   r
   )	r   predicted_meanvar_pred_meanrx   r   r   r   r^   ry   s	            r   r   zPredictionResultsMean.__init__   s     (%"$	<46>>
DIDNNNS[[DI"gZDNNNDIDNNNr   c                     | j         S r   )r   r   s    r   rz   z$PredictionResultsMean.predicted_mean  s     ~r   c                     | j         S r   )r   r   s    r   r{   z#PredictionResultsMean.var_pred_mean  s     }r   c                     | j         S r   )r   r   s    r   se_meanzPredictionResultsMean.se_mean  s     wr   ra   rC   c                    t          j        ddd          }| j                            |          |k                                    }|dk    r9|s7| j                            |d          }| j                            |          }n]|dk    s|rU| j        } | j        j	        d|dz  z
  g| j
        R  }	| j        |	|z  z
  }
| j        |	|z  z   }t          j        |
|f          }|S )	rc   r   r5   rd   ra   F)r<   obsre   r6   )r   rf   ry   inverserg   r^   rG   r   r   r8   r   rz   r9   )r   rh   r<   r   ri   rj   rk   r@   r   r=   r>   r?   s               r   rG   zPredictionResultsMean.conf_int  s    6 k!Q""Y&&s++s27799	Z	--Eu-EEI""9--BBw)B	a%"*n>t~>>>A'!b&0E'!b&0E%00B 	r   c                    |                      |          }i }| j        |d<   | j        |d<   |dddf         |d<   |dddf         |d<   || _        t	          j        || j        |                                	          }|S )
ao  Summary frame

        Parameters
        ----------
        alpha : float, optional
            The significance level for the confidence interval.
            ie., The default `alpha` = .05 returns a 95% confidence interval.

        Returns
        -------
        pandas DataFrame with columns
        'mean', 'mean_se', 'mean_ci_lower', 'mean_ci_upper'.
        rD   meanmean_seNr   mean_ci_lowerr5   mean_ci_upperrK   )rG   rz   r   rN   rO   rP   r   rQ   )r   r<   ci_meanrR   rS   s        r   rT   z#PredictionResultsMean.summary_frameF  s     --e-,,
!0
6 $
9&-aaadm
?#&-aaadm
?#
 l:T_#-??#4#46 6 6
r   )NNNNNNrl   rU   )rV   rW   rX   rY   r   rZ   rz   r{   r   rG   rT   r	   r   r   rv   rv      s          AEIM       *   X   X   X) ) ) )V     r   rv   Tc                 X   |rft          | j        d          rQ|Oddlm} t	          |t
          j                  rt          j        |          } || j        j        j	        |          }||"t          |dd          }t          |          rd}t          j        |          }|j        dk    r<| j        j        j        dk    s| j        j        j        d         dk    r|dddf         }t          j        |          }n)| j        j        }|t          | j        j        dd          }||fS )a,  Prepare or transform exog for prediction

    Parameters
    ----------
    exog : array_like, optional
        The values for which you want to predict.
    transform : bool, optional
        If the model was fit via a formula, do you want to pass
        exog through the formula. Default is True. E.g., if you fit
        a model y ~ log(x1) + log(x2), and transform is True, then
        you can pass a data structure that contains x1 and x2 in
        their original form. Otherwise, you'd need to log the data
        first.
    row_labels : list of str or None
        If row_lables are provided, then they will replace the generated
        labels.

    Returns
    -------
    exog : ndarray
        Prediction exog
    row_labels : list of str
        Labels or pandas index for rows of prediction
    formulaNr   )dmatrixrL   r5   r   )hasattrmodelpatsyr   
isinstancerO   SeriesrP   datadesign_infogetattrcallabler   asarrayndimexogshape
atleast_2d)r   r   	transformr   r   s        r   _get_exog_predictr   e  s6   6  :WTZ33 :8H!!!!!!dBI&& 	&<%%Dwtz2D99 w55J
## "!
z$9>>tz3q88#z4Q71<<4=D}T""z ,EEJr   c           
         t          | |||          \  }}|i } | j        j        | j        |fi |}|                                 }| j        j        j                            |j                  }	|	dz  |t          j
        ||j                  j        z                      d          z  }
| j        }| j        dk    r| j        d         }ddg| j                 }t#          ||
|| j        ||||	          S )
a  
    Compute prediction results for GLM compatible models.

    Parameters
    ----------
    exog : array_like, optional
        The values for which you want to predict.
    transform : bool, optional
        If the model was fit via a formula, do you want to pass
        exog through the formula. Default is True. E.g., if you fit
        a model y ~ log(x1) + log(x2), and transform is True, then
        you can pass a data structure that contains x1 and x2 in
        their original form. Otherwise, you'd need to log the data
        first.
    row_labels : list of str or None
        If row_lables are provided, then they will replace the generated
        labels.
    linpred : linear prediction instance
        Instance of linear prediction results used for confidence intervals
        based on endpoint transformation.
    link : instance of link function
        If no link function is provided, then the `model.family.link` is used.
    pred_kwds : dict
        Some models can take additional keyword arguments, such as offset or
        additional exog in multi-part models. See the predict method of the
        model for the details.

    Returns
    -------
    prediction_results : generalized_linear_model.PredictionResults
        The prediction results instance contains prediction and prediction
        variance and can on demand calculate confidence intervals and summary
        tables for the prediction of the mean and of new observations.
    r   r   r   Nr%   r5   zfixed scalescaler   r
   )r   r   r   r^   ry   )r   r   predictparams
cov_paramsfamilyry   inverse_derivrz   r   dotTsumr   cov_typecov_kwdsuse_trv   df_resid)r   r   r   r   r^   ry   	pred_kwdsrz   covb
link_derivr{   rx   r   s                r   get_prediction_glmr     s   N )	
 
 
D* 	'TZ'TGGYGGN??D"'55g6LMMJMTBF4,@,@,B%B$G$G$J$JJM
I }%%M'*	C=$D y=twT; ; ; ;r   c                    t          | |||          \  }}|i }|j        d         }t          | j        |k              rt	          j        |          }nd}|                     |          }|t	          j        ||j                  j        z  	                    d          }|
                                }	d|	d<    | j        j        | j        |fi |	}
ddg| j                 }t          |
|| j        ||	          }|S )
a  
    Compute prediction results for linear prediction.

    Parameters
    ----------
    exog : array_like, optional
        The values for which you want to predict.
    transform : bool, optional
        If the model was fit via a formula, do you want to pass
        exog through the formula. Default is True. E.g., if you fit
        a model y ~ log(x1) + log(x2), and transform is True, then
        you can pass a data structure that contains x1 and x2 in
        their original form. Otherwise, you'd need to log the data
        first.
    row_labels : list of str or None
        If row_lables are provided, then they will replace the generated
        labels.
    pred_kwargs :
        Some models can take additional keyword arguments, such as offset or
        additional exog in multi-part models.
        See the predict method of the model for the details.
    index : slice or array-index
        Is used to select rows and columns of cov_params, if the prediction
        function only depends on a subset of parameters.

    Returns
    -------
    prediction_results : PredictionResults
        The prediction results instance contains prediction and prediction
        variance and can on demand calculate confidence intervals and summary
        tables for the prediction.
    r   Nr5   columnlinearwhichr   r
   )r   r   r   )r   r   lenr   r   aranger   r   r   r   copyr   r   r   r   r   )r   r   r   r   r   rL   k1r   r   pred_kwds_linearr   r   rS   s                r   get_prediction_linearr     s   H )	
 
 
D* 		AB
4; 	"??%?((DrvdDF++--22155H ~~'' (W"
"4;II8HIIIC=$D
	8#'=t+5" " "C Jr   c                 F   t          | |||          \  }}|i }|| j        j        j        }|j        }|                     |          }|t          j        ||j                  j        z  	                    d          }	|
                                }
d|
d<    | j        j        | j        |fi |
} | j        j        | j        |fi |} ||          }|dz  |	z  }dd	g| j                 }t          ||| j        |||t          j        |	          |j        |
	  	        }|S )a  
    Compute prediction results when endpoint transformation is valid.

    Parameters
    ----------
    exog : array_like, optional
        The values for which you want to predict.
    transform : bool, optional
        If the model was fit via a formula, do you want to pass
        exog through the formula. Default is True. E.g., if you fit
        a model y ~ log(x1) + log(x2), and transform is True, then
        you can pass a data structure that contains x1 and x2 in
        their original form. Otherwise, you'd need to log the data
        first.
    row_labels : list of str or None
        If row_lables are provided, then they will replace the generated
        labels.
    link : instance of link function
        If no link function is provided, then the ``mmodel.family.link` is
        used.
    pred_kwargs :
        Some models can take additional keyword arguments, such as offset or
        additional exog in multi-part models.
        See the predict method of the model for the details.
    index : slice or array-index
        Is used to select rows and columns of cov_params, if the prediction
        function only depends on a subset of parameters.

    Returns
    -------
    prediction_results : PredictionResults
        The prediction results instance contains prediction and prediction
        variance and can on demand calculate confidence intervals and summary
        tables for the prediction.
    r   Nr   r5   r   r   r%   r   r
   )r   r   r   r^   r_   r   r   )r   r   r   ry   r   r   r   r   r   r   r   r   r   r   r\   r   r   r   )r   r   r   r   ry   r   rL   
func_derivr   linpred_varr   r^   r   r   r   r   rS   s                    r   get_prediction_monotonicr   !  sZ   P )	
 
 
D* 	|z %#J ??%?((D"&tv..0055a88K ~~'' (W dj dGG6FGGG"
"4;BB	BBIG$$J1}{*HC=$D
$Y(,D0:G020D0D*.,j	J J JC
 Jr   r   Fc                      t           ||          \  }t          j        d           fd}                     |          }	t	          |	          }
|
S )a  
    compute prediction results

    Parameters
    ----------
    exog : array_like, optional
        The values for which you want to predict.
    which : str
        The statistic that is prediction. Which statistics are available
        depends on the model.predict method.
    average : bool
        If average is True, then the mean prediction is computed, that is,
        predictions are computed for individual exog and then them mean over
        observation is used.
        If average is False, then the results are the predictions for all
        observations, i.e. same length as ``exog``.
    agg_weights : ndarray, optional
        Aggregation weights, only used if average is True.
        The weights are not normalized.
    transform : bool, optional
        If the model was fit via a formula, do you want to pass
        exog through the formula. Default is True. E.g., if you fit
        a model y ~ log(x1) + log(x2), and transform is True, then
        you can pass a data structure that contains x1 and x2 in
        their original form. Otherwise, you'd need to log the data
        first.
    row_labels : list of str or None
        If row_lables are provided, then they will replace the generated
        labels.
    pred_kwargs :
        Some models can take additional keyword arguments, such as offset or
        additional exog in multi-part models.
        See the predict method of the model for the details.

    Returns
    -------
    prediction_results : generalized_linear_model.PredictionResults
        The prediction results instance contains prediction and prediction
        variance and can on demand calculate confidence intervals and summary
        tables for the prediction of the mean and of new observations.
    r   Ng      ?c                      j         j        | fdi}r'|j        j        z                      d          j        }|S )z2Prediction function as function of params
        r   )r   r   r   r   )ppredagg_weightsaverager   r   r   r   s     r   f_predz$get_prediction_delta.<locals>.f_pred  sT     "tz!!TDDD)DD 	7F[]*00446Dr   )r   r   array_get_wald_nonlinearrn   )r   r   r   r   r   r   r   r   r   nlpmrS   s   `````  `   r   get_prediction_deltar   l  s    j )	
 
 
D* hrll          ##F++D
 
&
&CJr   c           	      n   t          | j        dd          }|dk    rt          | ||||          }	n|dk    r|du r|du r| j        j        j        d         }
t          | j        |
k              rt          j        |
          }nd}||d	<   t          | j        d
d          }|0t          | j        d          rt          | j        j
        d
d          }|3ddl}|                    d           ddlm} |                                }t!          | ||||||          }	nt#          | |||||          }	|	S )a8  
    Compute prediction results when endpoint transformation is valid.

    Parameters
    ----------
    exog : array_like, optional
        The values for which you want to predict.
    transform : bool, optional
        If the model was fit via a formula, do you want to pass
        exog through the formula. Default is True. E.g., if you fit
        a model y ~ log(x1) + log(x2), and transform is True, then
        you can pass a data structure that contains x1 and x2 in
        their original form. Otherwise, you'd need to log the data
        first.
    which : str
        Which statistic is to be predicted. Default is "mean".
        The available statistics and options depend on the model.
        see the model.predict docstring
    linear : bool
        Linear has been replaced by the `which` keyword and will be
        deprecated.
        If linear is True, then `which` is ignored and the linear
        prediction is returned.
    row_labels : list of str or None
        If row_lables are provided, then they will replace the generated
        labels.
    average : bool
        If average is True, then the mean prediction is computed, that is,
        predictions are computed for individual exog and then the average
        over observation is used.
        If average is False, then the results are the predictions for all
        observations, i.e. same length as ``exog``.
    agg_weights : ndarray, optional
        Aggregation weights, only used if average is True.
        The weights are not normalized.
    **kwargs :
        Some models can take additional keyword arguments, such as offset,
        exposure or additional exog in multi-part models like zero inflated
        models.
        See the predict method of the model for the details.

    Returns
    -------
    prediction_results : PredictionResults
        The prediction results instance contains prediction and prediction
        variance and can on demand calculate confidence intervals and
        summary dataframe for the prediction.

    Notes
    -----
    Status: new in 0.14, experimental
    _use_endpointTr   )r   r   r   r   r   Fr5   Nr   ry   r   r   z(using default log-link in get_predictionlinks)r   r   r   ry   r   rL   )r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   warningswarnstatsmodels.genmod.familiesr   Logr   r   )r   r   r   r   r   r   r   r   use_endpointrS   r   rL   ry   r   r   s                  r   get_predictionr     s   n 4:==L#!   6//|t33'U:J:JZ_"1%t{R   	IbMMEEE"	'tz6400<tz8,, @tz0&$??<OOOMMDEEE99999999;;D&!   ##   Jr   c                    ddl m} |||                                }|t          | d          r| j        }t          j        |           } |                    |           }|                    |           }|dz  t          j	        |          z  }t          j        }	t          | t          j	        |          |	||                                          }
t          |||	||
|          }|S )aI  
    results for univariate, nonlinear, monotonicaly transformed parameters

    This provides transformed values, standard errors and confidence interval
    for transformations of parameters, for example in calculating rates with
    `exp(params)` in the case of Poisson or other models with exponential
    mean function.
    r   r   NrL   r%   )r   r   ry   )r   r   r^   ry   )r   r   r   r   rL   r   r   r   r   diagr   r   rv   Identity)r   r   ry   r   r   r   rz   r   r{   r   r^   rS   s               r   params_transform_univariater   )  s     211111|	)yy{{gfg66\
ZF\\&))N##F++JMBGJ$7$77M :D $
##$ENN$4$46 6 6G  DwT; ; ;C Jr   )NTN)NTNNNN)NTNNN)Nr   FNTNN)NTr   NFNN)NNN)rY   numpyr   scipyr   pandasrO   r   r\   rn   rv   r   r   r   r   r   r   r   r	   r   r   <module>r      s                 A A A A A A A AHM M M M M!6 M M M`	6 	6 	6 	6 	62 	6 	6 	6s s s s s1 s s sl1 1 1 1h 37;?!%B; B; B; B;J 6:AE@ @ @ @F 9=3737H H H HZ J J J JZ ;A?C!m m m m` JN+/$ $ $ $ $ $r   