
    g|                       U d 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ZddlZddl	m
Z
mZmZ ddlmZ ddlmZ ddlmZ ddlmZmZmZmZmZmZmZ ddlZddlmc mZ dd	lm Z m!Z! dd
l"m#Z# ddl$m%Z%m&Z&m'Z' ejP                  dk\  rddlm)Z)m*Z*m+Z+ n
ddl,m)Z)m*Z*m+Z+ ejP                  dk\  r	ddlm-Z-m.Z. nddl,m-Z-m.Z. erddlZ/ddl0Z1ddl"m2Z2 ddl3m4Z5 ddl6m7Z8  ede#      Z9 ed      Z: e.d      Z; ed      Z< e*dede<f   e<f      Z= e*dee;e<f   e;e<f      Z> e*dde:e<f      Z? e*dee-e:e;f   e<f   e:e;e<f      Z@e+ G d d e)             ZAd!d"d#dd$d%ZBeBj                         D  ci c]  \  } }|| 
 c}} ZDg d&ZEg d'ZFg d(ZG eH ej                   eJeB       eJeD                  ZKd)d*j                  d+j                  eK            d,d-d.j                  d+j                  eE            d/j                  d+j                  eEeFz               d0j                  d+j                  eG            d1ZN eOd2      ZPd3eQd4<   	 	 	 	 dJd5ZRdKd6ZSdLd7ZTdMd8ZUdNd9ZV	 	 	 	 dOd:ZWdPd;ZX	 	 	 	 	 dQ	 	 	 	 	 	 	 	 	 	 	 	 	 dRd<ZY	 	 	 	 dSd=ZZdTd>Z[e	 dU	 	 	 	 	 	 	 dVd?       Z\e	 	 	 	 	 	 	 	 dWd@       Z\	 dX	 	 	 	 	 	 	 dYdAZ\dZd[dBZ]edC   Z^dDeQdE<   	  G dF dD      Z_dG Z`	 	 	 	 d\dHZad]dIZbyc c}} w )^zUtility routines.    )annotationsN)IteratorMappingMutableMapping)deepcopy)groupby)
itemgetter)TYPE_CHECKINGAnyCallableLiteralTypeVarcastoverload)is_pandas_dataframeis_polars_dataframe)IntoDataFrame)
SchemaBase
SchemaLike	Undefined)      )ProtocolTypeAliasTyperuntime_checkable)r   
   )Concatenate	ParamSpec)IntoExpr)	DataFrame)StandardType_TTIntoDataFrame)boundTPR	WrapsFunc.)type_paramsWrappedFuncWrapsMethodz Callable[Concatenate[T, ...], R]WrappedMethodc                  "    e Zd Z	 d	 	 	 	 	 ddZy)DataFrameLikec                     y N )selfnan_as_null
