o
    0GfW                     @   s   d dl mZ d dlmZ d dlZd dlmZ d dlZd dlZd dl	Z
d dlZddlmZ ddlmZmZ G dd	 d	Zd
d ZddddddddZdd Z		d-ddZd.ddZd/ddZd d! Z			d0d#d$Zd1d%d&Z			 d2d)d*Zd3d+d,ZdS )4    )FUTURE_STACK)lzipN)reduce   )SimpleTable)	fmt_latexfmt_txtc                   @   s   e Zd Zdd Zdd Zdd Zdd Zd	d
 Z		d%ddZd&ddZ	d'ddZ
dd Zd(ddZ		d)ddZdd Zd d! Zd*d#d$ZdS )+Summaryc                 C   s"   g | _ g | _g | _d | _d| _d S )NF)tablessettings	extra_txttitle_merge_latexself r   :lib/python3.10/site-packages/statsmodels/iolib/summary2.py__init__   s
   
zSummary.__init__c                 C      |   S Nas_textr   r   r   r   __str__   s   zSummary.__str__c                 C   s   t t| d |   d S )Nz
"""
z
""")strtyper   r   r   r   r   __repr__   s   zSummary.__repr__c                 C   r   )z$Display as HTML in IPython notebook.as_htmlr   r   r   r   _repr_html_      zSummary._repr_html_c                 C   r   )z9Display as LaTeX when converting IPython notebook to PDF.)as_latexr   r   r   r   _repr_latex_"   r   zSummary._repr_latex_T%.4frc                 C   s*   ||||d}| j | | j| dS )a  
        Add the contents of a DataFrame to summary table

        Parameters
        ----------
        df : DataFrame
        header : bool
            Reproduce the DataFrame column labels in summary table
        index : bool
            Reproduce the DataFrame row labels in summary table
        float_format : str
            Formatting to float data columns
        align : str
            Data alignment (l/c/r)
        indexheaderfloat_formatalignN)r
   appendr   )r   dfr%   r&   r'   r(   r   r   r   r   add_df&   s
   zSummary.add_dfc                 C   s"   t |}| j|dd||d dS )a  Add the contents of a Numpy array to summary table

        Parameters
        ----------
        array : numpy array (2D)
        float_format : str
            Formatting to array if type is float
        align : str
            Data alignment (l/c/r)
        Fr$   N)pd	DataFramer+   )r   arrayr(   r'   tabler   r   r   	add_array=   s   


zSummary.add_array   lc           	         s    fdd|  D } fdd| D }tt||}|jd | dkr?||jd |  }t|t|ddgg g}t||}tdd |}| j	||d d	S )
a  Add the contents of a Dict to summary table

        Parameters
        ----------
        d : dict
            Keys and values are automatically coerced to strings with str().
            Users are encouraged to format them before using add_dict.
        ncols : int
            Number of columns of the output table
        align : str
            Data alignment (l/c/r)
        float_format : str
            Formatting to float data columns
        c                       g | ]}t | qS r   
_formatter.0xr'   r   r   
<listcomp>]       z$Summary.add_dict.<locals>.<listcomp>c                    r3   r   r4   r6   r9   r   r   r:   ^   r;   r    c                 S   s   t | |gS r   )nphstackr8   yr   r   r   <lambda>f   s    z"Summary.add_dict.<locals>.<lambda>r(   N)
keysvaluesr=   r.   r   shapevstacksplitr   r0   )	r   dZncolsr(   r'   rC   Zvalsdatapadr   r9   r   add_dictM   s   zSummary.add_dictc                 C   s   | j | dS )zAppend a note to the bottom of the summary table. In ASCII tables,
        the note will be wrapped to table width. Notes are not indented.
        N)r   r)   )r   stringr   r   r   add_texti   s   zSummary.add_textNc                 C   sN   t |tr
|| _dS |dur"|jjj}|tv rt| }d| | _dS d| _dS )a  Insert a title on top of the summary table. If a string is provided
        in the title argument, that string is printed. If no title string is
        provided but a results instance is provided, statsmodels attempts
        to construct a useful title automatically.
        Nz	Results: r<   )
isinstancer   r   model	__class____name___model_types)r   r   resultsrO   r   r   r   	add_titleo   s   



