
    M/Ph^G                         d Z ddlmZmZ ddlZddlZddlm	c m
Z ddlmZmZ ddZdd
Zd Zd Z G d d          Z G d de          Zd Zd Zd Z G d d          ZdS )a  Tools for working with groups

This provides several functions to work with groups and a Group class that
keeps track of the different representations and has methods to work more
easily with groups.


Author: Josef Perktold,
Author: Nathaniel Smith, recipe for sparse_dummies on scipy user mailing list

Created on Tue Nov 29 15:44:53 2011 : sparse_dummies
Created on Wed Nov 30 14:28:24 2011 : combine_indices
changes: add Group class

Notes
~~~~~

This reverses the class I used before, where the class was for the data and
the group was auxiliary. Here, it is only the group, no data is kept.

sparse_dummies needs checking for corner cases, e.g.
what if a category level has zero elements? This can happen with subset
    selection even if the original groups where defined as arange.

Not all methods and options have been tried out yet after refactoring

need more efficient loop if groups are sorted -> see GroupSorted.group_iter
    )lrangelzipN)Index
MultiIndex .Fc                 ,   t          | t                    rt          j        |           } nt          j        |           } | j        }| j        dk    }|r[| j        d         }| j        j	        st          j
        | d          } |                     d| j        fg| j        d         z            }n| }t          j        |dd          \  }}	|r)                    |                              d|          |rfd	D             }
|	||
fS |	|fS )
zIuse np.unique to get integer group indices for product, intersection
          C)orderr   T)return_indexreturn_inversec           
          g | ]A}                     d gt          d                   z            z   t          |          z  BS %sr   joinlentuple.0iiprefixsepunis     \/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tools/grouputils.py
<listcomp>z#combine_indices.<locals>.<listcomp>H   sV           4&SV"4555rB          )
isinstancer   npcolumn_stackasarraydtypendimshapeflagsc_contiguousarrayviewuniquereshape)groupsr   r   return_labelsdtis2dncolsgroups_uni_idxuni_invlabelr   s    ``        @r   combine_indicesr7   %   sR    &%   $((F##	BK1D Q|( 	1XfC000F++FL12V\!_DEEIgD59; ; ;C'  .hhrll""2u--  %                e++$$r    Tc                     t          j                    t          j                                                   j        dk    r dddf          n j        dk    r|rt	          d          |ryt          j                  d j        d         z  k    rt          j                  d         t          j	         fdt           j        d                   D                       S t          j                  }t          j        t          |          gt           j        dd                   z             }t          |          D ]'\  }} |k                                 d          ||<   (|S )zsimple bincount version, again

    group : ndarray, integer
        assumed to be consecutive integers

    no dtype checking because I want to raise in that case

    uses loop over columns of x

    for comparison, simple python loop
    r   Nr
   znot implemented yetr   c                 P    g | ]"}t          j        d d |f                   #S )N)weights)r"   bincount)r   colgroupxs     r   r   zgroup_sums.<locals>.<listcomp>j   sD        E1QQQV9555  r    )r"   r$   squeezer&   
