U
    mdV                  	   @   s   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d/d"d#Zd0d$d%Zd1d(d)Zd2d*d+ZdS )3    )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   S/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/statsmodels/iolib/summary2.py__init__   s
    zSummary.__init__c                 C   s   |   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   s   |   S )z$Display as HTML in IPython notebook.as_htmlr   r   r   r   _repr_html_   s    zSummary._repr_html_c                 C   s   |   S )z9Display as LaTeX when converting IPython notebook to PDF.)as_latexr   r   r   r   _repr_latex_!   s    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                    s   g | ]}t | qS r   
_formatter.0xr$   r   r   
<listcomp>\   s     z$Summary.add_dict.<locals>.<listcomp>c                    s   g | ]}t | qS r   r0   r2   r5   r   r   r6   ]   s     r    c                 S   s   t | |gS r   )nphstackr4   yr   r   r   <lambda>e       z"Summary.add_dict.<locals>.<lambda>r%   N)
keysvaluesr8   r+   r   shapevstacksplitr   r-   )	r   dZncolsr%   r$   r?   valsdatapadr   r5   r   add_dictL   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_texth   s    zSummary.add_textNc                 C   sJ   t |tr|| _n4|dk	r@|jjj}|tkr4t| }d| | _n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: r7   )
isinstancer   r   model	__class____name___model_types)r   r   resultsrL   r   r   r   	add_titlen   s    

zSummary.add_title皙?c           	      C   sd   t |||jd}t|}|dk	r&||_|dk	r6||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:r/   r>   r5   )r   rP   )summary_paramsrT   summary_modelr"   rH   r(   rQ   )	r   rP   rS   r$   r   xnameyname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k	r|}t	| k rdt
 d t	|d   | }nd	} fd
d|D }
dd |
D }
d|
}
d||	|
g}|S )z%Generate ASCII Summary Table
        =c                 S   s   g | ]}|  qS r   r   r2   r   r   r   r6      s     z#Summary.as_text.<locals>.<listcomp>
r   N r.   r7   c                    s   g | ]}t | qS r   )textwrapwrapr2   Zwidestr   r   r6      s     c                 S   s   g | ]}d  |qS )r^   )joinr2   r   r   r   r6      s     )r	   r
   r   r   _measure_tables_simple_tablesrc   rC   r&   lenint)r   r	   r
   r   r   pad_col	pad_indexZ
rule_equalsimple_tablestabtxtoutr   rb   r   r      s.    



"
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   s   g | ]}|  qS r   r   r2   r   r   r   r6      s     z#Summary.as_html.<locals>.<listcomp>r^   c                 S   s   g | ]}| d dqS )r^   <br/>
)replace)r3   str   r   r   r6      s     rn   )r	   r
   re   rc   r   )r   r	   r
   rj   rk   Ztemp_txtrl   rm   r   r   r   r      s    


zSummary.as_htmlr7   c                 C   s   | j }| j}| j}|dk	r(d| d }nd}d| d }t||}dd |D }d|}d	}| jrrt|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   s   g | ]}|  qS r   )Zas_latex_tabularr2   r   r   r   r6      s     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}r^   z \newline 
z

\bigskip
)	r	   r
   r   re   rc   r   resubr   )r   labelr	   r
   r   rj   rk   Z
to_replaceZnon_captionedrl   rm   r   r   r   r      s$    	


zSummary.as_latex)TTr   r    )r    r   )r.   r/   r   )NN)rR   r   NNN)r7   )rN   
__module____qualname__r   r   r   r   r   r(   r-   rH   rJ   rQ   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 ]X}t| | jd d d}	t|||  |	 }
||
 || |	|
  }|||  qB||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   s   g | ]}|  qS r   r   r2   r   r   r   r6     s     z#_measure_tables.<locals>.<listcomp>c                 S   s   g | ]}t | d  qS r   )rf   
splitlinesr2   r   r   r   r6     s     r   )re   maxrangerf   rA   rg   r&   )r	   r
   rj   rk   lengthZlen_maxZpad_sepri   iZnseprG   Zlen_newr   r   r   rd      s    