zSummary.add_title皙?c           	      C   sd   t |||jd}t|}|dur||_|dur||d< | j|dd | j||d | j||d dS )aL  Try to construct a basic summary instance.

        Parameters
        ----------
        results : Model results instance
        alpha : float
            significance level for the confidence intervals (optional)
        float_format: str
            Float formatting for summary of parameters (optional)
        title : str
            Title of the summary table (optional)
        xname : list[str] of length equal to the number of parameters
            Names of the independent variables (optional)
        yname : str
            Name of the dependent variable (optional)
        )alphause_tNDependent Variable:r2   rB   r9   )r   rS   )summary_paramsrW   summary_modelr%   rK   r+   rT   )	r   rS   rV   r'   r   xnameynameZparaminfor   r   r   add_base   s   zSummary.add_basec                    s   | j }| j}| j}| j}t||\}}  d }t||||}dd |D }	d|	}	|	d}	||	d< |	| d|	}	|dur[|}t	| k rZdt
 d t	|d   | }nd	} fd
d|D }
dd |
D }
d|
}
d||	|
g}|S )z%Generate ASCII Summary Table
        =c                 S      g | ]}|  qS r   r   r6   r   r   r   r:          z#Summary.as_text.<locals>.<listcomp>
r   N r1   r<   c                    s   g | ]}t | qS r   )textwrapwrapr6   Zwidestr   r   r:          c                 S   s   g | ]}d  |qS )rb   )joinr6   r   r   r   r:      r;   )r
   r   r   r   _measure_tables_simple_tablesrh   rG   r)   lenint)r   r
   r   r   r   pad_col	pad_indexZ
rule_equalsimple_tablestabtxtoutr   rf   r   r      s0   



 
zSummary.as_textc                 C   sZ   | j }| j}t||}dd |D }d|}dd | jD }d|}d||g}|S )z$Generate HTML Summary Table
        c                 S   r`   r   r   r6   r   r   r   r:      ra   z#Summary.as_html.<locals>.<listcomp>rb   c                 S   s   g | ]}| d dqS )rb   <br/>
)replace)r7   str   r   r   r:      rg   rs   )r
   r   rj   rh   r   )r   r
   r   ro   rp   Ztemp_txtrq   rr   r   r   r   r      s   


zSummary.as_htmlr<   c                 C   s   | j }| j}| j}|durd| d }nd}d| d }t||}dd |D }d|}d	}| jr9t|d
|}d|||df}d|}d| j}	|d |	 }
|
S )zGenerate LaTeX Summary Table

        Parameters
        ----------
        label : str
            Label of the summary table that can be referenced
            in a latex document (optional)
        Nz	\caption{}z
\caption{}z\label{c                 S   r`   r   )Zas_latex_tabularr6   r   r   r   r:      ra   z$Summary.as_latex.<locals>.<listcomp>z

z8\\hline\n\\hline\n\\end{tabular}\n\\begin{tabular}{.*}\nz\\midrule\nz\begin{table}z\end{table}rb   z \newline 
z

\bigskip
)	r
   r   r   rj   rh   r   resubr   )r   Zlabelr
   r   r   ro   rp   Z
to_replaceZnon_captionedrq   rr   r   r   r   r       s$   	


zSummary.as_latex)TTr"   r#   )r#   r"   )r1   r2   r"   NN)rU   r"   NNN)r<   )rQ   
__module____qualname__r   r   r   r   r!   r+   r0   rK   rM   rT   r^   r   r   r    r   r   r   r   r	      s&    