ValueErrormaxr'   pd	factorizer*   ranger,   zerosr   list	enumeratesum)r>   r=   use_bincountuniquesresultr   cats   ``     r   
group_sumsrM   P   sr    	
1AJu%%''Ev{{aaagJ	
!.///  6%==1qwqz>))L''*Ex     ,,  
 
 	
 )E""3w<<.4+<+<<== )) 	0 	0GB5C<,,Q//F2JJr    c                 t    t          j        |d          rt          j        | j        |          S | j        |z  S )zesum by groups given group dummy variable

    group_dummy can be either ndarray or sparse matrix
    N)	data_util_is_using_ndarray_typer"   dotT)r>   group_dummys     r   group_sums_dummyrT   w   s:    
 'T:: !vac;'''s[  r    c                     ddl m} t          j        t	          |           dz             }t          j        t	          |           t          j                  }|                    || |f          }|S )aH  create a sparse indicator from a group array with integer labels

    Parameters
    ----------
    groups : ndarray, int, 1d (nobs,)
        an array of group indicators for each observation. Group levels are
        assumed to be defined as consecutive integers, i.e. range(n_groups)
        where n_groups is the number of group levels. A group level with no
        observations for it will still produce a column of zeros.

    Returns
    -------
    indi : ndarray, int8, 2d (nobs, n_groups)
        an indicator array with one row per observation, that has 1 in the
        column of the group level for that observation

    Examples
    --------

    >>> g = np.array([0, 0, 2, 1, 1, 2, 0])
    >>> indi = dummy_sparse(g)
    >>> indi
    <7x3 sparse matrix of type '<type 'numpy.int8'>'
        with 7 stored elements in Compressed Sparse Row format>
    >>> indi.todense()
    matrix([[1, 0, 0],
            [1, 0, 0],
            [0, 0, 1],
            [0, 1, 0],
            [0, 1, 0],
            [0, 0, 1],
            [1, 0, 0]], dtype=int8)


    current behavior with missing groups
    >>> g = np.array([0, 0, 2, 0, 2, 0])
    >>> indi = dummy_sparse(g)
    >>> indi.todense()
    matrix([[1, 0, 0],
            [1, 0, 0],
            [0, 0, 1],
            [1, 0, 0],
            [0, 0, 1],
            [1, 0, 0]], dtype=int8)
    r   )sparser   )r%   )scipyrV   r"   aranger   onesint8
csr_matrix)r.   rV   indptrdataindis        r   dummy_sparser_      sk    \ Ys6{{1}%%F73v;;bg...DdFF344DKr    c                   F    e Zd ZddZd Zd ZddefdZd Zdd
Z	ddZ
dS )Groupr   c                     || _         t          |          \  }}}|||c| _        | _        | _        t          | j                  | _        d| _        | j         | _        | j        r| j        dz   | _        d S d S )Nr   =)	namer7   	group_intr4   r   r   n_groups	separatorr   )selfr=   rd   r   r4   r5   s         r   __init__zGroup.__init__   s~     	 / 6 6Wg 25gw.dhDH i; 	,++DKKK	, 	,r    c                 4    t          j        | j                  S N)r"   r;   re   rh   s    r   countszGroup.counts   s    {4>***r    c                     | j         | j        | j        j        dk    rfdD             }nfdD             }|S )Nr   c           
          g | ]A}                     d gt          d                   z            z   t          |          z  BS r   r   r   s     r   r   z Group.labels.<locals>.<listcomp>   sV     $ $ $ SXXtfSQ[[&8999U2YYF $ $ $r    c                      g | ]
}d |z  z   S )r    )r   r   r   s     r   r   z Group.labels.<locals>.<listcomp>   s"    666BVdRi'666r    )r   r   rg   r&   )rh   r6   r   r   r   s     @@@r   labelszGroup.labels   sy    hn8a<<$ $ $ $ $ $"$ $ $EE 7666#666Er    NFc                     | j         }|'t          t          |                    }||= ||         }| j        }|s-|dddf         |dddf         k                        |          S t          | j                  S )zl
        drop_idx is only available if sparse=False

        drop_idx is supposed to index into uni
        N)r   r   r   r=   astyper_   re   )rh   drop_idxrV   r%   r   idxr=   s          r   dummyzGroup.dummy   s     hS""CHc(C
 	0!!!T'Nc$'l2::5AAA///r    c                 h    t          || j                  r|j        }|                     | |f          S rk   )r!   	__class__r=   )rh   others     r   interactionzGroup.interaction   s3    eT^,, 	 KE~~tUm,,,r    Tc                 0    t          || j        |          S N)rI   )rM   re   )rh   r>   rI   s      r   rM   zGroup.group_sums   s    !T^,GGGGr    c                     t          t          |                    }t          ||z  | j        |          }||| j                 z
  }||fS r}   )floatr   rM   re   )rh   r>   rI   nobsmeans_g