rd   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 rd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 ]8\}}z|| ||< W n tttfk
r   Y nX qv|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   s
   | j jjS r   )rL   rM   rN   r4   r   r   r   r<   )  r=   zsummary_model.<locals>.<lambda>zModel:c                 S   s
   | j jjS r   )familyZ__classrN   r   r   r   r   r<   *  r=   zModel Family:c                 S   s   | j jjjS r   )r   linkrM   rN   r   r   r   r   r<   +  r=   zLink Function:c                 S   s   | j jS r   )rL   endog_namesr   r   r   r   r<   ,  r=   rU   zDate:c                 S   s
   d| j  S Nz%#6d)Znobsr   r   r   r   r<   .  r=   zNo. Observations:c                 S   s
   d| j  S r   )Zdf_modelr   r   r   r   r<   /  r=   z	Df Model:c                 S   s
   d| j  S r   )Zdf_residr   r   r   r   r<   0  r=   zDf Residuals:c                 S   s
   | j d S )NZ	convergedZmle_retvalsr   r   r   r   r<   1  r=   z
Converged:c                 S   s
   | j d S )NZ
iterationsr   r   r   r   r   r<   2  r=   zNo. Iterations:c                 S   s   | j S r   )methodr   r   r   r   r<   3  r=   zMethod:c                 S   s
   | j d S )NZnormZfit_optionsr   r   r   r   r<   4  r=   zNorm:c                 S   s
   | j d S )NZ	scale_estr   r   r   r   r   r<   5  r=   zScale Est.:c                 S   s
   | j d S )NZcovr   r   r   r   r   r<   6  r=   z
Cov. Type:r7   z (uncentered)c                 S   s
   d| j  S Nz%#8.3f)rsquaredr   r   r   r   r<   9  r=   	R-squared:c                 S   s
   d| j  S r   )rsquared_adjr   r   r   r   r<   :  r=   zAdj. R-squaredc                 S   s
   d| j  S r   )Z	prsquaredr   r   r   r   r<   ;  r=   zPseudo R-squared:c                 S   s
   d| j  S Nz%8.4f)Zaicr   r   r   r   r<   <  r=   zAIC:c                 S   s
   d| j  S r   )Zbicr   r   r   r   r<   =  r=   zBIC:c                 S   s
   d| j  S Nz%#8.5g)Zllfr   r   r   r   r<   >  r=   zLog-Likelihood:c                 S   s
   d| j  S r   )Zllnullr   r   r   r   r<   ?  r=   zLL-Null:c                 S   s
   d| j  S r   )Z
llr_pvaluer   r   r   r   r<   @  r=   zLLR p-value:c                 S   s
   d| j  S r   )Zdeviancer   r   r   r   r<   A  r=   z	Deviance:c                 S   s
   d| j  S Nz%#6.3g)Zpearson_chi2r   r   r   r   r<   B  r=   zPearson chi2:c                 S   s
   d| j  S )Nz%#8.4g)Zfvaluer   r   r   r   r<   C  r=   zF-statistic:c                 S   s
   d| j  S r   )Zf_pvaluer   r   r   r   r<   D  r=   zProb (F-statistic):c                 S   s
   d| j  S r   )scaler   r   r   r   r<   E  r=   zScale:)Z
k_constantitemsAttributeErrorKeyErrorNotImplementedError)rP   r   r[   Zrsquared_typerm   keyfuncr   r   r   rW     sJ    
rW   rR   TFr   c              	   C   s  t | tr| \} }}}	}
}n"| j}| j}| j}	| j}
| |}t|||	|
gj	}t
||g}t|}|rdddddt|d  td|d  d g|_n.ddd	d
dt|d  td|d  d g|_|sz| jjj|_W n  tk
r   | jj|_Y nX n||_|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|[r.   r   ]zzP>|z|)rK   tupleparamsbsetvaluespvaluesconf_intr8   r+   Tr9   r)   r*   r   columnsrL   rF   Zparam_namesr"   r   Z
exog_names)rP   rY   rX   rS   rT   Zskip_headerr$   r   r   r   r   r   rF   r   r   r   rV   Q  s4    


  rV   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 }| }|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
    Nr.   c                    s    |  S r   r   r   r5   r   r   r<     r=   z_col_params.<locals>.<lambda>(r   )   g?r   *rR   g{Gz?r   r   ))r   r7   )zR-squared Adj.r7   c                    s    |  S r   r   r   r5   r   r   r<     r=   )Zaxis)rV   r   applyiloclocstackgetattrr8   nanr)   SeriesZnotnullanyconcatr*   r   rL   r   )
