L i UddlmZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z mZddlmZddl mZmZmZmZmZmZddlZddlmcmZddlmZmZddl m!Z"ddl#m$Z$m%Z%m&Z&dd l'm(Z)dd l'm*Z+dd l,m-Z-dd l,m.Z/dd l0m1Z1m2Z2ddl3m4Z4ddl5m6Z6ddl7m8Z8m9Z9m:Z:m;Z;ddlZ>m!Z!m?Z?ddl@mAZAmBZBmCZCmDZDejdk\rddl mFZFnddlGmFZFejdk\r ddl mHZHmIZImJZJn ddlGmHZHmIZImJZJejdk\rddl mKZKnddlGmKZKejdk\rddl mLZLnddlGmLZLerddl mMZMmNZNddlOmPZPddl mQZQddlRmSZSejd k\r dd!l mTZTmUZUndd!lGmTZTmUZUejdk\r dd"l mVZVmWZWndd"lGmVZVmWZWdd#lXmYZYmZZZm[Z[m\Z\m]Z]dd$l^m_Z_dd%l`maZambZbmcZcdd&l@mdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZlmmZmmnZnmoZompZpmqZqmrZrdd'lsmtZtmuZumvZvdd(lwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZgd)Ze$ee-e!jNee!jRfZd*ed+<ed,e%-Zdd.Z dd/Z d dd0Ze!jZe!jbZe!jfZGd1d2e!jjZGd3d4e!jlZd5e!j _hd6ZGd7d8e"jrZe!j(ZGd9d:e"jrZGd;d< eee!jd?ee"jrfZd*ed@< ee"jre!j(fZd*edA< ee%eAefZd*edB< edCee%fZd*edD< ddEZddFZe&dG ddIZ ddJZGdKd?eFdLd5MZeZd*edH< GdNdOeFdLd5MZeeZd*edP< edQeeɫZGdRdSeFe jed5TZee1eefZd*edU< GdVdWeFdLd5MZddXZddYZddZZdd[Z dd\Z dd]Z dd^Z dd_Zdd`ZddaZ ddbZGdcddeHZGdedfeݫZGdgdhe1e jeZGdidjeݫZe&fe&dG ddkZddlZde&e&e&e&f ddmZe&fddnZejdodpdqre&fddsZdtZd*edu< e eCeeeefeeefeeefedveeeeeeedwffZd*edx< de&e&e&e&e&e&e&e&e&e&e&f ddyZde&e&e&e&e&e&e&e&e&e&e&f ddzZejdod{|dd}Zejdod{|dd~Ze&e&e&e&e&d ddZeje!jddZeje!jddZeje!jddZeje!jddZeddG ddZeddG ddZeddG ddZe ddZe&dG ddZ ddZGdde?jZGdde>jZGddeee?je!jZ ddZddZGddee!jZ d ddZGddee!jZddZGddee!j ZddZGddee!jZ ddZ Gddeee!jZ ddZGddee!jZddZ ddZee!jBe!j<e!j0fZd*ed<ddZddZddZddZ ddZ ddZddZ ddZ ddZeje!j:de&e&f ddZeje!j>ddZ ddZ!eeeeee ee fZ"d*ed<ee"e!jFe!jHe!jJe!jLe!jNe!jPe!jRe!jTe!jTe!jVe!jXf Z-d*ed<ee"e!j\e!jHfZ/d*ed<ddZ0y)) annotationsN)MappingSequence)deepcopy) TYPE_CHECKINGAnyLiteralTypeVarUnionoverload)themeutils)core)Optional SchemaBase Undefined)compile_with_vegafusion)using_vegafusion)DataType) is_data_type) ConditionLike_TypeMap)vegalite_compilers)data_transformers) VEGA_VERSIONVEGAEMBED_VERSIONVEGALITE_VERSION renderers) SCHEMA_URLchannelsrmixins)MapPrimitiveValue_TSingleDefUnitChannel_TTemporal)) TypedDict)r' )Protocol TypeAliasTyperuntime_checkable)r' ) LiteralString)r' ) TypeAlias)IterableIterator)Path)IO) DataFrameLike)r' )RequiredTypeIs)NeverSelf)BinaryExpression ExpressionGetAttrExpressionGetItemExpressionIntoExpression)MimeBundleType)BrushConfigKwdsDerivedStreamKwdsMergedStreamKwds) AggregateOp_TAutosizeType_T ColorName_TCompositeMark_TImputeMethod_T LayoutAlign_TMark_TMultiTimeUnit_TOneOrSeqProjectionType_T ResolveMode_TSelectionResolution_TSelectionType_TSingleTimeUnit_T StackOffset_T)ColumnFacetRow).AggregatedFieldDef AggregateOpAnyMark BindCheckboxBinding BindInputBindRadioSelect BindRange BinParams BrushConfigDateTimeExprExprRefFacetedEncoding FacetFieldDef FieldNameGraticuleGenerator ImputeMethodImputeSequence InlineData InlineDatasetIntervalSelectionConfigJoinAggregateFieldDefLayerRepeatMappingLookupSelection NamedData ParameterNamePointSelectionConfigPredicateCompositionProjectionType RepeatMapping RepeatRefSelectionParameterSequenceGenerator SortFieldSphereGeneratorStepTimeUnitTopLevelSelectionParameter TransformUrlDataVariableParameter Vector2numberVector2Vector2number Vector3numberWindowFieldDef)0TOPLEVEL_ONLY_KEYSBin ChainedWhenChart ChartDataType ConcatChartr FacetChart FacetMapping HConcatChartImpute LayerChart LookupData ParameterParameterExpression RepeatChartSelectionExpressionSelectionPredicateCompositionThenTitle TopLevelMixin VConcatChartWhenbindingbinding_checkbox binding_radio binding_rangebinding_selectcheck_fields_and_encodingsconcat condition graticulehconcatlayerr"paramrepeat selectionselection_intervalselection_multiselection_pointselection_singlesequencesphere topo_featurevaluevconcatwhenr1r _TSchemaBase)boundct|tjr|j}|igk(ryt j |dt }tj|jjdd}d|zS)a  Generate a unique hash of the data. Parameters ---------- values : list, dict, core.InlineDataset A representation of data values. Returns ------- name : string A unique name generated from the hash of the values. emptyT) sort_keysdefaultN zdata-) isinstancerrkto_dictjsondumpsstrhashlibsha256encode hexdigest)values values_jsonhshs \/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/altair/vegalite/v5/api.py _dataset_namerso&$,,-! "~**VtSAK ..++- . 8 8 :3B ?C S=ct}i}t|tjrt j |j rt j |jst|jtjr|jd}n |j}d|ji}nFt|tr6d|vr2d|vr.|d}|jDcic]\}}|dk7s ||}}}t j |s7t|}tjdd|i|}||jdi|<|Scc}}w)z If data is specified inline, then move it to context['datasets']. This function will modify context in-place, and return a new version of data rformatnamedatasets)rrrrjr is_undefinedrrrkrrdictitemsrrp setdefault)datacontextrkwdskvrs r_consolidate_datarsF D$(   dii (1C1CDKK1P$++t'9'9:1dkk*D D$ F$$68t;Kh!%?Ah1??   f %V$~~0404039:r*40 K@s $ E2Ec|tur|St|ts?t|r4t j x}rC|t j|d}n%t|trtj|}|tjr t||}t|ttjfs$tjdt!|dd|S)a Convert input data to data for use within schema. Parameters ---------- data : The input dataset in the form of a DataFrame, dictionary, altair data object, or other type that is recognized by the data transformers. context : dict (optional) The to_dict context in which the data is being prepared. This is used to keep track of information that needs to be passed up and down the recursive serialization routine, such as global named datasets. T) pass_throughz data of type z not recognizedr) stacklevel)rrr _is_data_typergetnw to_nativerrrconsolidate_datasetsrDatawarningswarntype)rrfuncs r _prepare_datars  y d # d(;$((* *4 * T=>D D# ||D!0EE w/ dT499- . d4j\AaP KrcjeZdZejej dfd Zdfd ZxZ S)rc$t||i|yNsuper__init__)selfargskwargs __class__s rrzLookupData.__init__4s $)&)rc|jd}t|j|jd|_t t ||i|S)z;Convert the chart to a dictionary suitable for JSON export.Fdeepr)copyrrrrrr)rrrrrs rrzLookupData.to_dict8sEyyey$!$))VZZ -BC Z.???r)rrrrreturnNonerrrrrdict[str, Any]) __name__ __module__ __qualname__r use_signaturerrrr __classcell__rs@rrr3s2U)***@@rrcHeZdZdZdZeef dfd Zdfd ZxZS)ra= FacetMapping schema wrapper. Parameters ---------- column : str, :class:`FacetFieldDef`, :class:`Column` A field definition for the horizontal facet of trellis plots. row : str, :class:`FacetFieldDef`, :class:`Row` A field definition for the vertical facet of trellis plots. Fc *t|d||d|y)N)columnrowrr)rrrrrs rrzFacetMapping.__init__Ms :C:6:rc|jd}|jdi}|jdd}t|jtr8t j ditj|j||_t|jtr8t j ditj|j||_ tt|2|i|S)NFrrrr) rrrrrrrerparse_shorthandrrrr)rrrrrrrs rrzFacetMapping.to_dictUsyyey$**Y+{{64( dhh $))RE,A,A$((D,QRDH dkk3 ',,Xu/D/DT[[RV/WXDK\40$A&AAr)r&Optional[str | FacetFieldDef | Column]r#Optional[str | FacetFieldDef | Row]rrrrr) rrr__doc__ _class_is_valid_at_instantiationrrrrrs@rrr?sP (-$:C3<;6;1; ;  ;BBrrF>configpaddingautosize background$schemaceZdZUdZddiZded<dZded<edd Zd e e e f dd Z e jd d dddZ ddZddZddZddZddZddZd dZd!dZd"dZy )#rzA Parameter object.robject't.ClassVar[_TypeMap[Literal['object']]]_schemarint_countercJ|xjdz c_d|jS)Nrparam_rclss r _get_namezParameter._get_namess!   ~&&rNc`||j}||_||_||_||_yr)rrrr param_type)rrrrrs rrzParameter.__init__xs1 <>>#D   $r5.0.0rz!No need to call '.ref()' anymore.version alternativemessagec"|jS)z6'ref' is deprecated. No need to call '.ref()' anymore.)rrs rrefz Parameter.refs||~rc|jdk(rd|jiS|jdk(r-|j}dt|dr|jiS|iSd|j}t |)NvariableexprrrrzUnrecognized parameter type: )rrhasattrr ValueError)rnmmsgs rrzParameter.to_dictso ??j (DII& & __ +iiBWR-CRZZ\L LL L1$//1BCCS/ !rc|jdk(r#tjdd|jiiStj j |S)Nrnotr)rrrsr _expr_core OperatorMixin __invert__r!s rr.zParameter.__invert__sD ??k ),,egtyy5I-JK K++66t< rrr)r field_name _attrexprs r __getattr__zParameter.__getattr__sl   &:+>+>t+D , ,00JG  &dJ 7&y1 1++DIIzBBrcBtj|j|Sr)r,r?r)rrHs r __getitem__zParameter.__getitem__s++DIIzBBrrr) r str | NonerOptional[bool]rzMOptional[VariableParameter | TopLevelSelectionParameter | SelectionParameter]rz*Optional[Literal['variable', 'selection']]rr)rr)rzdict[str, str | dict[str, Any]])rPredicateComposition | Any)r3rrrPr%r@rr)rHrrz'GetAttrExpression | SelectionExpression)rHrrr?)rrrrr__annotations__r classmethodrrrr deprecatedr"rr.r1r6r9r;rArJrLrrrrrms8>7IG 4IHc''  ) AJ%%% %?% % U3   "= A@9.CCrrc@eZdZUddiZded<d dZd dZd dZd dZy )rrrrrc||_yrr>r@s rrzParameterExpression.__init__  rc0dt|jiSNr%reprr%r!s rrzParameterExpression.to_dictTYY((rc,t|jSrrZr!s rr;zParameterExpression._to_exprDIIrct|Sr=r?r@s rrAzParameterExpression._from_exprrBrNr%r@rrrzdict[str, str]rMrQ rrrrrRrrr;rArrrrr&8>7IG 4I).rrc@eZdZUddiZded<d dZd dZd dZd dZy )rrrrrc||_yrr>r@s rrzSelectionExpression.__init__rWrc0dt|jiSrYrZr!s rrzSelectionExpression.to_dictr\rc,t|jSrrZr!s rr;zSelectionExpression._to_exprr^rct|Sr=)rr@s rrAzSelectionExpression._from_exprrBrNr`rarM)r%r@rrrbrrrrrrcrrc|j}tj|st|tj rydD]} |t |j|vryy#ttf$rY2wxYw)NF)fields encodingsT) rrrrrrgetattrselectrG TypeError) parameterrHrprops rrrsx OOE % Jud6L6L$M' WU\\4889  *   sA  A21A2_TestPredicateType_ConditionExtra_PredicateType_ComposablePredicateType_StatementTyper@_FieldEqualTypec`t|ttjtj fSr)rrr,r=rrsobjs r_is_test_predicaterz0s" cC!6!68Q8QR SSrc8t|jdtSrY)rlrr)ps r_get_predicate_exprr}4s 177FI ..rr _Conditionc t|trt|}|jdk(st j |rPd|j i}t|tr||d<|St|jtr|j|d<|Sd|i}|St|rd|i}|St|tr|}|St|tjrd|ji}|Sdt|jd|d}t!|)NrrrtestzExpected a predicate, but got: z From `predicate=`.)rrr}rrrrboolrrzrr,r-r;rrrn) predicaterpredicate_exprrr)s r_predicate_to_conditionr9s0)Y',Y7   ; .%2D2D^2T )..1I%&%* '"" !IOOT2%.__ '"  0I  I &Y'   It $   Iz77 8Y//12   .d9o.F.F-IJ(m2 / nrc @t|tr|j}nSt|trCt|tr d}t |t j |}|j|t|}|j|t|tr|j}||_ |St|ttfrEt|tr&t j |}|j|tdd|i|}|St|)NzA field cannot be used for both the `if_true` and `if_false` values of a condition. One of them has to specify a `value` or `datum` definition.rr) rrrrr'rrupdaterrr _Conditionalrn)rif_trueif_falserr) cond_mutablers r_condition_to_selectionrVs':&//# GS ! h $N  S/ !++G4G NN6 "YL (J'MMO *   HsDk * h $,,X6H OOF # D<D8D  !!rc@eZdZUded<ded<ded<ded<d ed <y ) rrrOrParameter | strrrqrrrz+_StatementType | OneOrSeq[PrimitiveValue_T]__extra_items__NrrrrRrrrrrrr{s!    J@@rT)closedtotalc6eZdZUded<ded<ded<ded<y ) _ConditionClosedrOrrrrqrrrNrrrrrrs    Jrr _Conditions_Cc&eZdZUdZded<ded<y)ra A dictionary representation of a conditional encoding or property. Parameters ---------- condition One or more (predicate, statement) pairs which each form a condition. value An optional default value, used when no predicates were met. z Required[_C]rrrN)rrrrrRrrrrrs  Jrr)r IntoConditionc"eZdZUded<ded<y)_Valuez Required[Any]rrrNrrrrrrs rrc||jDcic]\}}|tjvs||c}}Scc}}wr)rrSHORTHAND_KEYS)ryrrs r_reveal_parsed_shorthandrs1 YY[ FTQA1E1E,EAqD FF Fs88c'&K|D]}t|ttjfrft|tr|j dn|}|j |j z j tj yw)NFvalidate) rrtrrkeys isdisjointrr)robjselitems r _is_extrarsr b:qyy1 21;B 1K2::u:-QSDyy{TYY[0<rrrr)rrxs r_is_condition_closedrs .#((* <) constraintsrrs r_parse_when_constraintsrs>#((*C e**7D9UBBCs57c#K|D]W}t|tjtjfr|2dt |j d|d}t|yw)Nz+Predicate composition is not permitted for z. Try wrapping z in a `Parameter` first.)rr,r-rrsrrrn) predicatesr|r)s r_validate_composablesrso ! a*22D4M4MN OG>7##&' !u$<>  C.  !sAA c@g}|r|jt||r|jt|tjt j tjj|}tjtj|S)a# Compose an `&` reduction predicate. Parameters ---------- predicates Collected positional arguments. constraints Collected keyword arguments. Raises ------ TypeError On the first non ``_ComposablePredicateType`` of `predicates` )appendrr functoolsreduceoperatorand_ itertoolschain from_iterablercastr,r<)rritersrs r_parse_when_composerso( E *:67 ,[9: (E(Ee(LMA 66*--q 11rctj|r!|s|r t||}n)d|}t||s|r|g|}t||}n|}t ||S)NzJAt least one predicate or constraint must be provided, but got: predicate=r~)rrrrnr)rrmore_predicatesrcomposedr)rs r _parse_whenr$ss )$ k*?KHH'%<) C. K00 &z;? "85 99rct|trtj|Sdt |j d|d}t |)Nz%Expected a shorthand `str`, but got: z From `statement=r)rrrrrrrn)valr)s r_parse_literalr<sT#s$$S))4DI4F4F3IJ"gR ) nrct|tr|j}nt|ts t |}|j ||Sr)rrrrrr) statementrs r _parse_thenrGsB)Z(%%'  4 ("9-  T rct|tr.|j}|jdi||d|_|St|t j s t|}|}|jdi|||S)Nrr)rrrrrrrr)r conditionsrrs r_parse_otherwiserPs)Z(NN$  !D!(5   )QYY/&y1I  -9-- rc,eZdZUded< ddZy) _BaseWhenr _conditioncjt|j}t||}|j||Sr) _deepcopyrrr)rrrrthens r _when_thenz_BaseWhen._when_thends2#4??3 9d+rN)rrurrrz_ConditionClosed | _Condition)rrrrRrrrrrr`s%'/= &rrcjeZdZdZd dZd dZed dZed dZe d dZddZy)raR Utility class for ``when-then-otherwise`` conditions. Represents the state after calling :func:`.when()`. This partial state requires calling :meth:`When.then()` to finish the condition. References ---------- `polars.when `__ c||_yr)r)rrs rrz When.__init__zs #rcLt|jd|jdS)N(r8)rrrr!s rr9z When.__repr__}s%t*%%&a':!<`__ c|d|_y)Nrr)rrs rrz Then.__init__s' 4rc yrrrs r otherwisezThen.otherwisesRUrc yrrrs rrzThen.otherwisesUXrc yrrrs rrzThen.otherwises%(rc yrrrs rrzThen.otherwises rc tjt|}||j|r|j}t |t rt |dk(rt|d}nnt |tr;||s|j}nEt|}d|d|d|d}t|d |d |}t||j}t|||S) a3 Finalize the condition with a default value. Parameters ---------- statement A spec or value to use when no predicates were met. .. note:: Roughly equivalent to an ``else`` clause. .. note:: ``str`` will be encoded as `shorthand`_. **kwds Additional keyword args are added to the resulting ``dict``. .. _shorthand: https://altair-viz.github.io/user_guide/encodings/index.html#encoding-shorthands Examples -------- Points outside of ``brush`` will not appear highlighted:: import altair as alt from vega_datasets import data source = data.cars() brush = alt.selection_interval() color = alt.when(brush).then("Origin:N").otherwise(alt.value("grey")) alt.Chart(source).mark_point().encode( x="Horsepower:Q", y="Miles_per_Gallon:Q", color=color, ).add_params(brush) rrrrz9Only one field may be used within a condition. Shorthand z would conflict with  Use `alt.value(%)` if this is not a shorthand string.z:Chained conditions cannot be mixed with field conditions. z ) rpartialrrrlistlenrrrrrnr)rrris_extracurrentrcondr)s rrzThen.otherwisesP$$%8tD DNNI .nnG'4(S\Q->*GAJ? GT* *!%J3G= 30, Origin="Europe") .then(alt.value("crimson")) .when(alt.datum.Horsepower > 150) .then(alt.value("goldenrod")) .otherwise(alt.value("grey")) ) alt.Chart(source).mark_point().encode(x="Horsepower", y="Miles_per_Gallon", color=color) rrzdChained conditions cannot be mixed with field conditions. Additional conditions would conflict with z* Must finalize by calling `.otherwise()`.z*The internal structure has been modified. z) found, but only `dict | list` are valid.)rrrrrrrrrrrrnrrNotImplementedError) rrrrrrrrrr)s rrz Then.whenst XOX5XKX \\^ [) gt $ [ 9:FJy*5 5  &+G4D==AHE;<  C. >=)),,UW &c* *rcJt|jjSNr)rrr)rrrs rrz Then.to_dictgsdnn&9&9&;<>41PQRRrct|j}d}d\}}t|jdk(r!||jj dd}n*dj d|jD}|d|d }|d |d|d|d S) Nz condition: ){}r z z c3"K|]}| ywrr).0cs r z Then.__repr__..ts!CqQE(!Cs z[ z ]rr8)rrrrreplacejoin)rrCONDLBRBrcondss rr9z Then.__repr__msDz""B t~~ ! #VDNN-.66tVDDMM!CDNN!CCEV7ugU3DqDbA..rN)r_Conditional[_C]rr)rrrrrr)rrrrr_Conditional[_Condition])rrrrr_Conditional[_Conditions])rrrrr_Conditional[Any])rrurrrSchemaBase | _Conditional[Any]) rOptional[_PredicateType]rrtrrOrrvrr)rrrrrr)rrrr;rM) rrrrrr rrrrrr9rrrrrs 5UU XX ((,/( "(( ' 47   C='C=47C= 'C=N/8M+!* M++M+3M+ M+ ' M+  M+^=S /rrc4eZdZdZ ddZddZddZy) rag Utility class for ``when-then-otherwise`` conditions. Represents the state after calling :func:`.when().then().when()`. This partial state requires calling :meth:`ChainedWhen.then()` to finish the condition. References ---------- `polars.when `__ c ||_||_yr)r _conditions)rrrs rrzChainedWhen.__init__s $%rcft|jd|jd|jdS)Nz( z, z ))rrrrr!s rr9zChainedWhen.__repr__s=Dz""#$!!$E$//)<=  rc |j||}t|r9|jj}|dj |t |St |}d|d|d|d}t|)a Attach a statement to this predicate. Parameters ---------- statement A spec or value to use when the preceding :meth:`Then.when()` clause is true. .. note:: ``str`` will be encoded as `shorthand`_. **kwds Additional keyword args are added to the resulting ``dict``. Returns ------- :class:`Then` .. _shorthand: https://altair-viz.github.io/user_guide/encodings/index.html#encoding-shorthands Examples -------- Multiple conditions with an implicit default:: import altair as alt from vega_datasets import data source = data.movies() predicate = (alt.datum.IMDB_Rating == None) | (alt.datum.Rotten_Tomatoes_Rating == None) color = ( alt.when(predicate) .then(alt.value("grey")) .when(alt.datum.IMDB_Votes < 5000) .then(alt.value("lightblue")) ) alt.Chart(source).mark_point(invalid=None).encode( x="IMDB_Rating:Q", y="Rotten_Tomatoes_Rating:Q", color=color ) rzDChained conditions cannot be mixed with field conditions. Shorthand z expanded to rr)rrrrrrrrn)rrrrrrr)s rrzChainedWhen.thensROOIt4  *))..0J { # * *9 5 # #+I6D&Mth?""+.SU  C. rN)rrrr rrrM)rrurrrr)rrrrrr9rrrrrrys2 &&.&  & 5!rrc:t|g|d|i|}t|S)aL Start a ``when-then-otherwise`` condition. The resulting predicate is an ``&`` reduction over ``predicate`` and optional ``*``, ``**``, arguments. Parameters ---------- predicate A selection or test predicate. ``str`` input will be treated as a test operand. .. note:: Accepts the same range of inputs as in :func:`.condition()`. *more_predicates Additional predicates, restricted to types supporting ``&``. empty For selection parameters, the predicate of empty selections returns ``True`` by default. Override this behavior, with ``empty=False``. .. note:: When ``predicate`` is a ``Parameter`` that is used more than once, ``alt.when(..., empty=...)`` provides granular control for each occurrence. **constraints Specify `Field Equal Predicate`_'s. Shortcut for ``alt.datum.field_name == value``, see examples for usage. Returns ------- :class:`When` A partial state which requires calling :meth:`When.then()` to finish the condition. Notes ----- - Directly inspired by the ``when-then-otherwise`` syntax used in `polars.when`_. .. _Field Equal Predicate: https://vega.github.io/vega-lite/docs/predicate.html#equal-predicate .. _polars.when: https://docs.pola.rs/py-polars/html/reference/expressions/api/polars.when.html Examples -------- Setting up a common chart:: import altair as alt from vega_datasets import data source = data.cars() brush = alt.selection_interval() points = ( alt.Chart(source) .mark_point() .encode(x="Horsepower", y="Miles_per_Gallon") .add_params(brush) ) points Basic ``if-then-else`` conditions translate directly to ``when-then-otherwise``:: points.encode(color=alt.when(brush).then("Origin").otherwise(alt.value("lightgray"))) Omitting the ``.otherwise()`` clause will use the channel default instead:: points.encode(color=alt.when(brush).then("Origin")) Predicates passed as positional arguments will be reduced with ``&``:: points.encode( color=alt.when( brush, (alt.datum.Miles_per_Gallon >= 30) | (alt.datum.Horsepower >= 130) ) .then("Origin") .otherwise(alt.value("lightgray")) ) Using keyword-argument ``constraints`` can simplify compositions like:: verbose_composition = ( (alt.datum.Name == "Name_1") & (alt.datum.Color == "Green") & (alt.datum.Age == 25) & (alt.datum.StartDate == "2000-10-01") ) when_verbose = alt.when(verbose_composition) when_concise = alt.when(Name="Name_1", Color="Green", Age=25, StartDate="2000-10-01") r)rr)rrrrrs rrrs(vITTuT TI  ?rc tdd|i|S)z'Specify a value for use in an encoding.rr)r)rrs rrr1s  ( ( ((rc d}ddd}t|}tj|sqt|trt|t s||_nI||vr:tj|d|tjt ||_n t||jddx} r$tjd d|tur| |d <d |vr2tjd|j|||d ||_d |_|Sd|vr2tj$d|j|||d ||_d|_|Stj&d|j|||d ||_d|_|S)aB Create a named parameter, see https://altair-viz.github.io/user_guide/interactions.html for examples. Although both variable parameters and selection parameters can be created using this 'param' function, to create a selection parameter, it is recommended to use either 'selection_point' or 'selection_interval' instead. Parameters ---------- name : string (optional) The name of the parameter. If not specified, a unique name will be created. value : any (optional) The default value of the parameter. If not specified, the parameter will be created without a default value. bind : :class:`Binding` (optional) Binds the parameter to an external input element such as a slider, selection list or radio button group. empty : boolean (optional) For selection parameters, the predicate of empty selections returns True by default. Override this behavior, by setting this property 'empty=False'. expr : str, Expression (optional) An expression for the value of the parameter. This expression may include other parameters, in which case the parameter will automatically update in response to upstream parameter changes. **kwds : additional keywords will be used to construct a parameter. If 'select' is among the keywords, then a selection parameter will be created. Otherwise, a variable parameter will be created. Returns ------- parameter: Parameter The parameter object that can be used in chart creation. z-The value of `empty` should be True or False.FT)noneallrrinitNzUse `value` instead of `init`.rrm)rbindrr%r$viewsrr)rrrrrrrdeprecated_warnrrr'poprrrrrrr}rw) rrrrr%rwarn_msg empty_remapro_inits rrr6sX?H .K$I   e $ eT ":eS+A#IO k !  ! !(G <)!&&e*<=IOX& &&&u& >P I !DMt00      *   D99 d%d FJ  +   11 d%d FJ  +  rc hd}||jzDcic]}||j|}}|dk(rtjd d|i|}n^|dk(rtjd d|i|}nA|dvr0tjd ddi|}t j ddd n d }t|td d |i|Scc}w) N>rrrrrrintervalrpoint>multisinglez0The types `single` and `multi` are now combined.rzselection_point()rrz$'type' must be 'point' or 'interval'rmr) rrrrlrrrrr'r)rr select_kwdskey param_kwdsrmr)s r _selectionr*sFK0;diik0IJ#txx}$JJJ z--@4@4@ **=== $ $**@@4@  >+ 9o  - -* --%KsB=rz-'selection_point()' or 'selection_interval()'z5These functions also include more helpful docstrings.rc tdd|i|S)z'selection' is deprecated use 'selection_point' or 'selection_interval' instead, depending on the type of parameter you want to create.rrr*)rrs rrrs  (4 (4 ((rzPrimitiveValue_T | Temporal | DateTime | Sequence[Mapping[SingleDefUnitChannel_T | LiteralString, PrimitiveValue_T | Temporal | DateTime]]_SelectionPointValue)Temporal | DateTimer.r._SelectionIntervalValueMapc  4tdd|||||||||| | | d | S)a Create an interval selection parameter. Selection parameters define data queries that are driven by direct manipulation from user input (e.g., mouse clicks or drags). Interval selection parameters are used to select a continuous range of data values on drag, whereas point selection parameters (`selection_point`) are used to select multiple discrete data values.). Parameters ---------- name : str (optional) The name of the parameter. If not specified, a unique name will be created. value : Any (optional) The default value of the parameter. If not specified, the parameter will be created without a default value. bind : :class:`Binding`, str (optional) Binds the parameter to an external input element such as a slider, selection list or radio button group. empty : bool (optional) For selection parameters, the predicate of empty selections returns True by default. Override this behavior, by setting this property 'empty=False'. expr : :class:`Expr` (optional) An expression for the value of the parameter. This expression may include other parameters, in which case the parameter will automatically update in response to upstream parameter changes. encodings : Sequence[str] (optional) A list of encoding channels. The corresponding data field values must match for a data tuple to fall within the selection. on : str (optional) A Vega event stream (object or selector) that triggers the selection. For interval selections, the event stream must specify a start and end. clear : str, bool (optional) Clears the selection, emptying it of all values. This property can be an Event Stream or False to disable clear. Default is 'dblclick'. resolve : Literal['global', 'union', 'intersect'] (optional) With layered and multi-view displays, a strategy that determines how selections' data queries are resolved when applied in a filter transform, conditional encoding rule, or scale domain. One of: * 'global': only one brush exists for the entire SPLOM. When the user begins to drag, any previous brushes are cleared, and a new one is constructed. * 'union': each cell contains its own brush, and points are highlighted if they lie within any of these individual brushes. * 'intersect': each cell contains its own brush, and points are highlighted only if they fall within all of these individual brushes. The default is 'global'. mark : :class:`BrushConfig` (optional) An interval selection also adds a rectangle mark to depict the extents of the interval. The ``mark`` property can be used to customize the appearance of the mark. translate : str, bool (optional) When truthy, allows a user to interactively move an interval selection back-and-forth. Can be True, False (to disable panning), or a Vega event stream definition which must include a start and end event to trigger continuous panning. Discrete panning (e.g., pressing the left/right arrow keys) will be supported in future versions. The default value is True, which corresponds to [pointerdown, window:pointerup] > window:pointermove! This default allows users to click and drag within an interval selection to reposition it. zoom : str, bool (optional) When truthy, allows a user to interactively resize an interval selection. Can be True, False (to disable zooming), or a Vega event stream definition. Currently, only wheel events are supported, but custom event streams can still be used to specify filters, debouncing, and throttling. Future versions will expand the set of events that can trigger this transformation. The default value is True, which corresponds to wheel!. This default allows users to use the mouse wheel to resize an interval selection. **kwds : Any Additional keywords to control the selection. Returns ------- parameter: Parameter The parameter object that can be used in chart creation. r") rrrrrr%rkonclearresolvemark translatezoomrr,) rrrrr%rkr1r2r3r4r5r6rs rrrsH~            rc  4tdd|||||||||| | | d | S)as Create a point selection parameter. Selection parameters define data queries that are driven by direct manipulation from user input (e.g., mouse clicks or drags). Point selection parameters are used to select multiple discrete data values; the first value is selected on click and additional values toggled on shift-click. To select a continuous range of data values on drag interval selection parameters (`selection_interval`) can be used instead. Parameters ---------- name : str (optional) The name of the parameter. If not specified, a unique name will be created. value : Any (optional) The default value of the parameter. If not specified, the parameter will be created without a default value. bind : :class:`Binding`, str (optional) Binds the parameter to an external input element such as a slider, selection list or radio button group. empty : bool (optional) For selection parameters, the predicate of empty selections returns True by default. Override this behavior, by setting this property 'empty=False'. expr : :class:`Expr` (optional) An expression for the value of the parameter. This expression may include other parameters, in which case the parameter will automatically update in response to upstream parameter changes. encodings : Sequence[str] (optional) A list of encoding channels. The corresponding data field values must match for a data tuple to fall within the selection. fields : Sequence[str] (optional) A list of field names whose values must match for a data tuple to fall within the selection. on : str (optional) A Vega event stream (object or selector) that triggers the selection. For interval selections, the event stream must specify a start and end. clear : str, bool (optional) Clears the selection, emptying it of all values. This property can be an Event Stream or False to disable clear. Default is 'dblclick'. resolve : Literal['global', 'union', 'intersect'] (optional) With layered and multi-view displays, a strategy that determines how selections' data queries are resolved when applied in a filter transform, conditional encoding rule, or scale domain. One of: * 'global': only one brush exists for the entire SPLOM. When the user begins to drag, any previous brushes are cleared, and a new one is constructed. * 'union': each cell contains its own brush, and points are highlighted if they lie within any of these individual brushes. * 'intersect': each cell contains its own brush, and points are highlighted only if they fall within all of these individual brushes. The default is 'global'. toggle : str, bool (optional) Controls whether data values should be toggled (inserted or removed from a point selection) or only ever inserted into point selections. One of: * True (default): the toggle behavior, which corresponds to "event.shiftKey". As a result, data values are toggled when the user interacts with the shift-key pressed. * False: disables toggling behaviour; the selection will only ever contain a single data value corresponding to the most recent interaction. * A Vega expression which is re-evaluated as the user interacts. If the expression evaluates to True, the data value is toggled into or out of the point selection. If the expression evaluates to False, the point selection is first cleared, and the data value is then inserted. For example, setting the value to the Vega expression True will toggle data values without the user pressing the shift-key. nearest : bool (optional) When true, an invisible voronoi diagram is computed to accelerate discrete selection. The data value nearest the mouse cursor is added to the selection. The default is False, which means that data values must be interacted with directly (e.g., clicked on) to be added to the selection. **kwds : Any Additional keywords to control the selection. Returns ------- parameter: Parameter The parameter object that can be used in chart creation. r#) rrrrrr%rkrjr1r2r3togglenearestrr,) rrrrr%rkrjr1r2r3r8r9rs rrrWsHF          rrr&c tdddi|S)z8'selection_multi' is deprecated. Use 'selection_point'.rr#rr,rs rrr  -7 -f --rc tdddi|S)z9'selection_single' is deprecated. Use 'selection_point'.rr#rr,r;s rrrr<r) autocompletedebounceelementr placeholderc8tj||||||S)a A generic binding. Parameters ---------- input : str The type of input element to use. The valid values are ``"checkbox"``, ``"radio"``, ``"range"``, ``"select"``, and any other legal `HTML form input type `__. autocomplete : str A hint for form autofill. See the `HTML autocomplete attribute `__ for additional information. debounce : float If defined, delays event handling until the specified milliseconds have elapsed since the last event was fired. element : str An optional CSS selector string indicating the parent element to which the input element should be added. By default, all input elements are added within the parent container of the Vega view. name : str By default, the signal name is used to label input elements. This ``name`` property can be used instead to specify a custom label for the bound signal. placeholder : str Text that appears in the form control when it has no value set. )r>r?r@inputrrA)rr\)rCr>r?r@rrAs rrrs(F >>!   rc 0tjdddi|S)zA checkbox binding.rCcheckboxr)rrZr;s rrrs    8: 8 88rc 0tjdddi|S)zA radio button binding.rCradiorrr]r;s rrr s    8g 8 88rc 0tjdddi|S)zA select binding.rCrmrrHr;s rrrs    9h 9& 99rc 0tjdddi|S)zA range binding.rCranger)rr^r;s rrrs >> 2 26 22r.c yrrrrrrrs rrrsrc yrrrMs rrr& #rc yrrrMs rrr/rOrc yrr)rrrrs rrr8s rc 8t||}t|||fi|S)a A conditional attribute or encoding. Parameters ---------- predicate: Parameter, PredicateComposition, expr.Expression, dict, or string the selection predicate or test predicate for the condition. if a string is passed, it will be treated as a test operand. if_true: the spec or object to use if the selection predicate is true if_false: the spec or object to use if the selection predicate is false empty For selection parameters, the predicate of empty selections returns ``True`` by default. Override this behavior, with ``empty=False``. .. note:: When ``predicate`` is a ``Parameter`` that is used more than once, ``alt.condition(..., empty=...)`` provides granular control for each :func:`.condition()`. **kwargs: additional keyword args are added to the resulting dict Returns ------- spec: dict or VegaLiteSchema the spec that describes the condition r~)rr)rrrrrrs rrr=s%F( ?I "9gx J6 JJrc0t|trt|tsBts>t|tr.t |j tr|jtur|St|jdtj}t|)a Enforces an intersection type w/ `SchemaBase` & `TopLevelMixin` objects. Use for methods, called from `TopLevelMixin` that are defined in `SchemaBase`. Notes ----- - The `super` sub-branch is not statically checked *here*. - It would widen the inferred intersection to: - `( | super)` - Both dunder attributes are not in the `super` type stubs - Requiring 2x *# type: ignore[attr-defined]* - However it is required at runtime for any cases that use `super(..., copy)`. - The inferred type **is** used statically **outside** of this function. z does not derive from ) rrrrr issubclass__self_class__ __thisclass__rrrn)ryr)s r_top_schema_baserWhsv$ 3 # 3 (F  sE "3--z:!!]2 c##&& d?d Zddd@dZ dddAdZ d ddd e e e d d d df dBdZdCdZdDdZdEdZdFdZeeeeef dGdZdHdZeeeeeeeeeeeeeeeeeeef dIdZdJdZeef dKdZeedf dLdZeef dMdZeeeeeeeeeef dNdZeeeeef dOdZeef dPd Z dQd!Zefed" dRd#Zef dSd$Z ef dTd%Z!eeef dUd&Z"eeeef dVd'Z#eeef dWd(Z$eeeef dXd)Z%eeeeeef dYd*Z&dZd[d+Z'eef d\d,Z(eeef d]d-Z)eeeeef d^d.Z*d_d/Z+eeef d`d0Z,e-j\d1d23 da dbd4Z/dbd5Z0e-jbe2jfdcd6Z4e-jbe2jjddd7Z6e-jbe2jnddd8Z8e-jbe2jrddd9Z:xZ;S)erzCMixin for top-level chart objects such as Chart, LayeredChart, etc.FrrrrT vega-liteNrignorerc|dvrd|}t||r|jni}|jdi|jdd}t |jd}t |dt }tj|s. tj|d } t| ||_ | |d<d|d<t tt|j!||t#|d  } |r{d | vr t$| d <t'jx} rtj(| | d } nddd}t||dr$| jdij+|d|jddr't-r|dk(r d}t|t/| S|dk(r+t1j} | d}t|| | S| S#t$r|} YGwxYw)a Convert the chart to a dictionary suitable for JSON export. Parameters ---------- validate : bool, optional If True (default), then validate the result against the schema. format : {"vega-lite", "vega"}, optional The chart specification format. The `"vega"` format relies on the active Vega-Lite compiler plugin, which by default requires the vl-convert-python package. ignore : list[str], optional A list of keys to ignore. context : dict[str, Any], optional A context dictionary. Raises ------ SchemaValidationError : If ``validate`` and the result does not conform to the schema. Notes ----- - ``ignore``, ``context`` are usually not needed to be specified as a user. - *Technical*: ``ignore`` will **not** be passed to child :meth:`.to_dict()`. >vegarYzCThe format argument must be either "vega-lite" or "vega". Received r top_levelTFrr)eager_or_interchange_only) pre_transform)rr[rr rz#Expected a theme to be set but got Nz?. Call `themes.enable('default')` to reset the `ThemeRegistry`.r`rYzWhen the "vegafusion" data transformer is enabled, the to_dict() and to_json() chart methods must be called with format="vega". For example: >>> chart.to_dict(format="vega") >>> chart.to_json(format="vega")r]z)No active vega-lite compiler plugin found)r'rrrrWrlrrrr from_nativernrrrrrrr r update_nestedr_using_vegafusion_compile_with_vegafusionr)rrrr[rr) is_top_levelr original_datar vegalite_specrpluginrs rrzTopLevelMixin.to_dictsF . .WX^WabCS/ !%,',,.:r*{{;5 %***6fi8 !!-0 %~~mtT&dG4DI"GFO % -eM4.HIQQfd7RW6XR  -+5 i(yy{"t" % 3 3DFMPT U :$BTU n$z"((R8?? @ST ;; -2C2E$;!o%/ >> v '++-F~A o%-( ( i %$ %sG G/.G/c n|g}|i}|j||||}tj|f||d|S)a Convert a chart to a JSON string. Parameters ---------- validate : bool, optional If True (default), then validate the result against the schema. indent : int, optional The number of spaces of indentation to use. The default is 2. sort_keys : bool, optional If True (default), sort keys in the output. format : {"vega-lite", "vega"}, optional The chart specification format. The `"vega"` format relies on the active Vega-Lite compiler plugin, which by default requires the vl-convert-python package. ignore : list[str], optional A list of keys to ignore. context : dict[str, Any], optional A context dictionary. **kwargs Additional keyword arguments are passed to ``json.dumps()`` Raises ------ SchemaValidationError : If ``validate`` and the result does not conform to the schema. Notes ----- - ``ignore``, ``context`` are usually not needed to be specified as a user. - *Technical*: ``ignore`` will **not** be passed to child :meth:`.to_dict()`. rrr[r)indentr)rrr) rrrlrrr[rrspecs rto_jsonzTopLevelMixin.to_jsonsRV >F ?G||fVW zz$MvMfMMrc |rd|d<tj|jfdttt ||||||d |S)a Embed a Vega/Vega-Lite spec into an HTML page. Parameters ---------- base_url : string (optional) The base url from which to load the javascript libraries. output_div : string (optional) The id of the div element where the plot will be shown. embed_options : dict (optional) Dictionary of options to pass to the vega-embed script. Default entry is {'mode': mode}. json_kwds : dict (optional) Dictionary of keywords to pass to json.dumps(). fullhtml : boolean (optional) If True (default) then return a full html page. If False, then return an HTML snippet that can be embedded into an HTML page. requirejs : boolean (optional) If False (default) then load libraries from base_url using