allow_copys      F/var/www/openai/venv/lib/python3.12/site-packages/altair/utils/core.py__dataframe__zDataFrameLike.__dataframe__>   s        N)FT)r2   boolr3   r7   returnDfiDataFrame)__name__
__module____qualname__r5   r0   r6   r4   r-   r-   <   s%     =A59	r6   r-   ONQG)ordinalnominalquantitativetemporalgeojson)argmaxargminaveragecountdistinctmaxmeanmedianminmissingproductq1q3ci0ci1stderrstdevstdevpsumvalidvaluesvariance	variancepexponentialexponentialb)
row_numberrank
dense_rankpercent_rank	cume_distntilelagleadfirst_value
last_value	nth_value)Qyearquartermonthweekday	dayofyeardatehoursminutessecondsmillisecondsyearquarteryearquartermonth	yearmonthyearmonthdateyearmonthdatehoursyearmonthdatehoursminutes yearmonthdatehoursminutessecondsyearweekyearweekdayyearweekdayhoursyearweekdayhoursminutesyearweekdayhoursminutessecondsyeardayofyearquartermonth	monthdatemonthdatehoursmonthdatehoursminutesmonthdatehoursminutessecondsweekdayweeksdayhoursweekdayhoursweekdayhoursminutesweekdayhoursminutessecondsdayhoursdayhoursminutesdayhoursminutessecondshoursminuteshoursminutessecondsminutessecondssecondsmillisecondsutcyear
utcquarterutcmonthutcweekutcdayutcdayofyearutcdateutchours
utcminutes
utcsecondsutcmillisecondsutcyearquarterutcyearquartermonthutcyearmonthutcyearmonthdateutcyearmonthdatehoursutcyearmonthdatehoursminutes#utcyearmonthdatehoursminutessecondsutcyearweekutcyearweekdayutcyearweekdayhoursutcyearweekdayhoursminutes!utcyearweekdayhoursminutessecondsutcyeardayofyearutcquartermonthutcmonthdateutcmonthdatehoursutcmonthdatehoursminutesutcmonthdatehoursminutesseconds
utcweekdayutcweekdayhoursutcweekdayhoursminutesutcweekdayhoursminutessecondsutcdayhoursutcdayhoursminutesutcdayhoursminutessecondsutchoursminutesutchoursminutessecondsutcminutessecondsutcsecondsmillisecondsz(?P<field>.*)z(?P<type>{})|z(?P<aggregate>count)z(?P<op>count)z(?P<aggregate>{})z
(?P<op>{})z(?P<timeUnit>{}))fieldtype	agg_countop_count	aggregate	window_optimeUnit)r   r   r   r   z<frozenset[Literal['field', 'aggregate', 'type', 'timeUnit']]SHORTHAND_KEYSc                   ddl m}  || d      }|dv ry|dk(  rHt        | d      r<| j                  j                  r&d	| j                  j
                  j                         fS |d
v ry|dv ryt        j                  d| dd       y)z
    From an array-like input, infer the correct vega typecode.

    ('ordinal', 'nominal', 'quantitative', or 'temporal').

    Parameters
    ----------
    data: Any
    r   )infer_dtypeF)skipna>   mixed-integermixed-integer-floatcomplexintegerfloatingrC   categoricalcatrA   >   bytesmixedstringbooleanunicoder   rB   >   rp   timeperioddatetime	timedelta
datetime64timedelta64rD   z.I don't know how to infer vegalite type from 'z'.  Defaulting to nominal.   
stacklevel)	pandas.api.typesr   hasattrr   ordered
categoriestolistwarningswarn)datar   typs      r4   infer_vegalite_type_for_pandasr      s     -
d5
)C
   		'$"6488;K;K488..55788	Q	Q	  
 <SE B% %	

 r6   c                    dD ci c]  }|| |   
 }}	 | d   j                  |       | d   }|S c c}w # t        t        f$ r |}Y |S w xY w)zf
    Merge properties with geometry.

    * Overwrites 'type' and 'geometry' entries if existing.
    r   geometry
properties)updateAttributeErrorKeyError)featkgeom
props_geoms       r4   merge_props_geomr     st     !55 41AtAwJ 4D5\!!$','
  6 H%  
s   05 A
	A
c                   t        |       } | D ]I  }t        t        | |         j                        j	                  d      s4| |   j                         | |<   K t        j                  t        j                  |             }|d   dk(  r6|d   }t        |      dkD  r!t        |      D ]  \  }}t        |      ||<    |S |d   dk(  rt        |      }|S d|d}|S )z
    Santize a geo_interface to prepare it for serialization.

    * Make a copy
    * Convert type array or _Array to list
    * Convert tuples to lists (using json.loads/dumps)
    * Merge properties with geometry
    )_Arrayarrayr   FeatureCollectionfeaturesr   Featurer   )r   strr   r:   