resultr$   stars
include_r2rescolidxr   r   r2r   r5   r   _col_params  s2    ((((
r   c              	   C   s   |dkri }g }g }|D ]T}t || tr,qz||| |  W n tk
r`   |d Y nX || qtjt| jj|i|d}|S )z!Stack model info in a column
    Nr7   )r"   )	rK   dictr&   r   r)   r*   r   rL   r   )r   	info_dictrm   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 ||   q4|S )Nr   )defaultdictIr_   )rf   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 }|r4t|}	ntdd |D }	tt|D ]}
|	|
 g||
 _qRdd }t||}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 }g }|jd}td|jd dD ]\}
|||
  |
d |jd k r||
 ||
d  kr|d n|||
d   qH||_rƇfdd| D }ndd | D }t|tdd |D D ]\}}|g|_qdd }t||}t
t||g}|j|_t
|j	 |j	  |_|}|d}t }d|_|j|ddd |d r|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   r2   )r$   r   r   r   r   r6     s   zsummary_col.<locals>.<listcomp>c                 S   s   g | ]}|j d  qS rw   r   r2   r   r   r   r6     s     c                 S   s   | j |ddddS NouterT)howZright_indexZ
left_indexmerger:   r   r   r   merg
  s    
zsummary_col.<locals>.mergr   r.   c                    s   g | ]}| kr|qS r   r   r2   )varnamesr   r   r6     s      c                    s   g | ]}| kr|qS r   r   r2   )regressor_orderr   r   r6     s      c                    s   g | ]}| kr|qS r   r   r2   )	new_orderr   r   r6     s    r   r7   c                    s$   g | ]}t | |jjj qS r   )r   getrL   rM   rN   r2   )r   r   r   r6   +  s   c                 S   s   g | ]}t |t|d dqS )Zdefault_model_infosN)r   r   r2   r   r   r   r6   .  s     c                 S   s   g | ]}|j d  qS rw   r   )r3   r'   r   r   r   r6   1  s     c                 S   s   | j |ddddS r   r   r:   r   r   r   r   4  s    
Tr/   )r#   r%   zStandard errors in parentheses.z* p<.1, ** p<.05, ***p<.01)rK   listr   rz   rf   r   r   r"   Zget_level_valuestolistr)   r   Zvalue_countsr   removerA   r&   zipr*   r8   rB   IndexZfillnar   r   r(   rJ   )rP   r$   Zmodel_namesr   r   r   Zdrop_omittedr   colsZcolnamesr|   r   ZsummvcZordered	unorderedotherZuor   r"   r'   namer[   datZsmryr   )r$   r   r   r   r   r   r   r   summary_col  sp    %



*
 



r   c              	   C   s6   z||  }W n  t tfk
r,   t| }Y nX | S r   )
ValueError	TypeErrorr   strip)elementr$   rm   r   r   r   r1   J  s
    r1   r    -c
                    s>  |   }
z|
 fdd}
W n& tk
rD   |
 fdd}
Y nX |r`dd |
j D }nd }|rfdd|
j D }n2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                    s
   t |  S r   r0   r   r5   r   r   r<   W  r=   z$_df_to_simpletable.<locals>.<lambda>c                    s
   t |  S r   r0   r   r5   r   r   r<   Y  r=   c                 S   s   g | ]}t |qS r   )r   r2   r   r   r   r6   [  s     z&_df_to_simpletable.<locals>.<listcomp>c                    s    g | ]}t |t d   qS r_   r   rg   r2   ri   r   r   r6   _  s     c                    s    g | ]}t |t d   qS r   r   r2   r   r   r   r6   a  s   r   )headersstubsZltx_fmtZtxt_fmtlatexZdata_alignsZheader_alignrl   table_dec_abovetable_dec_belowheader_dec_belowr_   r   Zcolsep)copymapr   Zapplymapr   r   r"   r   r   r8   r+   r   r   Zoutput_formatsrg   )r'   r%   r$   r#   r"   r   r   r   rh   ri   r   r   r   rp   r   )r$   ri   r   _df_to_simpletableR  s4    
 r   c                 C   s   g }|r|d d nd}|d kr.dgt |  }|d krDdgt |  }t| D ]P\}}|| d }|| d }	|| d }
|t||
||	||| || d qL|S )Nr   r$   r   r"   r#   r%   )r%   r$   r#   r"   rh   ri   )rf   	enumerater&   r   )r	   r
   rh   ri   rj   r$   r|   vr"   r#   r%   r   r   r   re   p  s$    
 
re   )NNrR   TFr   )r   TF)N)r   r   FNr   FT)r   )	r    r   TTr   Nr   r   r   )NN)Zstatsmodels.compat.pythonr   r}   	functoolsr   rr   r`   numpyr8   Zpandasr)   r,   r   Ztableformattingr   r   r   rd   rO   rW   rV   r   r   r   r   r1   r   re   r   r   r   r   <module>   sV    m
2    
=
'
       
s
           
