
    IR-e6                         d dl Z d dlZd dlZd dlmZ ddlmZ ddgZd Z	d Z
d	 Z G d
 d          Z G d de          Z G d de          ZdS )    N)AstropyUserWarning   )get_index_by_namesTableGroupsColumnGroupsc                     |                      d          5  t          | |          cd d d            S # 1 swxY w Y   d S )Ndiscard_on_copy)
index_mode_table_group_by)tablekeyss     4lib/python3.11/site-packages/astropy/table/groups.pytable_group_byr      s    			+	,	, , ,ud++, , , , , , , , , , , , , , , , , ,s   377c                     ddl m} ddlm} t	          |t
                    r|f}t	          |t          t          f          r|D ]V}| j        vrt          d|           j
        r2t          j         |         j                  rt          d|d          W                      fd|D             d	          }t           |          }d
}nt	          |t          j        |f          rd|}t#          |          t#                     k    r=t          d                    t#          |          t#                                         d}d}n/t'          d                    t)          |                              |st	          ||          r ||          }	 ||                                }n|                    d          }d
}	n9# t&          $ r, |                                }t/          j                    dv}	Y nw xY w||         }t          j        d
g|dd         |dd         k    d
gf          }
t          j        |
          }|	sBt7          |dd         |dd                   D ]!\  }}|||                                          "                      |                   }||dd                  }t	          ||          r
||j        d<   t=          |||          |_        |S )a2  
    Get groups for ``table`` on specified ``keys``.

    Parameters
    ----------
    table : `Table`
        Table to group
    keys : str, list of str, `Table`, or Numpy array
        Grouping key specifier

    Returns
    -------
    grouped_table : Table object with groups attr set accordingly
    r   represent_mixins_as_columnsTablezTable does not have key column zMissing values in key column z are not allowedc                      g | ]
}|         S  r   ).0keyr   s     r   
<listcomp>z#_table_group_by.<locals>.<listcomp>5   s    %A%A%ASeCj%A%A%A    F)copyTz9Input keys array length {} does not match table length {}NzHKeys input must be string, list, tuple, Table or numpy array, but got {}	mergesort)kind)DarwinWindowsgrouped_by_table_colsindicesr   ) 	serializer   r   r   
isinstancestrlisttuplecolnames
ValueErrormaskednpanymask	__class__r   ndarraylenformat	TypeErrortypesorted_dataargsortplatformsystemconcatenateflatnonzerozipsortmetar   _groups)r   r   r   r   name
table_keystable_indexr!   idx_sortstable_sortdiffsr#   i0i1outout_keyss   `               r   r   r      su    766666 $ w$u&&  
 	 	D5>)) !K4!K!KLLL| uT{'7 8 8  LDLLL  
 __%A%A%A%AD%A%A%A_NN
 )55 $	D2:u-	.	. 

z??c%jj((KRR
OOSZZ   
  % V]]T

 
 
 	
  =:j%88 =00<<