startswithr   jsonloadsdumpslen	enumerater   )geokeygeo_dctidxr   s        r4   sanitize_geo_interfacer  "  s     3-C tCH~&&'223FG3x(CH 
 JJtzz#/G v--*%w<!&w/	T/5 0 N 
I	%"7+ N %':Nr6   c                Z    dd l }	 |j                  | |      S # t        t        f$ r Y yw xY w)Nr   F)numpy
issubdtypeNotImplementedError	TypeError)dtypesubtypenps      r4   numpy_is_subtyper  C  s2    }}UG,,+ s    **c                |  
 ddl 
ddl}| j                         } t        | j                  |j
                        r$| j                  j                  t              | _        | j                  D ]#  }t        |t              rd|d}t        |       t        | j                  |j                        rd}t        |      t        | j                  |j                        rd}t        |      
fd}| j                  j                         D ]  }t        t        |d         }|d   }t        |      }|dk(  r<| |   j                  t              }|j                  |j!                         d      | |<   h|d	k(  r<| |   j                  t              }|j                  |j!                         d      | |<   |d
k(  r| |   j                  t              | |<   |dk(  r=| |   j                  t              }|j                  |j!                         d      | |<   |j#                  d      r*| |   j%                  d       j'                  dd      | |<   G|j#                  d      rd| d| d}t        |      |j#                  d      r|dv r=| |   j                  t              }|j                  |j!                         d      | |<   t)        |
j*                        r| |   j                  t              | |<   t)        |
j,                        rR| |   }|j/                         
j1                  |      z  }	|j                  t              j                  |	 d      | |<   [|t        k(  sf| |   j                  t              j%                  |      }|j                  |j!                         d      | |<    | S )a  
    Sanitize a DataFrame to prepare it for serialization.

    * Make a copy
    * Convert RangeIndex columns to strings
    * Raise ValueError if column names are not strings
    * Raise ValueError if it has a hierarchical index.
    * Convert categoricals to strings.
    * Convert np.bool_ dtypes to Python bool objects
    * Convert np.int dtypes to Python int objects
    * Convert floats to objects and replace NaNs/infs with None.
    * Convert DateTime dtypes into appropriate string representations
    * Convert Nullable integers to objects and replace NaN with None
    * Convert Nullable boolean to objects and replace NaN with None
    * convert dedicated string column to objects and replace NaN with None
    * Raise a ValueError for TimeDelta dtypes
    r   Nz(Dataframe contains invalid column name: z. Column names must be stringsz"Hierarchical indices not supportedc                T    t        | j                        r| j                         S | S r/   )
isinstancendarrayr   )valr  s    r4   to_list_if_arrayz3sanitize_pandas_dataframe.<locals>.to_list_if_arrayx  s"    c2::&::<Jr6   r   categoryr   r7   r   )r   	timestampc                "    | j                         S r/   )	isoformat)xs    r4   <lambda>z+sanitize_pandas_dataframe.<locals>.<lambda>  s
    Q[[]r6   NaT r   Field "" has type "^" which is not supported by Altair. Please convert to either a timestamp or a numerical value.r   >
   Int8Int16Int32Int64UInt8UInt16UInt32UInt64Float32Float64)r  pandascopyr  columns