x_demeaneds         r   group_demeanzGroup.group_demean   sP    SVV}}QXt~*68 8 800
7""r    r   T)__name__
__module____qualname__ri   rm   rr   intrw   r{   rM   r   rq   r    r   ra   ra      s        , , , ,$+ + +   "%s 0 0 0 0&- - -
H H H H# # # # # #r    ra   c                   ,     e Zd Zd fd	Zd Zd Z xZS )GroupSortedr   c                 2   t          | j        |                               ||           t          j        t          j        |                    d         dz                                   }t          dg|z   |t          |          gz             | _	        d S )Nrd   r   r   )
superry   ri   r"   nonzerodifftolistr   r   groupidx)rh   r=   rd   rv   ry   s       r   ri   zGroupSorted.__init__  s}    dnd##,,U,>>>z"'%..))!,Q.6688aS3Ys5zzl(:;;r    c              #   H   K   | j         D ]\  }}t          ||          V  d S rk   )r   slice)rh   lowupps      r   
group_iterzGroupSorted.group_iter
  s<       	" 	"HCS//!!!!	" 	"r    c                 j    t          j        | j                  dddf         |z
  }||k    }||         S )a  return the index array for lagged values

        Warning: if k is larger then the number of observations for an
        individual, then no values for that individual are returned.

        TODO: for the unbalanced case, I should get the same truncation for
        the array with lag=0. From the return of lag_idx we would not know
        which individual is missing.

        TODO: do I want the full equivalent of lagmat in tsa?
        maxlag or lag or lags.

        not tested yet
        Nr   )r"   r$   r   )rh   laglag_idxmask_oks       r   lag_indiceszGroupSorted.lag_indices  s=     *T]++AAAqD1C7'> wr    r   )r   r   r   ri   r   r   __classcell__)ry   s   @r   r   r     s[        < < < < < <" " "             r    r   c                     | d         }t          |t          t          t          j        t
          j        t
          j        f          rdS dS )z
    Checks if the first item of an array-like object is also array-like
    If so, we have a MultiIndex and returns True. Else returns False.
    r   TF)r!   rF   r   r"   ndarrayrB   Series	DataFrame)r>   items     r   _is_hierarchicalr   $  s:    
 Q4D$ubj")R\JKK tur    c                 &    t          j        | gd|iS )Nnames)r   from_tuplesindexr   s     r   _make_hierarchical_indexr   1  s    !E78%888r    c                     t          | j                  }t          t          t          |                              fdt          |          D             S )Nc                 F    g | ]}d z   dz                        |          S )z	group{0:0})format)r   ipads     r   r   z'_make_generic_names.<locals>.<listcomp>8  s0    DDD[_S ((++DDDr    )r   r   strrD   )r   n_namesr   s     @r   _make_generic_namesr   5  sM    %+G
c#g,,
 
 CDDDDU7^^DDDDr    c                       e Zd ZddZed             Zed             Zed             Zed             ZddZ	dd	Z
