
    !g                     N    d Z ddlmZ ddlZddlmZ ddlmc m	Z	 	 	 	 ddZ
d Zy)z@
Authors:    Josef Perktold, Skipper Seabold, Denis A. Engemann
    )lrangeN)rainbowc           	         ddl m} t        j                  |      \  }}|xs t	        |dd      }t	        |dt        |            }| d| }|xs t	        | dd      }|xs t	        |dd      }|j                  |       |j                  |       d	x}}t        | d   t
              rUt        j                  |       D cg c]  }| }}t        t        |            }t        | t        t        ||                  }  |t        | ||
            }|j!                  ddg      j#                  |      j%                         }t        |d   j                               }|
dg|z  n|
}
|	dg|z  n|	}	|t'        |      n|}t        |
      |k7  rt)        d      t        |	      |k7  rt)        d      t        |      |k7  rt)        d      |dk(  s|dk(  rit+        |j!                  d            D ]K  \  }\  }}t        |d   j,                  d         } |j.                  |d   |d   f||   |	|   ||
|   d| M n|dk(  s|dk(  ret+        |j!                  d            D ]G  \  }\  }}t        |d   j,                  d         } |j.                  |d   |d   f||   ||
|   d| I n}|dk(  s|dk(  ret+        |j!                  d            D ]G  \  }\  }}t        |d   j,                  d         } |j0                  |d   |d   f||   ||	|   d| I nt)        d|z        |j3                  ||       |j5                  d       t7        ||g      r"|j9                  |       |j;                  |       |S c c}w )a  
    Interaction plot for factor level statistics.

    Note. If categorial factors are supplied levels will be internally
    recoded to integers. This ensures matplotlib compatibility. Uses
    a DataFrame to calculate an `aggregate` statistic for each level of the
    factor or group given by `trace`.

    Parameters
    ----------
    x : array_like
        The `x` factor levels constitute the x-axis. If a `pandas.Series` is
        given its name will be used in `xlabel` if `xlabel` is None.
    trace : array_like
        The `trace` factor levels will be drawn as lines in the plot.
        If `trace` is a `pandas.Series` its name will be used as the
        `legendtitle` if `legendtitle` is None.
    response : array_like
        The reponse or dependent variable. If a `pandas.Series` is given
        its name will be used in `ylabel` if `ylabel` is None.
    func : function
        Anything accepted by `pandas.DataFrame.aggregate`. This is applied to
        the response variable grouped by the trace levels.
    ax : axes, optional
        Matplotlib axes instance
    plottype : str {'line', 'scatter', 'both'}, optional
        The type of plot to return. Can be 'l', 's', or 'b'
    xlabel : str, optional
        Label to use for `x`. Default is 'X'. If `x` is a `pandas.Series` it
        will use the series names.
    ylabel : str, optional
        Label to use for `response`. Default is 'func of response'. If
        `response` is a `pandas.Series` it will use the series names.
    colors : list, optional
        If given, must have length == number of levels in trace.
    markers : list, optional
        If given, must have length == number of levels in trace
    linestyles : list, optional
        If given, must have length == number of levels in trace.
    legendloc : {None, str, int}
        Location passed to the legend command.
    legendtitle : {None, str}
        Title of the legend.
    **kwargs
        These will be passed to the plot command used either plot or scatter.
        If you want to control the overall plotting options, use kwargs.

    Returns
    -------
    Figure
        The figure given by `ax.figure` or a new instance.

    Examples
    --------
    >>> import numpy as np
    >>> np.random.seed(12345)
    >>> weight = np.random.randint(1,4,size=60)
    >>> duration = np.random.randint(1,3,size=60)
    >>> days = np.log(np.random.randint(1,30, size=60))
    >>> fig = interaction_plot(weight, duration, days,
    ...             colors=['red','blue'], markers=['D','^'], ms=10)
    >>> import matplotlib.pyplot as plt
    >>> plt.show()

    .. plot::

       import numpy as np
       from statsmodels.graphics.factorplots import interaction_plot
       np.random.seed(12345)
       weight = np.random.randint(1,4,size=60)
       duration = np.random.randint(1,3,size=60)
       days = np.log(np.random.randint(1,30, size=60))
       fig = interaction_plot(weight, duration, days,
                   colors=['red','blue'], markers=['D','^'], ms=10)
       import matplotlib.pyplot as plt
       #plt.show()
    r   )	DataFramenameresponse__name__z of XTraceN)xtracer   r   r   -.z(Must be a linestyle for each trace levelz%Must be a marker for each trace levelz$Must be a color for each trace levelbothb)colormarkerlabel	linestylelinel)r   r   r   scatters)r   r   r   zPlot type %s not understood)loctitleg?)pandasr   utilscreate_mpl_axgetattrstr
set_ylabel
set_xlabel
isinstancenpuniquer   len_recodedictzipgroupby	aggregatereset_indexr   
ValueError	enumeratevaluesplotr   legendmarginsall
set_xticksset_xticklabels)r   r   r   funcaxplottypexlabelylabelcolorsmarkers
linestyles	legendloclegendtitlekwargsr   figresponse_name	func_namex_valuesx_levelsr   data	plot_datan_traceir/   groupr   s                               ]/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/statsmodels/graphics/factorplots.pyinteraction_plotrL      s   d !!!"%GCCgh
CMj#d)4I{$}o.F.wq&#.F@!@KMM&MM&Hx!A$!yy|,!A,,#h-(AtC(345TAUX>?Dgs^,66t<HHJI )G$++-.G$.$6#JJ!(segogG!'WWVF
:'!CDD
7|w@AA
6{g?@@6X_"+I,=,=g,F"G 	7Ag--a01EBGGE#Jj 1 7"1:U(m7/57	7 
V	x3"+I,=,=g,F"G 	DAg--a01EBGGE#Jj 1 D:a=D<BD	D
 
Y	(c/"+I,=,=g,F"G 	>Ag--a01EBJJuSz5#4 >F1I
>6<>	> 6ABBII);I/JJrN
Hh 
h
8$Je -s   ?	M?c                    ddl m} d}d}t        | |      r$| j                  }| j                  }| j
                  } | j                  j                  t        j                  t        j                  fvrt        d      t        |t              st        d      t        j                  |       t        j                  t        |j                                     k(  j!                         st        d      t        j"                  | j$                  d   t&              }|j)                         D ]  \  }}||| |k(  <    |r ||||      }|S )	a8   Recode categorial data to int factor.

    Parameters
    ----------
    x : array_like
        array like object supporting with numpy array methods of categorially
        coded data.
    levels : dict
        mapping of labels to integer-codings

    Returns
    -------
    out : instance numpy.ndarray
    r   )SeriesNz<This is not a categorial factor. Array of str type required.z4This is not a valid value for levels. Dict required.z)The levels do not match the array values.)dtype)r   index)r   rN   r#   r   rP   r/   rO   typer$   str_object_r-   r(   r%   listkeysr3   emptyshapeintitems)r   levelsrN   r   rP   outlevelcodings           rK   r'   r'      s    DE!VvvHHww||BGGRZZ00 8 9 	9 % + , 	, iilbiiV[[](;<<AACDEE hhqwwqz-#\\^ 	%ME6$CU
O	% 4u5C
    )
meanNr   NNNNNbestN)__doc__statsmodels.compat.pythonr   numpyr$   statsmodels.graphics.plottoolsr   statsmodels.graphics.utilsgraphicsr   rL   r'    r^   rK   <module>rh      s4    -  2 * * ILDHDHRj+r^   