
    -Ph               
         U d dl mZ d dlZd dlmZmZmZmZmZm	Z	m
Z
mZmZmZ d dlmZmZmZmZmZmZmZmZmZmZmZmZmZ d dlmZ d dlmZ erd dl m!Z!  edee          Z"g d	Z# ed
dd          Z$e
d         Z%de&d<    ej'        d          Z(de&d<    G d deeef                   Z) G d de)eef         eeef                   Z* G d de)eef         eeef                   Z+ G d de+eef         eeee$f                   Z, G d de,eee$f         e*eef         eeee$f                   Z- G d de+eef         e)eef         eeeef                   Z.dS )     )annotationsN)
TYPE_CHECKINGAnyCallableClassVarIterableIteratorLiteralMappingSequenceTypeVar)CompliantDataFrameAnyCompliantDataFrameTCompliantDataFrameT_coCompliantExprT_contraCompliantFrameTCompliantFrameT_coCompliantLazyFrameAnyCompliantLazyFrameTDepthTrackingExprAnyDepthTrackingExprT_contraEagerExprT_contraLazyExprT_contraNativeExprT_co)
Protocol38)is_sequence_of)	TypeAlias_SameFrameT)CompliantGroupByDepthTrackingGroupByEagerGroupByLazyGroupByNarwhalsAggregationNativeAggregationT_cozstr | Callable[..., Any]T)bound	covariant)
summeanmedianmaxminstdvarlenn_uniquecountr   r#   z(\w+->)zre.Pattern[str]_RE_LEAF_NAMEc                  B    e Zd ZU ded<   edd            ZddZddZdS )r   r   _compliant_framereturnr   c                    | j         S N)r3   selfs    \/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/narwhals/_compliant/group_by.py	compliantzCompliantGroupBy.compliant?   s    $$    compliant_framekeys/Sequence[CompliantExprT_contra] | Sequence[str]drop_null_keysboolNonec                  d S r6    )r8   r<   r=   r?   s       r9   __init__zCompliantGroupBy.__init__C   s	     sr;   exprsr   c                    d S r6   rC   )r8   rE   s     r9   aggzCompliantGroupBy.aggL         r;   N)r4   r   )r<   r   r=   r>   r?   r@   r4   rA   )rE   r   r4   r   )__name__
__module____qualname____annotations__propertyr:   rD   rG   rC   r;   r9   r   r   <   s_         % % % X%    LKKKKKr;   r   c                      e Zd ZddZdS )DataFrameGroupByr4   ,Iterator[tuple[Any, CompliantDataFrameT_co]]c                    d S r6   rC   r7   s    r9   __iter__zDataFrameGroupBy.__iter__S   rH   r;   N)r4   rP   )rI   rJ   rK   rR   rC   r;   r9   rO   rO   O   s         LKKKKKr;   rO   c                  .    e Zd ZddZedd            ZdS )ParseKeysGroupByr<   r   r=   r>   r4   ,tuple[CompliantFrameT, list[str], list[str]]c                    t          |t                    r&t          |          }|||                                fS |                     ||          S )N)r=   )r   strlistcopy_parse_expr_keys)r8   r<   r=   keys_strs       r9   _parse_keyszParseKeysGroupBy._parse_keysZ   sP    
 $$$ 	EDzzH"Hhmmoo==((t(DDDr;   r   Sequence[CompliantExprT_contra](tuple[_SameFrameT, list[str], list[str]]c                    t          d | j        D                       dz   dfd | j        | }fdt          ||          D             } | j        |  | j        | |fS )	a#  Parses key expressions to set up `.agg` operation with correct information.

        Since keys are expressions, it's possible to alias any such key to match
        other dataframe column names.

        In order to match polars behavior and not overwrite columns when evaluating keys:

        - We evaluate what the output key names should be, in order to remap temporary column
            names to the expected ones, and to exclude those from unnamed expressions in
            `.agg(...)` context (see https://github.com/narwhals-dev/narwhals/pull/2325#issuecomment-2800004520)
        - Create temporary names for evaluated key expressions that are guaranteed to have
            no overlap with any existing column name.
        - Add these temporary columns to the compliant dataframe.
        c              3  N   K   | ] }t          t          |                    V  !d S r6   )r.   rW   ).0cs     r9   	<genexpr>z4ParseKeysGroupBy._parse_expr_keys.<locals>.<genexpr>w   s.      KKac#a&&kkKKKKKKr;      keyrW   r4   c                ^    t          |           }d| ddt          |          z
  dz
  z   S )N__tmp   )rW   r.   )re   key_strtmp_name_lengths     r9   _temporary_namez:ParseKeysGroupBy._parse_expr_keys.<locals>._temporary_namey   s9    #hhGPwPPC?S\\+IA+M$NPPPr;   c                    g | ]_\  }}|j         xr3j                                        r|j                                      n|                     |                    `S rC   )	_metadataexpansion_kindis_multi_outputnamemapalias)ra   re   new_namerl   metadatas      r9   
<listcomp>z5ParseKeysGroupBy._parse_expr_keys.<locals>.<listcomp>   s     
 
 
 X  M)6/7/F/V/V/X/X6CHLL))) ??84455
 
 