dd
ZddZddZddZddZddZd ZddZddZdS )GroupingNc                 J   t          |t          t          f          r9|/t          |d          r|                    |d           n||_        || _        nt          |          rt          ||          | _        nt          ||          | _        |Rt          | j                  }t          | j        d          r| j                            |d           n|| j        _        t          | j                  | _        t          | j        j                  | _        d| _        dS )a$  
        index : index-like
            Can be pandas MultiIndex or Index or array-like. If array-like
            and is a MultipleIndex (more than one grouping variable),
            groups are expected to be in each row. E.g., [('red', 1),
            ('red', 2), ('green', 1), ('green', 2)]
        names : list or str, optional
            The names to use for the groups. Should be a str if only
            one grouping variable is used.

        Notes
        -----
        If index is already a pandas Index then there is no copy.
        N	set_namesTinplacer   )r!   r   r   hasattrr   r   r   r   r   r   r   r   nlevelsslicesrh   r   r   s      r   ri   zGrouping.__init__<  s    eeZ011 	- 5+.. (OOE4O8888"'EKDJJ&& 65eUCC

"5u555
}+DJ774:{33 -J(((====',DJ$
OO	4:+,,r    c                 \    t          | j        d          r| j        j        S | j        j        S )Nlevshape)r   r   r   r'   rl   s    r   index_shapezGrouping.index_shapeb  s,    4:z** 	$:&&:##r    c                     t          | j        d          r| j        j        S t          j        | j                  j        S )Nlevels)r   r   r   rB   Categoricalrl   s    r   r   zGrouping.levelsi  s6    4:x(( 	5:$$>$*--44r    c                     t          | j        dd           }|Ft          | j        d          r| j        j        }n$t	          j        | j                  j        d          }|S )Ncodesrr   )getattrr   r   rr   rB   r   r   )rh   r   s     r   rr   zGrouping.labelsp  sZ     
GT22=tz8,, ?
)tz228>r    c                     | j         j        S rk   r   rl   s    r   group_nameszGrouping.group_names{  s    zr    c                 8    || j         }t          ||          } dS )z,
        Resets the index in-place.
        N)r   r   r   s      r   reindexzGrouping.reindex  s$     =$Eu%%r    r   c                 8     j                                                                       }t          j        |          }|                                 t           j         t                    r fd|D              _        dS  fd|D              _        dS )z
        Sets the slices attribute to be a list of indices of the sorted
        groups for the first index level. I.e., self.slices[0] is the
        index where each observation is in the first (sorted) group.
        c                 T    g | ]$}j                             |           d         %S )levelr   )r   get_loc_level)r   r>   r   rh   s     r   r   z'Grouping.get_slices.<locals>.<listcomp>  sC     , , ,   :33AU3CCAF , , ,r    c                 D    g | ]}j                             |          S rq   )r   get_loc)r   r>   rh   s     r   r   z'Grouping.get_slices.<locals>.<listcomp>  s)    AAAQ4:--a00AAAr    N)	r   get_level_valuesr,   r"   r*   sortr!   r   r   )rh   r   r.   s   `` r   
get_sliceszGrouping.get_slices  s     ,,U33::<<&!!dj*-- 	B, , , , ,$*, , ,DKKK BAAA&AAADKKKr    c                 N    t          j        | j        |                   | _        dS )zi
        Sets the attribute counts to equal the bincount of the (integer-valued)
        labels.
        N)r"   r;   rr   rm   rh   r   s     r   count_categorieszGrouping.count_categories  s      k$+e"455r    Tc                    |s| j         }|rrt          j        t          t	          |                    |          }|                                }|j                             |j                   st          d          |rAt	          |          t	          |                                          k    rt          d          dS dS )zSanity checksr   zData is not be sortedzDuplicate index entriesN)	r   rB   r   r   r   r   equals	Exceptionr,   )rh   	is_sortedr,   r   testtest_sorteds         r   check_indexzGrouping.check_index  s     	JE 	9<s5zz 2 2%@@@D))++K:$$[%677 9 7888 	;5zzS0000 9:::	; 	;00r    c                    || j         }t          j        |d          r~|j        dk    r,t	          j        ||d          }|                                }n,t	          j        ||          }|                    d          }t          j	        |          |j         fS t          j
        |d          r4|}|                    |          }|                                }||j         fS d}t          |          )	a  Applies a (potentially hierarchical) sort operation on a numpy array
        or pandas series/dataframe based on the grouping index or a
        user-supplied index.  Returns an object of the same type as the
        original data as well as the matching (sorted) Pandas index.
        Nr   T)r   copyr   Fr   z7data must be a Numpy array or a Pandas Series/DataFrame)r   rO   rP   r&   rB   r   
