
    4ik|                       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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 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/Z0ddl"m1Z1 ddl2m3Z4 ddl5m6Z7  edd      Z8 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/d0j                  d-j                  eE            d1j                  d-j                  eEeFz               d2j                  d-j                  eG            d3ZN eOd4      ZPd5eQd6<   	 	 	 	 dLd7ZRdMd8ZSdNd9ZTdOd:ZUdPd;ZV	 	 	 	 dQd<ZWdRd=ZX	 	 	 	 	 dS	 	 	 	 	 	 	 	 	 	 	 	 	 dTd>ZY	 	 	 	 dUd?ZZdVd@Z[e	 dW	 	 	 	 	 	 	 dXdA       Z\e	 	 	 	 	 	 	 	 dYdB       Z\	 dZ	 	 	 	 	 	 	 d[dCZ\d\d]dDZ]edE   Z^dFeQdG<   	  G dH dF      Z_dI Z`	 	 	 	 d^dJZad_dKZbyc c}} w )`zUtility routines.    )annotationsN)CallableIteratorMappingMutableMapping)deepcopy)groupby)
itemgetter)TYPE_CHECKINGAny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_PandasDataFrameTzpd.DataFrame)boundTIntoDataFrame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      [/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/altair/utils/core.py__dataframe__zDataFrameLike.__dataframe__>   s        N)FT)r3   boolr4   r8   returnDfiDataFrame)__name__
__module____qualname__r6   r1   r7   r5   r.   r.   <   s%     =A59	r7   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floatingrD   categoricalcatrB   >   bytesmixedstringbooleanunicoder   rC   >   rq   timeperioddatetime	timedelta
datetime64timedelta64rE   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      r5   infer_vegalite_type_for_pandasr      s     -
d5
)C
   		'$"6488;K;K488..55788	Q	Q	  
 <SE B% %	

 r7   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       r5   merge_props_geomr     sq     !551AtAwJ5D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
    Sanitize 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        r5   sanitize_geo_interfacer  "  s     3-C  )tCH~&&'223FG3x(CH)
 JJtzz#/G v--*%w<!&w/ 6	T/56 N 
I	%"7+ N %':Nr7   c                n    dd l }	 t        d|j                  | |            S # t        t        f$ r Y yw xY w)Nr   r8   F)numpyr   
issubdtypeNotImplementedError	TypeError)dtypesubtypenps      r5   numpy_is_subtyper  C  s9    FBMM%9::+ s   " 44c                  
 ddl 
ddl}t        d| 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        d|d         }|d	   }t        |      }|d
k(  r<| |   j                  t              }|j                  |j!                         d      | |<   d|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      | |<   C|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      | |<   W|t        k(  sb| |   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   Nr"   z(Dataframe contains invalid column name: z. Column names must be stringsz"Hierarchical indices not supportedc                T    t        | j                        r| j                         S | S r0   )
isinstancendarrayr   )valr  s    r5   to_list_if_arrayz3sanitize_pandas_dataframe.<locals>.to_list_if_arrayx  s"    c2::&::<Jr7   r   r   categoryr   r8   r   )r   	timestampc                "    | j                         S r0   )	isoformat)xs    r5   <lambda>z+sanitize_pandas_dataframe.<locals>.<lambda>  s    Q[[] r7   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  pandasr   copyr  columns
RangeIndexastyper   
ValueErrorindex
MultiIndexdtypesitemsobjectwherenotnullr   applyreplacer  r   r   isnullisinf)dfpdcol_namemsgr  
dtype_itemr
  
dtype_namecol
bad_valuesr  s             @r5   sanitize_pandas_dataframerB  M  s_   ( 	!2779	-B"**bmm,ZZ&&s+
JJ "(C(:8, G/ /  S/!" "((BMM*2o"**bmm,2o iioo' O:
 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_O:` Ir7   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_nativer2  nwDateappendr@  r   Datetimedt	to_stringDurationr.  select)r   rD  r+  local_iso_fmt_string	is_polarsnamer
  r=  s           r5   sanitize_narwhals_dataframerQ    sE    [[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r7   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)rF  from_native	get_levelaltair.utils.datarV  )r   data_nwrV  pa_tables       r5   to_eager_narwhals_dataframer]    sJ     nnTTBG	||G- 	E1$7..d;Nr7   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}Nr1   .0ps     r5   	<genexpr>z"parse_shorthand.<locals>.<genexpr>~  s     )O1y=!*<)Os   c           	   3     K   | ]B  }t        j                  d  |j                  di t        z   dz   t         j                         D yw)z\Az\ZNr1   )recompileformatSHORTHAND_UNITSDOTALLra  s     r5   rd  z"parse_shorthand.<locals>.<genexpr>  s?       	

581886o66>		Js   AA
c              3  ~   K   | ]4  }|j                        !|j                        j                          6 y wr0   )match	groupdict)rb  exp	shorthands     r5   rd  z"parse_shorthand.<locals>.<genexpr>  s:      
yy#/ IIi **,
s   :=r   r   rJ   rD   r   rE   r   \r  TrS  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".)rZ  r_  extendlist	itertoolschainr  dictnextINV_TYPECODE_MAPgetr7  rF  rX  rD  ObjectUnknownr   rE  r    infer_vegalite_type_for_narwhalstuplerfindr.  rh  splitjoinTYPECODE_MAPr[   )ro  r   parse_aggregatesparse_window_opsparse_timeunitsparse_typesr_  patternsregexpsattrsunescaped_fieldr[  rD  columns   `             r5   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
 	
 Lr7   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        |      )NrB   rC   rD   rE   zUnexpected DtypeKind: )r
  rF  is_ordered_categoricalr   get_categoriesis_emptyto_listStringCategoricalBoolean