RangeIndexastyper   
ValueErrorindex
MultiIndexdtypesitemsr   objectwherenotnullr   applyreplacer  r   r   isnullisinf)dfpdcol_namemsgr  
dtype_itemr	  
dtype_namecol
bad_valuesr  s             @r4   sanitize_pandas_dataframerA  M  sK   ( 	B"**bmm,ZZ&&s+
JJ(C(:8, G/ /  S/!  "((BMM*2o"**bmm,2o iioo'
 Z]+1Z
# X,%%f-C99S[[]D9BxL8# X,%%f-C99S[[]D9BxL6!h<..v6BxL9$ X,%%f-C99S[[]D9BxL""#<= 8""#:;CCE2N xL "";/(<w 7   S/!"":.  X,%%f-C99S[[]D9BxLeRZZ0h<..v6BxLeR[[1 X,C5J::f-33ZKFBxLf_ X,%%f-334DEC99S[[]D9BxL_ (` Ir6   c                F   | j                   }g }d}t        | j                               }|j                         D ]T  \  }}|t        j
                  k(  r]|r[|j                  t	        j                  |      j                  t        j                        j                  j                  |             w|t        j
                  k(  r>|j                  t	        j                  |      j                  j                  |             |t        j                  k(  rB|j                  t	        j                  |      j                  j                  | d             |t        j                  k(  rd| d| d}t        |      |j                  |       W | j                  |      S )z3Sanitize narwhals.DataFrame for JSON serialization.z%Y-%m-%dT%H:%M:%Sz%.fr  r  r  )schemar   	to_nativer1  nwDateappendr?  r   Datetimedt	to_stringDurationr-  select)r   rC  r*  local_iso_fmt_string	is_polarsnamer	  r<  s           r4   sanitize_narwhals_dataframerP    s@    [[F G.#DNN$45I||~eBGG	 NNt!!"++.11;;<PQ bggNN266$<??445IJKbkk!NN266$<??448L7MS5QRSbkk!$|E7 3   S/!NN4 ) &* ;;wr6   c                    t        j                  | d      }t        j                  |      dk(  r%ddlm}  ||       }t        j                  |d      }|S )z
    Wrap `data` in `narwhals.DataFrame`.

    If `data` is not supported by Narwhals, but it is convertible
    to a PyArrow table, then first convert to a PyArrow Table,
    and then wrap in `narwhals.DataFrame`.
    Teager_or_interchange_onlyinterchanger   )arrow_table_from_dfi_dataframe)
eager_only)rE  from_native	get_levelaltair.utils.datarU  )r   data_nwrU  pa_tables       r4   to_eager_narwhals_dataframer\    sJ     nnTTBG	||G- 	E1$7..d;Nr6   c           	         ddl m}  si S g }|r$|j                  dg       |j                  dg       |r$|j                  dg       |j                  dg       |r|j                  dg       |j                  dg       |r"t        t	        j
                  d	 |D               }d
 |D        }t         t              r }	nt         fd|D              }	d|	v rt        j                  |	d   |	d         |	d<   |	ddik(  rd|	d<   d|	v r	d|	vrd|	d<   d|	vr ||      r|	d   j                  dd      }