sort_indexr   r"   r*   _is_using_pandasr   r@   )rh   r]   r   outmsgs        r   r   zGrouping.sort  s     =JE+D$77 	"yA~~iE===nn&&l4u555nnUn338C==#)++'d33 	"C++e$$C..""C	>!KCS//!r    c                     |j         d         | j        k    rt          d           |                    |          j        |fi |}d|j         v rt          j        |          S t          j        |          S )zeApply function to each column, by group
        Assumes that the dataframe already has a proper indexr   z/dataframe does not have the same shape as indexr   r   )r'   r   r   groupbyapplyr"   ravelr*   )rh   	dataframefunctionr   kwargsr   s         r   transform_dataframezGrouping.transform_dataframe  sy     ?1**MNNN2ie,,28FFvFF	>>8C== 8C== r    c                     |j         d         | j        k    rt          d          t          j        || j                  } | j        ||fd|i|S )z0Apply function to each column, by group
        r   +array does not have the same shape as indexr   r   )r'   r   r   rB   r   r   r   )rh   r*   r   r   r   r   s         r   transform_arrayzGrouping.transform_array  sk     ;q>TY&&IJJJLdj999	't'	8 2 25 2*02 2 	2r    c                    t          j        |          }|j        d         | j        k    rt	          d          |                     |           g }| j        D ]J}|j        dk    r||ddf         }n|j        dk    r||         }|                     |||fi |           Kt          j	        |          }|
                    d|j        d                   S )zApply function to each group. Similar to transform_array but does
        not coerce array to a DataFrame and back and only works on a 1D or 2D
        numpy array. function is called function(group, group_idx, **kwargs).
        r   r   r   r
   Nr   r   )r"   r$   r'   r   r   r   r   r&   appendr*   r-   )rh   r*   r   r   r   	processedssubsets           r   transform_sliceszGrouping.transform_slices  s    
 
5!!;q>TY&&IJJJe$$$	 	< 	<AzQq!!!tqqXXfa::6::;;;;HY''	  Y_R%8999r    c                 <    |                      d           | j        S )Nr   r   r_   _dummiesrl   s    r   dummies_timezGrouping.dummies_time  s!    """}r    c                 <    |                      |           | j        S )Nr   r   r   s     r   dummies_groupszGrouping.dummies_groups  s!    &&&}r    c                 H    t          | j        |                   }|| _        dS )a  create a sparse indicator from a group array with integer labels

        Parameters
        ----------
        groups : ndarray, int, 1d (nobs,)
            An array of group indicators for each observation. Group levels
            are assumed to be defined as consecutive integers, i.e.
            range(n_groups) where n_groups is the number of group levels.
            A group level with no observations for it will still produce a
            column of zeros.

        Returns
        -------
        indi : ndarray, int8, 2d (nobs, n_groups)
            an indicator array with one row per observation, that has 1 in the
            column of the group level for that observation

        Examples
        --------

        >>> g = np.array([0, 0, 2, 1, 1, 2, 0])
        >>> indi = dummy_sparse(g)
        >>> indi
        <7x3 sparse matrix of type '<type 'numpy.int8'>'
            with 7 stored elements in Compressed Sparse Row format>
        >>> indi.todense()
        matrix([[1, 0, 0],
                [1, 0, 0],
                [0, 0, 1],
                [0, 1, 0],
                [0, 1, 0],
                [0, 0, 1],
                [1, 0, 0]], dtype=int8)


        current behavior with missing groups
        >>> g = np.array([0, 0, 2, 0, 2, 0])
        >>> indi = dummy_sparse(g)
        >>> indi.todense()
        matrix([[1, 0, 0],
                [1, 0, 0],
                [0, 0, 1],
                [1, 0, 0],
                [0, 0, 1],
                [1, 0, 0]], dtype=int8)
        N)r_   rr   r   )rh   r   r^   s      r   r_   zGrouping.dummy_sparse  s$    ^ DK.//r    rk   )NN)r   )TTN)r   r   r   ri   propertyr   r   rr   r   r   r   r   r   r   r   r   r   r   r   r_   rq   r    r   r   r   ;  sp       $ $ $ $L $ $ X$ 5 5 X5   X     X & & & &B B B B 6 6 6 6; ; ; ;" " " "4	! 	! 	! 	!2 2 2 2: : : :*     0 0 0 0 0 0r    r   )r   r   Fr   )__doc__statsmodels.compat.pythonr   r   numpyr"   pandasrB   statsmodels.tools.datatoolsr]   rO   r   r   r7   rM   rT   r_   ra   r   r   r   r   r   rq   r    r   <module>r     s   8 3 2 2 2 2 2 2 2         * * * * * * * * * $ $ $ $ $ $ $ $'% '% '% '%V$ $ $ $N! ! !4 4 4nE# E# E# E# E# E# E# E#P         %      B
 
 
9 9 9E E En n n n n n n n n nr    