is_numericrI  rG  r.  )r  r
  r   r=  s       r5   r~  r~    s     LLE
!!&)%zz88::DDF*,,...		Ubnn48K					"++	"''!1 &ug.or7   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 r0   r1   cbs    r5   decoratezuse_signature.<locals>.decorate  s    FIr7   c                    y r0   r1   r  s    r5   r  zuse_signature.<locals>.decorate  s    <?r7   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       r5   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 %%r7   )r  zWrapsMethod[T, R]r9   zWrappedMethod[T, P, R])r  WrapsFunc[R]r9   zWrappedFunc[P, R])r  r  r9   z*WrappedMethod[T, P, R] | WrappedFunc[P, R])r   )r  r  s   ` r5   use_signaturer    s-     I I? ?&& Or7   c                     y r0   r1   originalr   r*  s      r5   update_nestedr        
  #r7   c                     y r0   r1   r  s      r5   r  r    r  r7   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   r2  r  r   r{  r   r  )r  r   r*  r  r  orig_vals         r5   r  r    sw    > H%LLN  Sc7#||C,H(N3 -h < #HSM  Or7   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       r5   display_tracebackr  :  s@    ||~H7]	~
"!!8,r7   )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r0   )r  	NameError__new___init_channel_to_namer  _invert_group_channelsr  )clscacheds     r5   
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  r{  r   r;   r  )r2   r  encodingr=  s       r5   get_encodingz_ChannelCache.get_encodingb  sE    ++//3383O#DH$5$5#89!#&&r7   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)	Nro  r  r   F)validatezUnrecognized encoding channel r   r   )r  r   r   ru  r  _wrap_in_channelr   to_dictr  r{  	from_dict
jsonschemaValidationErrorr   r   )r2   objr  elchannelr  s         r5   r  z_ChannelCache._wrap_in_channelh  s    c:&JS!$CdE]+BEFBD))"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 r0   )r2  r   r  )r2   kwargsr  r  s       r5   infer_encoding_typesz"_ChannelCache.infer_encoding_types~  sH     "(
#)# d++C::
 	
 
s   %=N)r9   r  )r  z	type[Any]r9   r   )r  r   r  r   )r  dict[str, Any])	r;   r<   r=   __annotations__classmethodr  r  r  r  r1   r7   r5   r  r  R  s/    00DD	 	',
r7   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.v6.schemar  FieldChannelMixinValueChannelMixinDatumChannelMixin__dict__r[   r  r   
issubclassr   _encoding_name)chmixinscs      r5   r  r    s{     9!!2#7#79M9MMF ##%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  _rP  sub_keys         r5   _reducez'_invert_group_channels.<locals>._reduce  sZ     -/ 	EB;;D}}W%w'!!DM	 r7   r   )r  zIterator[tuple[type[Any], str]]r9   r   )r	   r2  r
   )mr  grouperr   chanss        r5   r  r    s@    
$ aggiA/G.56(!UAwu~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  ru  r  ry  iterr  r   r.  r  )argsr  cacheargr  r  r=  s          r5   r  r    s    " $$&E "&0tUm&DT$s)T"#%%d2h/6!"F8h\):;CS/!" %%f--r7   )r   r   r9   z=InferredVegaLiteType | tuple[InferredVegaLiteType, list[Any]])r   r  r9   r  )r   MutableMapping[Any, Any]r9   r  )r
  r   r  r   r9   r8   )r:  r"   r9   r"   )r   nw.DataFrame[TIntoDataFrame]r9   r  )r   r   r9   znw.DataFrame[Any])NTFTT)ro  zdict[str, Any] | strr   zIntoDataFrame | Noner  r8   r  r8   r  r8   r  r8   r9   r  )r  z	nw.Seriesr9   z8InferredVegaLiteType | tuple[InferredVegaLiteType, list])r  zCallable[P, Any]).)r  r   r   Mapping[Any, Any]r*  zLiteral[False]r9   r   )r  r  r   r  r*  zLiteral[True]r9   r   )F)r  r   r   r  r*  r8   r9   r   )T)r  r8   )r  r  r9   r  )r  ztuple[Any, ...]r  r  )cr  
__future__r   rv  r   rf  r  r  r   collections.abcr   r   r   r   r*  r   r	   operatorr
   typingr   r   r   r   r   r   r  narwhals.stable.v1stablev1rF  narwhals.stable.v1.dependenciesr   r   narwhals.stable.v1.typingr   altair.utils.schemapir   r   r   version_infor   r   r   typing_extensionsr   r   r)  r;  r   altair.utils._dfi_typesr    r:   !altair.vegalite.v6.schema._typingr!   InferredVegaLiteTyper"   r$   r%   r&   r'   r(   r*   r+   r,   r.   r  r2  rz  
AGGREGATESWINDOW_AGGREGATES	TIMEUNITSru  rw  r  VALID_TYPECODESrh  r  ri  	frozensetr   r  r   r   r  r  rB  rQ  r]  r  r~  r  r  r  _ChannelTyper  r  r  r  )r   vs   00r5   <module>r     s
    "   	 
   G G    G G    T 3 C CwAALLw--8 2AX 3>J)?CLcNCL+xQ'7aTJ	M8AqD>1vN 5Aq6 Xk!Q$/23!Q
 H    &2%7%7%9:TQAqD: 
: 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   0K%