t        j                  |d      }|j                  }|
|v r||
   }||
   t        j                  t        j                   hv r6t#        |j%                               rt'        |j%                               |	d<   nt)        |      |	d<   t        |	d   t*              r|	d   d   |	d<   |	d   d   |	d<   d|	v rd|	d   v r|	d   |	d   j-                  d      dz
     dk7  rkt/        dj1                  |	d   j3                  d      d         dj1                  dj5                  t6        j9                                     z   dz   dz   d z         |	S )!a 
  
    General tool to parse shorthand values.

    These are of the form:

    - "col_name"
    - "col_name:O"
    - "average(col_name)"
    - "average(col_name):O"

    Optionally, a dataframe may be supplied, from which the type
    will be inferred if not specified in the shorthand.

    Parameters
    ----------
    shorthand : dict or string
        The shorthand representation to be parsed
    data : DataFrame, optional
        If specified and of type DataFrame, then use these values to infer the
        column type if not provided by the shorthand.
    parse_aggregates : boolean
        If True (default), then parse aggregate functions within the shorthand.
    parse_window_ops : boolean
        If True then parse window operations within the shorthand (default:False)
    parse_timeunits : boolean
        If True (default), then parse timeUnits from within the shorthand
    parse_types : boolean
        If True (default), then parse typecodes within the shorthand

    Returns
    -------
    attrs : dict
        a dictionary of attributes extracted from the shorthand

    Examples
    --------
    >>> import pandas as pd
    >>> data = pd.DataFrame({"foo": ["A", "B", "A", "B"], "bar": [1, 2, 3, 4]})

    >>> parse_shorthand("name") == {"field": "name"}
    True

    >>> parse_shorthand("name:Q") == {"field": "name", "type": "quantitative"}
    True

    >>> parse_shorthand("average(col)") == {"aggregate": "average", "field": "col"}
    True

    >>> parse_shorthand("foo:O") == {"field": "foo", "type": "ordinal"}
    True

    >>> parse_shorthand("min(foo):Q") == {
    ...     "aggregate": "min",
    ...     "field": "foo",
    ...     "type": "quantitative",
    ... }
    True

    >>> parse_shorthand("month(col)") == {
    ...     "field": "col",
    ...     "timeUnit": "month",
    ...     "type": "temporal",
    ... }
    True

    >>> parse_shorthand("year(col):O") == {
    ...     "field": "col",
    ...     "timeUnit": "year",
    ...     "type": "ordinal",
    ... }
    True

    >>> parse_shorthand("foo", data) == {"field": "foo", "type": "nominal"}
    True

    >>> parse_shorthand("bar", data) == {"field": "bar", "type": "quantitative"}
    True

    >>> parse_shorthand("bar:O", data) == {"field": "bar", "type": "ordinal"}
    True

    >>> parse_shorthand("sum(bar)", data) == {
    ...     "aggregate": "sum",
    ...     "field": "bar",
    ...     "type": "quantitative",
    ... }
    True

    >>> parse_shorthand("count()", data) == {
    ...     "aggregate": "count",
    ...     "type": "quantitative",
    ... }
    True
    r   )is_data_typez{agg_count}\(\)z{aggregate}\({field}\)z{op_count}\(\)z{window_op}\({field}\)z{timeUnit}\({field}\)z{field}c              3  *   K   | ]  }|d z   |f  yw)z:{type}Nr0   .0ps     r4   	<genexpr>z"parse_shorthand.<locals>.<genexpr>~  s     )Oh1y=!*<hs   c           	   3     K   | ]B  }t        j                  d  |j                  di t        z   dz   t         j                         D yw)z\Az\ZNr0   )recompileformatSHORTHAND_UNITSDOTALLr`  s     r4   rc  z"parse_shorthand.<locals>.<genexpr>  s?      A 	

581886o66>		Js   AA
c              3  ~   K   | ]4  }|j                        !|j                        j                          6 y wr/   )match	groupdict)ra  exp	shorthands     r4   rc  z"parse_shorthand.<locals>.<genexpr>  s:      
yy#/ IIi **,s   :=r   r   rI   rC   r   rD   r   \r  TrR  r   sort:z"{}" z0is not one of the valid encoding data types: {}.z, zi
For more details, see https://altair-viz.github.io/user_guide/encodings/index.html#encoding-data-types. z>If you are trying to use a column name that contains a colon, zPprefix it with a backslash; for example "column\:name" instead of "column:name".)rY  r^  extendlist	itertoolschainr  dictnextINV_TYPECODE_MAPgetr6  rE  rW  rC  ObjectUnknownr   rD  r    infer_vegalite_type_for_narwhalstuplerfindr-  rg  splitjoinTYPECODE_MAPrZ   )rn  r   parse_aggregatesparse_window_opsparse_timeunitsparse_typesr^  patternsregexpsattrsunescaped_fieldrZ  rC  columns   `             r4   parse_shorthandr    s   L /	H+,-234*+,234123OOZL!	)Oh)OPQG )T" 

 
 (,,U6]E&MJf g&&&f UvU2"f U|D1.00r:..Ff$_-Fo&		