%r	   c                 C   s   t | |}dd |D }dd |D }t|}g }g }tt|D ],}t| | jd d d}	t|||  |	 }
||
 || |	|
  }|||  q!||t|fS )zCompare width of ascii tables in a list and calculate padding values.
    We add space to each col_sep to get us as close as possible to the
    width of the largest table. Then, we add a few spaces to the first
    column to pad the rest.
    c                 S   r`   r   r   r6   r   r   r   r:     ra   z#_measure_tables.<locals>.<listcomp>c                 S   s   g | ]
}t | d  qS r   )rk   
splitlinesr6   r   r   r   r:     s    r   )rj   maxrangerk   rE   rl   r)   )r
   r   ro   rp   lengthZlen_maxZpad_seprn   iZnseprJ   Zlen_newr   r   r   ri      s   

ri   zOrdinary least squareszGeneralized least squaresz$Generalized least squares with AR(p)zWeighted least squareszRobust linear modelzNegative binomial modelzGeneralized linear model)ZOLSZGLSZGLSARZWLSZRLMZNBinZGLMc                 C   s  dd }i }dd |d< dd |d< dd |d	< d
d |d< ||d< dd |d< dd |d< dd |d< dd |d< dd |d< dd |d< dd |d< dd |d< dd |d< | j r]dnd }d!d |d"| d# < d$d |d%| d# < d&d |d'< d(d |d)< d*d |d+< d,d |d-< d.d |d/< d0d |d1< d2d |d3< d4d |d5< d6d |d7< d8d |d9< d:d |d;< i }| D ]\}}z|| ||< W q tttfy   Y qw |S )<z8
    Create a dict with information about the model
    c                  _   s   t j  }|dS )Nz%Y-%m-%d %H:%M)datetimenowstrftime)argskwdsr   r   r   r   time_now%  s   

zsummary_model.<locals>.time_nowc                 S   
   | j jjS r   )rO   rP   rQ   r8   r   r   r   rA   *     
 zsummary_model.<locals>.<lambda>zModel:c                 S   r   r   )familyZ__classrQ   r   r   r   r   rA   +  r   zModel Family:c                 S   s   | j jjjS r   )r   linkrP   rQ   r   r   r   r   rA   ,  s    zLink Function:c                 S   s   | j jS r   )rO   endog_namesr   r   r   r   rA   -      rX   zDate:c                 S   
   d| j  S Nz%#6d)Znobsr   r   r   r   rA   /  r   zNo. Observations:c                 S   r   r   )Zdf_modelr   r   r   r   rA   0  r   z	Df Model:c                 S   r   r   )Zdf_residr   r   r   r   rA   1  r   zDf Residuals:c                 S   
   | j d S )NZ	convergedZmle_retvalsr   r   r   r   rA   2  r   z
Converged:c                 S   r   )NZ
iterationsr   r   r   r   r   rA   3  r   zNo. Iterations:c                 S   s   | j S r   )methodr   r   r   r   rA   4  s    zMethod:c                 S   r   )NZnormZfit_optionsr   r   r   r   rA   5  r   zNorm:c                 S   r   )NZ	scale_estr   r   r   r   r   rA   6  r   zScale Est.:c                 S   r   )NZcovr   r   r   r   r   rA   7  r   z
Cov. Type:r<   z (uncentered)c                 S   r   Nz%#8.3f)rsquaredr   r   r   r   rA   :  r   	R-squared:c                 S   r   r   )rsquared_adjr   r   r   r   rA   ;  r   zAdj. R-squaredc                 S   r   r   )Z	prsquaredr   r   r   r   rA   <  r   zPseudo R-squared:c                 S   r   Nz%8.4f)Zaicr   r   r   r   rA   =  r   zAIC:c                 S   r   r   )Zbicr   r   r   r   rA   >  r   zBIC:c                 S   r   Nz%#8.5g)Zllfr   r   r   r   rA   ?  r   zLog-Likelihood:c                 S   r   r   )Zllnullr   r   r   r   rA   @  r   zLL-Null:c                 S   r   r   )Z
llr_pvaluer   r   r   r   rA   A  r   zLLR p-value:c                 S   r   r   )Zdeviancer   r   r   r   rA   B  r   z	Deviance:c                 S   r   Nz%#6.3g)Zpearson_chi2r   r   r   r   rA   C  r   zPearson chi2:c                 S   r   )Nz%#8.4g)Zfvaluer   r   r   r   rA   D  r   zF-statistic:c                 S   r   r   )Zf_pvaluer   r   r   r   rA   E  r   zProb (F-statistic):c                 S   r   r   )Zscaler   r   r   r   rA   F  r   zScale:)Z
k_constantitemsAttributeErrorKeyErrorNotImplementedError)rS   r   r]   Zrsquared_typerr   keyfuncr   r   r   rZ      sL   rZ   rU   TFr"   c              	   C   s  t | tr| \} }}}	}
}n| j}| j}| j}	| j}
| |}t|||	|
gj	}t
||g}t|}|rOdddddt|d  td|d  d g|_nddd	d
dt|d  td|d  d g|_|sz	| jjj|_W |S  ty   | jj|_Y |S w ||_|S )ax  create a summary table of parameters from results instance

    Parameters
    ----------
    res : results instance
        some required information is directly taken from the result
        instance
    yname : {str, None}
        optional name for the endogenous variable, default is "y"
    xname : {list[str], None}
        optional names for the exogenous variables, default is "var_xx"
    alpha : float
        significance level for the confidence intervals
    use_t : bool
        indicator whether the p-values are based on the Student-t
        distribution (if True) or on the normal distribution (if False)
    skip_header : bool
        If false (default), then the header row is added. If true, then no
        header row is added.
    float_format : str
        float formatting options (e.g. ".3g")

    Returns
    -------
    params_table : SimpleTable instance
    zCoef.zStd.Err.tzP>|t|[r1   r   ]zzP>|z|)rN   tupleparamsbsetvaluespvaluesconf_intr=   r.   Tr>   r,   r-   r   columnsrO   rI   Zparam_namesr%   r   Z
exog_names)rS   r\   r[   rV   rW   Zskip_headerr'   r   r   r   r   r   rI   r   r   r   rY   R  s6   


  rY   c           
         s  t | }|jdd D ]}||  fdd||< qd|jdddf  d |jdddf< |r|jdddf d	k }|j||jd
 f d |j||jd
 f< |jdddf dk }|j||jd
 f d |j||jd
 f< |jdddf dk }|j||jd
 f d |j||jd
 f< |jddddf }|jdi t}|rt| dtj	}t| dtj	}t
||d}	|	  r|	 fdd}	t
j||	gd
d}t
|}t| jjg|_|S )z<Stack coefficients and standard errors in single column
    Nr1   c                        |  S r   r   r   r9   r   r   rA     r   z_col_params.<locals>.<lambda>(r   )   g?r   *rU   g{Gz?r   r   )r   r<   )zR-squared Adj.r<   c                    r   r   r   r   r9   r   r   rA     r   )Zaxisr   )rY   r   Zapplyiloclocstackr   getattrr=   nanr,   SeriesZnotnullanyconcatr-   r   rO   r   )
resultr'   stars
include_r2rescolidxr   r   Zr2r   r9   r   _col_params  s2   ((((
r   c              	   C   s   |du ri }g }g }|D ])}t || trqz||| |  W n ty/   |d Y nw || qtjt| jj|i|d}|S )z!Stack model info in a column
    Nr<   )r%   )	rN   dictr)   r   r,   r-   r   rO   r   )r   	info_dictrr   r%   r   r   r   r   	_col_info  s   r   c                 C   sd   t t| t | kr| S ddlm} |t}g }| D ]}||  d7  < ||d ||   q|S )Nr   )defaultdictIrc   )rk   setcollectionsr   r   r)   )Zlist_of_namesr   Zname_counterr&   _namer   r   r   _make_unique  s   r   r   c                    s  t | ts| g}  fdd| D }|rt|}	n	tdd |D }	tt|D ]
}
|	|
 g||
 _q)dd }t|d j}|dd D ]}|jD ]}||vrU|| qJqEd	D ]}||v rl|| |	t|| qYt
||}||}r|jd t }|j|d
k j fddD }fddD }|| fdd|jdD }|7 |r|D ]}| q|jdd}g }|jd}td|jd d
D ]+}
|||
  |
d |jd k r||
 ||
d  kr|d q|||
d   q||_rfdd| D }ndd | D }t|tdd |D D ]	\}}|g|_q,t
||}tt||g}|j|_t|j |j  |_|}|d}t }d|_|j|ddd |d ry|d |S )a@  
    Summarize multiple results instances side-by-side (coefs and SEs)

    Parameters
    ----------
    results : statsmodels results instance or list of result instances
    float_format : str, optional
        float format for coefficients and standard errors
        Default : '%.4f'
    model_names : list[str], optional
        Must have same length as the number of results. If the names are not
        unique, a roman number will be appended to all model names
    stars : bool
        print significance stars
    info_dict : dict, default None
        dict of functions to be applied to results instances to retrieve
        model info. To use specific information for different models, add a
        (nested) info_dict with model name as the key.
        Example: `info_dict = {"N":lambda x:(x.nobs), "R2": ..., "OLS":{
        "R2":...}}` would only show `R2` for OLS regression models, but
        additionally `N` for all other results.
        Default : None (use the info_dict specified in
        result.default_model_infos, if this property exists)
    regressor_order : list[str], optional
        list of names of the regressors in the desired order. All regressors
        not specified will be appended to the end of the list.
    drop_omitted : bool, optional
        Includes regressors that are not specified in regressor_order. If
        False, regressors not specified will be appended to end of the list.
        If True, only regressors in regressor_order will be included.
    include_r2 : bool, optional
        Includes R2 and adjusted R2 in the summary table.
    c                    s   g | ]
}t | d qS ))r   r'   r   )r   r6   )r'   r   r   r   r   r:      s
    
zsummary_col.<locals>.<listcomp>c                 S      g | ]}|j d  qS r|   r   r6   r   r   r   r:     r;   c                 S   s   | j |ddddS )NZouterT)ZhowZright_indexZ
left_index)Zmerger?   r   r   r   merg  s   zsummary_col.<locals>.mergr   r   Nr   r1   c                    s   g | ]}| v r|qS r   r   r6   )varnamesr   r   r:      rg   c                       g | ]}| vr|qS r   r   r6   )regressor_orderr   r   r:   !  rg   c                    r   r   r   r6   )	new_orderr   r   r:   #  s    )levelr<   c                    s$   g | ]}t | |jjj qS r   )r   getrO   rP   rQ   r6   )r   r   r   r:   7  s
    
c                 S   s   g | ]}t |t|d dqS )Zdefault_model_infosN)r   r   r6   r   r   r   r:   :  s    c                 S   r   r|   r   )r7   r*   r   r   r   r:   =  r;   Tr2   )r&   r(   zStandard errors in parentheses.z* p<.1, ** p<.05, ***p<.01)rN   listr   r   rk   r   r%   r)   removeinsertr   ZreindexZget_level_valuestolistr,   r   Zvalue_countsr   rE   zipr-   r=   rF   ZIndexZfillnar	   r   r+   rM   )rS   r'   Zmodel_namesr   r   r   Zdrop_omittedr   ZcolsZcolnamesr   r   r%   r   r   ZspecialZsummZvcZorderedZ	unorderedotherZuor   r*   namer]   datZsmryr   )r'   r   r   r   r   r   r   r   summary_col  s   
%





&
 



r   c              	   C   s8   z	||  }W | S  t tfy   t| }Y | S w r   )
ValueError	TypeErrorr   strip)elementr'   rr   r   r   r   r5   R  s   

r5   r#   -c
                    s<  |   }
z|
 fdd}
W n ty!   |
 fdd}
Y nw |r/dd |
j D }nd }|r@fdd|
j D }nfdd|
jd d df D |
jd d df< d }tt	
|
||ttd	}||jd
 d< ||jd
 d< ||jd d< ||jd d< ||jd d< ||jd d< dt|d  |jd d< |S )Nc                    
   t |  S r   r4   r   r9   r   r   rA   _  r   z$_df_to_simpletable.<locals>.<lambda>c                    r   r   r4   r   r9   r   r   rA   a  r   c                 S   s   g | ]}t |qS r   )r   r6   r   r   r   r:   c  ra   z&_df_to_simpletable.<locals>.<listcomp>c                        g | ]}t |t d   qS rc   r   rl   r6   rn   r   r   r:   g  s     c                    r   r   r   r6   r   r   r   r:   i  s    r   )headersstubsZltx_fmtZtxt_fmtZlatexZdata_alignsZheader_alignrq   table_dec_abovetable_dec_belowheader_dec_belowrc   r   Zcolsep)copymapr   Zapplymapr   r   r%   r   r   r=   r.   r   r   Zoutput_formatsrl   )r*   r(   r'   r&   r%   r   r   r   rm   rn   r   r   r   ru   r   )r'   rn   r   _df_to_simpletableZ  s4   
r   c                 C   s   g }|r
|d d nd}|d u rdgt |  }|d u r"dgt |  }t| D ](\}}|| d }|| d }	|| d }
|t||
||	||| || d q&|S )Nr   r'   r"   r%   r&   r(   )r(   r'   r&   r%   rm   rn   )rk   	enumerater)   r   )r
   r   rm   rn   ro   r'   r   vr%   r&   r(   r   r   r   rj   x  s"   

rj   )NNrU   TFr"   )r"   TFr   )r"   r   FNr   FT)r"   )	r#   r"   TTr   Nr   r   r   ry   )Zstatsmodels.compat.pandasr   Zstatsmodels.compat.pythonr   r   	functoolsr   rw   rd   Znumpyr=   Zpandasr,   r/   r   Ztableformattingr   r   r	   ri   rR   rZ   rY   r   r   r   r   r5   r   rj   r   r   r   r   <module>   sL     m
2

=
'

z