E""..00HH!)){);;H E E E %%''o''/DDE H%J NTFJqrrNj"o$EvNOOEnU##G  #'#2#,44 	# 	#FBRUO  """" //%/
*
*C'#2#,'H(E"" G1F-.c7BBBCKJs   /G 3HHc                    ddl m} ddlm} t	          ||          r ||          }|                                }t	          |t          j                  st          dt          |                     t          |          t          |           k    r=t          d                    t          |          t          |                               |                                }||         }t          j        dg|dd         |dd         k    dgf          }t          j        |          }|                     | |                   }t#          ||||dd                  	          |_        |S )
a>  
    Get groups for ``column`` on specified ``keys``.

    Parameters
    ----------
    column : Column object
        Column to group
    keys : Table or Numpy array of same length as col
        Grouping key specifier

    Returns
    -------
    grouped_column : Column object with groups attr set accordingly
    r   r   r   z(Keys input must be numpy array, but got z:Input keys array length {} does not match column length {}TNr    r"   )r$   r   r   r   r%   as_arrayr,   r0   r3   r4   r1   r*   r2   r6   r9   r:   r/   r   r>   )columnr   r   r   rB   rD   r#   rG   s           r   column_group_byrL   y   sp    766666$ **400}}dBJ'' QO4::OOPPP
4yyCKKHOOD		3v;; 
 
 	
 ||~~H>D NTFDHSbS	$9D6BCCEnU##G 

6(+
,
,CsG$wss|:LMMMCKJr   c                   J    e Zd ZdZed             Zd Zd ZeZd Z	d Z
d ZdS )	
BaseGroupsa4  
    A class to represent groups within a table of heterogeneous data.

      - ``keys``: key values corresponding to each group
      - ``indices``: index values in parent table or column corresponding to group boundaries
      - ``aggregate()``: method to create new table by aggregating within groups
    c                 H    t          | t                    r| j        n| j        S N)r%   r   parent_columnparent_tableselfs    r   parentzBaseGroups.parent   s&     #-T<"@"@WDdFW	
r   c                     d| _         | S Nr   )_iter_indexrS   s    r   __iter__zBaseGroups.__iter__   s    r   c                     | j         }|t          | j                  dz
  k     r<| j        |         | j        |dz            }}| xj         dz  c_         | j        ||         S t          Nr   )rX   r1   r#   rU   StopIteration)rT   iirE   rF   s       r   nextzBaseGroups.next   sj    DL!!A%%%\"%t|BF';B!;r"u%%r   c                    | j         }t          |t          t          j        f          rD| j        |         | j        |dz            }}|||         }|j        j        |         |j        _        n| j        d d         | j        dd          }}	 ||         ||         }	}n"# t          $ r}
t          d          |
d }
~
ww xY wt          j        t          |          t                    }t          ||	          D ]\  }}d|||<   ||         }|j        j        |         |j        _        t          j        dgt          j        |	|z
            g          |j        _        |S )Nr   r    zHIndex item for groups attribute must be a slice, numpy mask or int arraydtypeTr   )rU   r%   intr,   integerr#   groupsr   _keys	Exceptionr3   zerosr1   boolr;   r9   cumsum_indices)rT   itemrU   rE   rF   rG   indices0indices1i0si1serrr.   s               r   __getitem__zBaseGroups.__getitem__   se   dS"*-.. 	N\$'dQh)?BB-C%}1$7CJ!%crc!2DL4DhH#D>8D>S   .  
 8CKKt444Dc3-- # #B"RU,C%}1$7CJ"$.1#rys7K7K1L"M"MCJ
s   B 
B<'B77B<c                 2    d| j         j         d| j         dS )N<z	 indices=>)r/   __name__r#   rS   s    r   __repr__zBaseGroups.__repr__   s"    D4>*DDT\DDDDr   c                 0    t          | j                  dz
  S r[   )r1   r#   rS   s    r   __len__zBaseGroups.__len__   s    4<  1$$r   N)ru   
__module____qualname____doc__propertyrU   rY   r^   __next__rq   rv   rx   r   r   r   rN   rN      s          
 
 X

        H  4E E E% % % % %r   rN   c                   N    e Zd ZddZed             Zed             Zd Zd ZdS )r   Nc                 R    || _         |j        j        | _        || _        || _        d S rP   )rQ   inforR   rj   re   )rT   rQ   r#   r   s       r   __init__zColumnGroups.__init__   s*    *).;


r   c                     | j         r| j         j        j        S | j        (t	          j        dt          | j                  g          S | j        S rW   )rR   rd   r#   rj   r,   arrayr1   rQ   rS   s    r   r#   zColumnGroups.indices   sN      	%$+33}$xC(:$;$; <===}$r   c                 @    | j         r| j         j        j        S | j        S rP   )rR   rd   r   re   rS   s    r   r   zColumnGroups.keys   s&      	$+00:r   c           	      P   ddl m} | j        d d         | j        dd          }}| j        t	          |          }t          d          }t          j        u }t          j        u }	 |sh|s|s|rb|r;t          j	        
                    |          t          j        | j                  z  }	nT|rt          j	        
                    |          }	n/t          j        fdt          ||          D                       }	                    |	          }
nK# t          $ r>}t!          d                    j        j        j        j        |                    |d }~ww xY w|
j        }dD ]7}	 t+          ||t-          j        |                     (# t.          $ r Y 4w xY w|
S )Nr   )MaskedColumnr    reduceatc                 <    g | ]\  }} ||                   S r   r   )r   rE   rF   funcpar_cols      r   r   z*ColumnGroups.aggregate.<locals>.<listcomp>  s/     R R R&"bgben!5!5 R R Rr   z/Cannot aggregate column '{}' with type '{}': {})r?   unitr2   descriptionr=   )rK   r   r#   rQ   r%   hasattrr,   summeanaddr   diffr   r;   r/   rf   r3   r2   r   r?   ra   setattrgetattrAttributeError)rT   r   r   rn   ro   r+   r   sum_case	mean_casevalsrG   rp   out_infoattrr   s    `            @r   	aggregatezColumnGroups.aggregate  s   ((((((<$dl122&6S$G\224,,26>BGO		 Tx T8 Ty T 76??7C88274<;P;PPDD &!v==#66DDx R R R R RCSMM R R RSS##D))CC 	 	 	AHHL%w|'93   		 8E 	 	D$d(C(CDDDD!    
s+   +B.D 
E"$9EE"1$F
F#"F#c                     t          j        t          |           t                    }t	          |           D ]\  }} ||          ||<   | |         S )a  
        Filter groups in the Column based on evaluating function ``func`` on each
        group sub-table.

        The function which is passed to this method must accept one argument:

        - ``column`` : `Column` object

        It must then return either `True` or `False`.  As an example, the following
        will select all column groups with only positive values::

          def all_positive(column):
              if np.any(column < 0):
                  return False
              return True

        Parameters
        ----------
        func : function
            Filter function

        Returns
        -------
        out : Column
            New column with the aggregated rows.
        r`   )r,   emptyr1   rh   	enumerate)rT   r   r.   igroup_columns        r   filterzColumnGroups.filter%  sV    6 xD		...( 	) 	)OA|d<((DGGDzr   NN)	ru   ry   rz   r   r|   r#   r   r   r   r   r   r   r   r      s}            % % X%   X" " "H    r   c                   d    e Zd ZddZed             Zed             Zd Zd Zed             Z	dS )	r   Nc                 0    || _         || _        || _        d S rP   )rR   rj   re   )rT   rR   r#   r   s       r   r   zTableGroups.__init__H  s    (


r   c                 v    t          | j        di                               dd          }|r| j        j        ndS )z^
        Return the names of columns in the parent table that were used for grouping.
        r=   r!   Fr   )r   r   getr)   )rT   r!   s     r   key_colnameszTableGroups.key_colnamesM  sD     !(	62 > > B B#U!
 !
 &;Bty!!Br   c                 n    | j         (t          j        dt          | j                  g          S | j         S rW   )rj   r,   r   r1   rR   rS   s    r   r#   zTableGroups.indices[  s2    = 8QD$5 6 67888= r   c                    | j         dd         }g }| j        }|j                                        D ]}|j        j        | j        v r|                    |          }n_	 |j        j        	                    |          }n># t          $ r1}t          j        t          |          t                     Y d}~d}~ww xY w|                    |           |                    ||j                  S )a  
        Aggregate each group in the Table into a single row by applying the reduction
        function ``func`` to group values in each column.

        Parameters
        ----------
        func : function
            Function that reduces an array of values to a single value

        Returns
        -------
        out : Table
            New table with the aggregated rows.
        Nr    )r=   )r#   rR   columnsvaluesr   r?   r   takerd   r   r3   warningswarnr&   r   appendr/   r=   )rT   r   rn   out_colsrR   colnew_colrp   s           r   r   zTableGroups.aggregateb  s     l3B3('..00 	% 	%Cx} 111((3--!ho77==GG    M#c((,>???HHHH OOG$$$$%%h\5F%GGGs   A>>
B9'B44B9c                     t          j        t          |           t                    }| j        }t          |           D ]\  }} |||          ||<   | |         S )a  
        Filter groups in the Table based on evaluating function ``func`` on each
        group sub-table.

        The function which is passed to this method must accept two arguments:

        - ``table`` : `Table` object
        - ``key_colnames`` : tuple of column names in ``table`` used as keys for grouping

        It must then return either `True` or `False`.  As an example, the following
        will select all table groups with only positive values in the non-key columns::

          def all_positive(table, key_colnames):
              colnames = [name for name in table.colnames if name not in key_colnames]
              for colname in colnames:
                  if np.any(table[colname] < 0):
                      return False
              return True

        Parameters
        ----------
        func : function
            Filter function

        Returns
        -------
        out : Table
            New table with the aggregated rows.
        r`   )r,   r   r1   rh   r   r   )rT   r   r.   r   r   group_tables         r   r   zTableGroups.filter  s`    < xD		...('oo 	6 	6NA{d;55DGGDzr   c                     | j         S rP   )re   rS   s    r   r   zTableGroups.keys  s
    zr   r   )
ru   ry   rz   r   r|   r   r#   r   r   r   r   r   r   r   r   G  s           
 C C XC ! ! X! H  H  HD# # #J   X  r   )r7   r   numpyr,   astropy.utils.exceptionsr   indexr   __all__r   r   rL   rN   r   r   r   r   r   <module>r      s         7 7 7 7 7 7 % % % % % %.
), , ,a a aH, , ,^<% <% <% <% <% <% <% <%~] ] ] ] ]: ] ] ]@d d d d d* d d d d dr   