+  &g&7&7&9: >v?O?O?Q Rf @ Hf%-/ %fa 0f %fa 0f
 	55>!'N5>//4q89TANN5>//4R89@GG		,--/0 {	{
 OO bb
 	
 Lr6   c                   | j                   }t        j                  |       r<| j                  j	                         x}j                         sd|j                         fS |t        j                  k(  s&|t        j                  k(  s|t        j                  k(  ry|j                         ry|t        j                  k(  s|t        j                  k(  ryd| }t        |      )NrA   rB   rC   rD   zUnexpected DtypeKind: )r	  rE  is_ordered_categoricalr   get_categoriesis_emptyto_listStringCategoricalBoolean
is_numericrH  rF  r-  )r  r	  r   r<  s       r4   r}  r}    s     LLE
!!&)%zz88::DDF*,,...		Ubnn48K					"++	"''!1 &ug.or6   c               H     t         dd       }t         dd       }d fd}|S )a_  
    Use the signature and doc of ``tp`` for the decorated callable ``cb``.

    - **Overload 1**: Decorating method
    - **Overload 2**: Decorating function

    Returns
    -------
    **Adding the annotation breaks typing**:

        Overload[Callable[[WrapsMethod[T, R]], WrappedMethod[T, P, R]], Callable[[WrapsFunc[R]], WrappedFunc[P, R]]]
    c                    y r/   r0   cbs    r4   decoratezuse_signature.<locals>.decorate  s    FIr6   c                    y r/   r0   r  s    r4   r  zuse_signature.<locals>.decorate  s    <?r6   c                  t        d      | _        j                  x}rP| j                  xs dj                   d d}dj	                  |g|j                  d      dd	       | _        | S d
}t        |      )z
        Raises when no doc was found.

        Notes
        -----
        - Reference to ``tp`` is stored in ``cb.__wrapped__``.
        - The doc for ``cb`` will have a ``.rst`` link added, referring  to ``tp``.
        __init__zRefer to :class:``
r  T)keependsr   NzFound no doc for )getattr__wrapped____doc__r:   r  
splitlinesr   )r  doc_inline_1r<  tps       r4   r  zuse_signature.<locals>.decorate  s     !Z4ZZ6

H(9"++a&HILF&!P6+<+<d+<+KAB+O!PQBJI%bV,C %%r6   )r  zWrapsMethod[T, R]r8   zWrappedMethod[T, P, R])r  WrapsFunc[R]r8   zWrappedFunc[P, R])r  r  r8   z*WrappedMethod[T, P, R] | WrappedFunc[P, R])r   )r  r  s   ` r4   use_signaturer    s-     I I? ?&& Or6   c                     y r/   r0   originalr   r)  s      r4   update_nestedr        
 "%r6   c                     y r/   r0   r  s      r4   r  r    r  r6   c                    |rt        |       } |j                         D ]R  \  }}t        |t              r8| j	                  |i       }t        |t
              rt        ||      | |<   H|| |<   N|| |<   T | S )a  
    Update nested dictionaries.

    Parameters
    ----------
    original : MutableMapping
        the original (nested) dictionary, which will be updated in-place
    update : Mapping
        the nested dictionary of updates
    copy : bool, default False
        if True, then copy the original dictionary rather than modifying it

    Returns
    -------
    original : MutableMapping
        a reference to the (modified) original dict

    Examples
    --------
    >>> original = {"x": {"b": 2, "c": 4}}
    >>> update = {"x": {"b": 5, "d": 6}, "y": 40}
    >>> update_nested(original, update)  # doctest: +SKIP
    {'x': {'b': 5, 'c': 4, 'd': 6}, 'y': 40}
    >>> original  # doctest: +SKIP
    {'x': {'b': 5, 'c': 4, 'd': 6}, 'y': 40}
    )r   r1  r  r   rz  r   r  )r  r   r)  r   r  orig_vals         r4   r  r    sr    > H%LLNSc7#||C,H(N3 -h < #HSM # Or6   c                    t        j                         }| rddlm}  |       }nd }||j	                  |       y t        j                  |  y )Nr   )get_ipython)sysexc_infoIPython.core.getipythonr  showtraceback	tracebackprint_exception)