r;   )re   rW   r4   rW   )r*   columns_evaluate_aliaseszipwith_columns)r<   r=   output_names	safe_keysrl   ru   rk   s       @@@r9   rZ   z!ParseKeysGroupBy._parse_expr_keyse   s    $ KK?3JKKKKKaO	Q 	Q 	Q 	Q 	Q 	Q
 98$?
 
 
 
 
 "%T<!8!8
 
 
	 )O()4-O-y9
 	
r;   N)r<   r   r=   r>   r4   rU   )r<   r   r=   r]   r4   r^   )rI   rJ   rK   r\   staticmethodrZ   rC   r;   r9   rT   rT   V   sL        	E 	E 	E 	E &
 &
 &
 \&
 &
 &
r;   rT   c                  p    e Zd ZU dZded<   	 ddZedd            Zedd            Zedd            Z	dS )r    zf`CompliantGroupBy` variant, deals with `Eager` and other backends that utilize `CompliantExpr._depth`.z+ClassVar[Mapping[NarwhalsAggregation, Any]]_REMAP_AGGSrE   #Sequence[DepthTrackingExprT_contra]r4   rA   c                    |D ]O}|                      |          s8| j        j        j                                        }d|d}t          |          Pd S )NzsNon-trivial complex aggregation found.

Hint: you were probably trying to apply a non-elementary aggregation with az table.
Please rewrite your query such that group-by aggregations are elementary. For example, instead of:

    df.group_by('a').agg(nw.col('b').round(2).mean())

use:

    df.with_columns(nw.col('b').round(2)).group_by('a').agg(nw.col('b').mean())

)
_is_simpler:   _implementationrq   lower
ValueError)r8   rE   exprrq   msgs        r9   _ensure_all_simplez'DepthTrackingGroupBy._ensure_all_simple   s{     	& 	&D??4(( &~5:@@BBjj j j  !oo%&	& 	&r;   r   r   r@   c               b    |                                 o|                     |          | j        v S )zNReturn `True` is we can efficiently use `expr` in a native `group_by` context.)_is_elementary
_leaf_namer   clsr   s     r9   r   zDepthTrackingGroupBy._is_simple   s.     ""$$P)=)=)PPr;   rq   NarwhalsAggregation | Anyr$   c               8    | j                             ||          S )zReplace `name`, with some native representation.

        Arguments:
            name: Name of a `nw.Expr` aggregation method.

        Returns:
            A native compatible representation.
        )r   get)r   rq   s     r9   _remap_expr_namez%DepthTrackingGroupBy._remap_expr_name   s     ""4...r;   c               B    t                               d|j                  S )z=Return the last function name in the chain defined by `expr`. )r1   sub_function_namer   s     r9   r   zDepthTrackingGroupBy._leaf_name   s       T%8999r;   N)rE   r   r4   rA   )r   r   r4   r@   )rq   r   r4   r$   )r   r   r4   r   )
rI   rJ   rK   __doc__rL   r   classmethodr   r   r   rC   r;   r9   r    r       s          qp<<<<& & & &  Q Q Q [Q / / / [/ : : : [: : :r;   r    c                      e Zd ZdS )r!   N)rI   rJ   rK   rC   r;   r9   r!   r!      s         3r;   r!   c                  4    e Zd ZU ded<   ded<   ddZddZdS )r"   z	list[str]_keys_output_key_namesr   r   r4   Iterator[NativeExprT_co]c             #    K   |                     | j                  }|j        r|                    |          n|} || j                  }|                                rFh | j        | j        }t          |||          D ]"\  }}}||vr|                    ||          V  #d S t          ||          D ]\  }}|                    ||          V  d S r6   )_evaluate_output_namesr:   _alias_output_names_is_multi_output_unnamedr   r   ry   _alias_native)	r8   r   r{   aliasesnative_exprsexcludenative_exprrq   rs   s	            r9   _evaluate_exprzLazyGroupBy._evaluate_expr   s     224>BB 'D$$\222 	
 tDN++((** 	=<
<T%;<G,/lG,T,T A A(T5w&&,,[%@@@@@A A '*,&@&@ = ="U((e<<<<<<= =r;   rE   Iterable[LazyExprT_contra]c             #  J   K   |D ]}|                      |          E d {V  d S r6   )r   )r8   rE   r   s      r9   _evaluate_exprszLazyGroupBy._evaluate_exprs   sJ        	1 	1D**40000000000	1 	1r;   N)r   r   r4   r   )rE   r   r4   r   )rI   rJ   rK   rL   r   r   rC   r;   r9   r"   r"      sX         
     = = = ="1 1 1 1 1 1r;   r"   )/
__future__r   retypingr   r   r   r   r   r	   r
   r   r   r   narwhals._compliant.typingr   r   r   r   r   r   r   r   r   r   r   r   r   narwhals._typing_compatr   narwhals._utilsr   typing_extensionsr   r   __all__r$   r#   rL   compiler1   r   rO   rT   r    r!   r"   rC   r;   r9   <module>r      s   " " " " " " " 				                                                     / . . . . . * * * * * * W++++++'-)>@UVVK    #=    ")S"     
 ",J!7!7 7 7 7 7L L L L Lz"46K"KL L L L&L L L L L+-BBC%'<<=L L L6
 6
 6
 6
 6
_&;;< 5566
 6
 6
r3: 3: 3: 3: 3:_&??@ 9;PPQ3: 3: 3:l    ,.?AVVW(*;;<"$57LLM  1 1 1 1 1(*::;(*::;"$4nDE1 1 1 1 1r;   