in_ipythonr  r  ips       r4   display_tracebackr  :  s@    ||~H7]	~
"!!8,r6   )r   datumvalue_ChannelCache_CHANNEL_CACHEc                  L    e Zd ZU ded<   ded<   ed
d       ZddZddZddZy	)r  dict[type[SchemaBase], str]channel_to_name/dict[str, dict[_ChannelType, type[SchemaBase]]]name_to_channelc                    	 t         }t         S # t        $ rD | j                  |       }t               |_        t        |j                        |_        |a Y t         S w xY wr/   )r  	NameError__new___init_channel_to_namer  _invert_group_channelsr  )clscacheds     r4   
from_cachez_ChannelCache.from_cacheV  s\    	$#F   	$[[%F%:%<F"%;F<R<R%SF"#N	$s    AAAc                   | j                   j                  |      x}r|S dt        |      j                  }t	        |      )Nzpositional of type )r  rz  r   r:   r  )r1   r  encodingr<  s       r4   get_encodingz_ChannelCache.get_encodingb  sE    ++//3383O#DH$5$5#89!#&&r6   c                  t        |t              r|S t        |t              rd|i}nVt        |t        t        f      r |D cg c]  }| j                  ||       c}S t        |t              r|j                         }| j                  j                  |      x}r|d|v rdnd   }	 |j                  |d      S t        j                  d|d       |S c c}w # t        j                  $ r |cY S w xY w)	Nrn  r  r   F)validatezUnrecognized encoding channel r   r   )r  r   r   rt  r~  _wrap_in_channelr   to_dictr  rz  	from_dict
jsonschemaValidationErrorr   r   )r1   objr  elchannelr  s         r4   r  z_ChannelCache._wrap_in_channelh  s    c:&JS!$CdE]+BEF#BD))"h7#FFZ(++-C**..x8878GsN@B ||C%|88
 MM:8,GTUVJ G -- 
s   C'C C32C3c          	         |j                         D ci c]   \  }}|t        ur|| j                  ||      " c}}S c c}}w r/   )r1  r   r  )r1   kwargsr  r  s       r4   infer_encoding_typesz"_ChannelCache.infer_encoding_types~  sM     "(
!/#)# d++C::!/
 	
 
s   %=N)r8   r  )r  z	type[Any]r8   r   )r  r   r  r   )r  dict[str, Any])	r:   r;   r<   __annotations__classmethodr  r  r  r  r0   r6   r4   r  r  R  s/    00DD	 	',
r6   c                    ddl m}  | j                  | j                  | j                  f}| j
                  j                         D ci c];  }t        |t              r)t        ||      rt        |t              r||j                  = c}S c c}w )a  
    Construct a dictionary of channel type to encoding name.

    Note
    ----
    The return type is not expressible using annotations, but is used
    internally by `mypy`/`pyright` and avoids the need for type ignores.

    Returns
    -------
        mapping: dict[type[`<subclass of FieldChannelMixin and SchemaBase>`] | type[`<subclass of ValueChannelMixin and SchemaBase>`] | type[`<subclass of DatumChannelMixin and SchemaBase>`], str]
    r   )channels)altair.vegalite.v5.schemar  FieldChannelMixinValueChannelMixinDatumChannelMixin__dict__rZ   r  r   
issubclassr   _encoding_name)chmixinscs      r4   r  r    s     9!!2#7#79M9MMF ##%%Aa:a#8Z:=V 	
1%  s   A B	c                   dd}t        | j                         t        d            }|D ci c]  \  }}| ||       c}}S c c}}w )z;Grouped inverted index for `_ChannelCache.channel_to_name`.c                    i }| D ]>  \  }}|j                   }|j                  d      r$|j                  d      rd}nd}|||<   @ |S )z
        Returns a 1-2 item dict, per channel.

        Never includes `datum`, as it is never utilized in `wrap_in_channel`.
        DatumValuer  r   )r:   endswith)ititemr  _rO  sub_keys         r4   _reducez'_invert_group_channels.<locals>._reduce  sU     -/EB;;D}}W%w'!!DM  r6   r   )r  zIterator[tuple[type[Any], str]]r8   r   )r   r1  r	   )mr  grouperr   chanss        r4   r  r    sD    
$ aggiA/G.56g(!UAwu~g666s   Ac                   t         j                         }| D ]c  }t        |t        t        f      rt        t        |      d      n|}|j                  t        |            }||vr|||<   Td|d}t        |       |j                  |      S )aa  
    Infer typed keyword arguments for args and kwargs.

    Parameters
    ----------
    args : Sequence
        Sequence of function args
    kwargs : MutableMapping
        Dict of function kwargs

    Returns
    -------
    kwargs : dict
        All args and kwargs in a single dict, with keys and types
        based on the channels mapping.
    Nz	encoding z specified twice.)r  r  r  rt  r~  rx  iterr  r   r-  r  )argsr  cacheargr  r  r<  s          r4   r  r    s    " $$&E&0tUm&DT$s)T"#%%d2h/6!"F8h\):;CS/!  %%f--r6   )r   r   r8   z=InferredVegaLiteType | tuple[InferredVegaLiteType, list[Any]])r   r  r8   r  )r   t.MutableMapping[Any, Any]r8   r  )r	  r   r
  r   r8   r7   )r9  pd.DataFramer8   r   )r   nw.DataFrame[TIntoDataFrame]r8   r  )r   r   r8   znw.DataFrame[Any])NTFTT)rn  zdict[str, Any] | strr   zIntoDataFrame | Noner  r7   r  r7   r  r7   r  r7   r8   r  )r  z	nw.Seriesr8   z8InferredVegaLiteType | tuple[InferredVegaLiteType, list])r  zCallable[P, Any]).)r  r  r   t.Mapping[Any, Any]r)  zLiteral[False]r8   r  )r  r  r   r  r)  zLiteral[True]r8   r  )F)r  r   r   r  r)  r7   r8   r  )T)r  r7   )r  r  r8   r  )r  ztuple[Any, ...]r  r  )cr  
__future__r   ru  r   re  r  r  r   collections.abcr   r   r   r)  r   r   operatorr	   typingr
   r   r   r   r   r   r   r  narwhals.stable.v1stablev1rE  narwhals.stable.v1.dependenciesr   r   narwhals.stable.v1.typingr   altair.utils.schemapir   r   r   version_infor   r   r   typing_extensionsr   r   tr(  r:  r   altair.utils._dfi_typesr    r9   !altair.vegalite.v5.schema._typingr!   InferredVegaLiteTyper"   r$   r%   r&   r'   r)   r*   r+   r-   r  r1  ry  
AGGREGATESWINDOW_AGGREGATES	TIMEUNITSrt  rv  r  VALID_TYPECODESrg  r  rh  	frozensetr   r  r   r   r  r  rA  rP  r\  r  r}  r  r  r  _ChannelTyper  r  r  r  )r   vs   00r4   <module>r     s    "   	 
   = =    Q Q Q    T 3 C CwAALLw--8 2AX)?CLcNCL+xQ'7aTJ	M8AqD>1vN 5Aq6 Xk!Q$/23!Q
 H    &2%7%7%9:%9TQAqD%9: 
: R	h ytL'94@P;QRS !!#((?";<'$++CHHZ,@A$$SXXj;L.L%MN"))#((9*=> 89 L 
-
-B-`$BAH 
& ! B* "&!" x#x
x x 	x
 x x xv=.'T 
 %(%% %  	% 
%
 
%!%% %  	% 
% *** *  	*Z-  01 1
 1
h07"7476.] ;s   *K