-
Notifications
You must be signed in to change notification settings - Fork 794
/
api.py
4974 lines (4291 loc) · 179 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import functools
import hashlib
import io
import itertools
import json
import operator
import sys
import typing as t
import warnings
from copy import deepcopy as _deepcopy
from typing import (
TYPE_CHECKING,
Any,
Literal,
Protocol,
Sequence,
TypeVar,
Union,
overload,
)
from typing_extensions import TypeAlias
import jsonschema
import narwhals.stable.v1 as nw
from altair import utils
from altair.expr import core as _expr_core
from altair.utils import Optional, SchemaBase, Undefined
from altair.utils._vegafusion_data import (
compile_with_vegafusion as _compile_with_vegafusion,
)
from altair.utils._vegafusion_data import using_vegafusion as _using_vegafusion
from altair.utils.data import DataType
from altair.utils.data import is_data_type as _is_data_type
from .compiler import vegalite_compilers
from .data import data_transformers
from .display import VEGA_VERSION, VEGAEMBED_VERSION, VEGALITE_VERSION, renderers
from .schema import SCHEMA_URL, channels, core, mixins
from .schema._typing import Map
from .theme import themes
if sys.version_info >= (3, 13):
from typing import TypedDict
else:
from typing_extensions import TypedDict
if TYPE_CHECKING:
from pathlib import Path
from typing import IO, Iterable, Iterator
from altair.utils.core import DataFrameLike
if sys.version_info >= (3, 13):
from typing import Required, TypeIs
else:
from typing_extensions import Required, TypeIs
if sys.version_info >= (3, 11):
from typing import Never, Self
else:
from typing_extensions import Never, Self
from altair.expr.core import (
BinaryExpression,
Expression,
GetAttrExpression,
GetItemExpression,
IntoExpression,
)
from altair.utils.display import MimeBundleType
from .schema._typing import (
AggregateOp_T,
AutosizeType_T,
ColorName_T,
CompositeMark_T,
ImputeMethod_T,
LayoutAlign_T,
Mark_T,
MultiTimeUnit_T,
OneOrSeq,
ProjectionType_T,
ResolveMode_T,
SelectionResolution_T,
SelectionType_T,
SingleDefUnitChannel_T,
SingleTimeUnit_T,
StackOffset_T,
)
from .schema.channels import Column, Facet, Row
from .schema.core import (
AggregatedFieldDef,
AggregateOp,
AnyMark,
BindCheckbox,
Binding,
BindRadioSelect,
BindRange,
BinParams,
Expr,
ExprRef,
FacetedEncoding,
FacetFieldDef,
FieldName,
GraticuleGenerator,
ImputeMethod,
ImputeSequence,
InlineData,
InlineDataset,
IntervalSelectionConfig,
JoinAggregateFieldDef,
LayerRepeatMapping,
LookupSelection,
Mark,
NamedData,
ParameterName,
PointSelectionConfig,
Predicate,
PredicateComposition,
ProjectionType,
RepeatMapping,
RepeatRef,
SelectionParameter,
SequenceGenerator,
SortField,
SphereGenerator,
Step,
TimeUnit,
TopLevelSelectionParameter,
Transform,
UrlData,
VariableParameter,
Vector2number,
Vector2Vector2number,
Vector3number,
WindowFieldDef,
)
__all__ = [
"TOPLEVEL_ONLY_KEYS",
"Bin",
"ChainedWhen",
"Chart",
"ChartDataType",
"ConcatChart",
"DataType",
"FacetChart",
"FacetMapping",
"HConcatChart",
"Impute",
"LayerChart",
"LookupData",
"Parameter",
"ParameterExpression",
"RepeatChart",
"SelectionExpression",
"SelectionPredicateComposition",
"Then",
"Title",
"TopLevelMixin",
"VConcatChart",
"When",
"binding",
"binding_checkbox",
"binding_radio",
"binding_range",
"binding_select",
"check_fields_and_encodings",
"concat",
"condition",
"graticule",
"hconcat",
"layer",
"mixins",
"param",
"repeat",
"selection",
"selection_interval",
"selection_multi",
"selection_point",
"selection_single",
"sequence",
"sphere",
"topo_feature",
"value",
"vconcat",
"when",
]
ChartDataType: TypeAlias = Optional[Union[DataType, core.Data, str, core.Generator]]
_TSchemaBase = TypeVar("_TSchemaBase", bound=SchemaBase)
# ------------------------------------------------------------------------
# Data Utilities
def _dataset_name(values: dict[str, Any] | list | InlineDataset) -> str:
"""
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.
"""
if isinstance(values, core.InlineDataset):
values = values.to_dict()
if values == [{}]:
return "empty"
values_json = json.dumps(values, sort_keys=True, default=str)
hsh = hashlib.sha256(values_json.encode()).hexdigest()[:32]
return "data-" + hsh
def _consolidate_data(
data: ChartDataType | UrlData, context: dict[str, Any]
) -> ChartDataType | NamedData | InlineData | UrlData:
"""
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
"""
values: Any = Undefined
kwds = {}
if isinstance(data, core.InlineData):
if utils.is_undefined(data.name) and not utils.is_undefined(data.values):
if isinstance(data.values, core.InlineDataset):
values = data.to_dict()["values"]
else:
values = data.values
kwds = {"format": data.format}
elif isinstance(data, dict) and "name" not in data and "values" in data:
values = data["values"]
kwds = {k: v for k, v in data.items() if k != "values"}
if not utils.is_undefined(values):
name = _dataset_name(values)
data = core.NamedData(name=name, **kwds)
context.setdefault("datasets", {})[name] = values
return data
def _prepare_data(
data: ChartDataType, context: dict[str, Any] | None = None
) -> ChartDataType | NamedData | InlineData | UrlData | Any:
"""
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.
"""
if data is Undefined:
return data
# convert dataframes or objects with __geo_interface__ to dict
elif not isinstance(data, dict) and _is_data_type(data):
if func := data_transformers.get():
data = func(nw.to_native(data, strict=False))
# convert string input to a URLData
elif isinstance(data, str):
data = core.UrlData(data)
# consolidate inline data to top-level datasets
if context is not None and data_transformers.consolidate_datasets:
data = _consolidate_data(data, context)
# if data is still not a recognized type, then return
if not isinstance(data, (dict, core.Data)):
warnings.warn(f"data of type {type(data)} not recognized", stacklevel=1)
return data
# ------------------------------------------------------------------------
# Aliases & specializations
Bin = core.BinParams
Impute = core.ImputeParams
Title = core.TitleParams
class LookupData(core.LookupData):
@utils.use_signature(core.LookupData)
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
def to_dict(self, *args: Any, **kwargs: Any) -> dict[str, Any]:
"""Convert the chart to a dictionary suitable for JSON export."""
copy = self.copy(deep=False)
copy.data = _prepare_data(copy.data, kwargs.get("context"))
return super(LookupData, copy).to_dict(*args, **kwargs)
class FacetMapping(core.FacetMapping):
"""
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.
"""
_class_is_valid_at_instantiation = False
def __init__(
self,
column: Optional[str | FacetFieldDef | Column] = Undefined,
row: Optional[str | FacetFieldDef | Row] = Undefined,
**kwargs: Any,
) -> None:
super().__init__(column=column, row=row, **kwargs) # type: ignore[arg-type]
def to_dict(self, *args: Any, **kwargs: Any) -> dict[str, Any]:
copy = self.copy(deep=False)
context = kwargs.get("context", {})
data = context.get("data", None)
if isinstance(self.row, str):
copy.row = core.FacetFieldDef(**utils.parse_shorthand(self.row, data))
if isinstance(self.column, str):
copy.column = core.FacetFieldDef(**utils.parse_shorthand(self.column, data))
return super(FacetMapping, copy).to_dict(*args, **kwargs)
# ------------------------------------------------------------------------
# Encoding will contain channel objects that aren't valid at instantiation
core.FacetedEncoding._class_is_valid_at_instantiation = False
# ------------------------------------------------------------------------
# These are parameters that are valid at the top level, but are not valid
# for specs that are within a composite chart
# (layer, hconcat, vconcat, facet, repeat)
TOPLEVEL_ONLY_KEYS = {"background", "config", "autosize", "padding", "$schema"}
# -------------------------------------------------------------------------
# Tools for working with parameters
class Parameter(_expr_core.OperatorMixin):
"""A Parameter object."""
_counter: int = 0
@classmethod
def _get_name(cls) -> str:
cls._counter += 1
return f"param_{cls._counter}"
def __init__(
self,
name: str | None = None,
empty: Optional[bool] = Undefined,
param: Optional[
VariableParameter | TopLevelSelectionParameter | SelectionParameter
] = Undefined,
param_type: Optional[Literal["variable", "selection"]] = Undefined,
) -> None:
if name is None:
name = self._get_name()
self.name = name
self.empty = empty
self.param = param
self.param_type = param_type
@utils.deprecated(
version="5.0.0",
alternative="to_dict",
message="No need to call '.ref()' anymore.",
)
def ref(self) -> dict[str, Any]:
"""'ref' is deprecated. No need to call '.ref()' anymore."""
return self.to_dict()
def to_dict(self) -> dict[str, str | dict[str, Any]]:
if self.param_type == "variable":
return {"expr": self.name}
elif self.param_type == "selection":
nm: Any = self.name
return {"param": nm.to_dict() if hasattr(nm, "to_dict") else nm}
else:
msg = f"Unrecognized parameter type: {self.param_type}"
raise ValueError(msg)
def __invert__(self) -> SelectionPredicateComposition | Any:
if self.param_type == "selection":
return SelectionPredicateComposition({"not": {"param": self.name}})
else:
return _expr_core.OperatorMixin.__invert__(self)
def __and__(self, other: Any) -> SelectionPredicateComposition | Any:
if self.param_type == "selection":
if isinstance(other, Parameter):
other = {"param": other.name}
return SelectionPredicateComposition({"and": [{"param": self.name}, other]})
else:
return _expr_core.OperatorMixin.__and__(self, other)
def __or__(self, other: Any) -> SelectionPredicateComposition | Any:
if self.param_type == "selection":
if isinstance(other, Parameter):
other = {"param": other.name}
return SelectionPredicateComposition({"or": [{"param": self.name}, other]})
else:
return _expr_core.OperatorMixin.__or__(self, other)
def __repr__(self) -> str:
return f"Parameter({self.name!r}, {self.param})"
def _to_expr(self) -> str:
return self.name
def _from_expr(self, expr: IntoExpression) -> ParameterExpression:
return ParameterExpression(expr=expr)
def __getattr__(self, field_name: str) -> GetAttrExpression | SelectionExpression:
if field_name.startswith("__") and field_name.endswith("__"):
raise AttributeError(field_name)
_attrexpr = _expr_core.GetAttrExpression(self.name, field_name)
# If self is a SelectionParameter and field_name is in its
# fields or encodings list, then we want to return an expression.
if check_fields_and_encodings(self, field_name):
return SelectionExpression(_attrexpr)
return _expr_core.GetAttrExpression(self.name, field_name)
# TODO: Are there any special cases to consider for __getitem__?
# This was copied from v4.
def __getitem__(self, field_name: str) -> GetItemExpression:
return _expr_core.GetItemExpression(self.name, field_name)
# Enables use of ~, &, | with compositions of selection objects.
class SelectionPredicateComposition(core.PredicateComposition):
def __invert__(self) -> SelectionPredicateComposition:
return SelectionPredicateComposition({"not": self.to_dict()})
def __and__(self, other: SchemaBase) -> SelectionPredicateComposition:
return SelectionPredicateComposition({"and": [self.to_dict(), other.to_dict()]})
def __or__(self, other: SchemaBase) -> SelectionPredicateComposition:
return SelectionPredicateComposition({"or": [self.to_dict(), other.to_dict()]})
class ParameterExpression(_expr_core.OperatorMixin):
def __init__(self, expr: IntoExpression) -> None:
self.expr = expr
def to_dict(self) -> dict[str, str]:
return {"expr": repr(self.expr)}
def _to_expr(self) -> str:
return repr(self.expr)
def _from_expr(self, expr: IntoExpression) -> ParameterExpression:
return ParameterExpression(expr=expr)
class SelectionExpression(_expr_core.OperatorMixin):
def __init__(self, expr: IntoExpression) -> None:
self.expr = expr
def to_dict(self) -> dict[str, str]:
return {"expr": repr(self.expr)}
def _to_expr(self) -> str:
return repr(self.expr)
def _from_expr(self, expr: IntoExpression) -> SelectionExpression:
return SelectionExpression(expr=expr)
def check_fields_and_encodings(parameter: Parameter, field_name: str) -> bool:
param = parameter.param
if utils.is_undefined(param) or isinstance(param, core.VariableParameter):
return False
for prop in ["fields", "encodings"]:
try:
if field_name in getattr(param.select, prop):
return True
except (AttributeError, TypeError):
pass
return False
# -------------------------------------------------------------------------
# Tools for working with conditions
_TestPredicateType: TypeAlias = Union[
str, _expr_core.Expression, core.PredicateComposition
]
"""https://vega.github.io/vega-lite/docs/predicate.html"""
_PredicateType: TypeAlias = Union[
Parameter,
core.Expr,
Map,
_TestPredicateType,
_expr_core.OperatorMixin,
]
"""Permitted types for `predicate`."""
_ComposablePredicateType: TypeAlias = Union[
_expr_core.OperatorMixin, SelectionPredicateComposition
]
"""Permitted types for `&` reduced predicates."""
_StatementType: TypeAlias = Union[SchemaBase, Map, str]
"""Permitted types for `if_true`/`if_false`.
In python terms:
```py
if _PredicateType:
return _StatementType
elif _PredicateType:
return _StatementType
else:
return _StatementType
```
"""
_ConditionType: TypeAlias = t.Dict[str, Union[_TestPredicateType, Any]]
"""Intermediate type representing a converted `_PredicateType`.
Prior to parsing any `_StatementType`.
"""
_LiteralValue: TypeAlias = Union[str, bool, float, int]
"""Primitive python value types."""
_FieldEqualType: TypeAlias = Union[_LiteralValue, Map, Parameter, SchemaBase]
"""Permitted types for equality checks on field values:
- `datum.field == ...`
- `FieldEqualPredicate(equal=...)`
- `when(**constraints=...)`
"""
def _is_test_predicate(obj: Any) -> TypeIs[_TestPredicateType]:
return isinstance(obj, (str, _expr_core.Expression, core.PredicateComposition))
def _get_predicate_expr(p: Parameter) -> Optional[str | SchemaBase]:
# https://vega.github.io/vega-lite/docs/predicate.html
return getattr(p.param, "expr", Undefined)
def _predicate_to_condition(
predicate: _PredicateType, *, empty: Optional[bool] = Undefined
) -> _ConditionType:
condition: _ConditionType
if isinstance(predicate, Parameter):
predicate_expr = _get_predicate_expr(predicate)
if predicate.param_type == "selection" or utils.is_undefined(predicate_expr):
condition = {"param": predicate.name}
if isinstance(empty, bool):
condition["empty"] = empty
elif isinstance(predicate.empty, bool):
condition["empty"] = predicate.empty
else:
condition = {"test": predicate_expr}
elif _is_test_predicate(predicate):
condition = {"test": predicate}
elif isinstance(predicate, dict):
condition = predicate
elif isinstance(predicate, _expr_core.OperatorMixin):
condition = {"test": predicate._to_expr()}
else:
msg = (
f"Expected a predicate, but got: {type(predicate).__name__!r}\n\n"
f"From `predicate={predicate!r}`."
)
raise TypeError(msg)
return condition
def _condition_to_selection(
condition: _ConditionType,
if_true: _StatementType,
if_false: _StatementType,
**kwargs: Any,
) -> SchemaBase | dict[str, _ConditionType | Any]:
selection: SchemaBase | dict[str, _ConditionType | Any]
if isinstance(if_true, SchemaBase):
if_true = if_true.to_dict()
elif isinstance(if_true, str):
if isinstance(if_false, str):
msg = (
"A 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."
)
raise ValueError(msg)
else:
if_true = utils.parse_shorthand(if_true)
if_true.update(kwargs)
condition.update(if_true)
if isinstance(if_false, SchemaBase):
# For the selection, the channel definitions all allow selections
# already. So use this SchemaBase wrapper if possible.
selection = if_false.copy()
selection.condition = condition
elif isinstance(if_false, (str, dict)):
if isinstance(if_false, str):
if_false = utils.parse_shorthand(if_false)
if_false.update(kwargs)
selection = dict(condition=condition, **if_false)
else:
raise TypeError(if_false)
return selection
class _ConditionClosed(TypedDict, closed=True, total=False): # type: ignore[call-arg]
# https://peps.python.org/pep-0728/
# Parameter {"param", "value", "empty"}
# Predicate {"test", "value"}
empty: Optional[bool]
param: Parameter | str
test: _TestPredicateType
value: Any
class _ConditionExtra(TypedDict, closed=True, total=False): # type: ignore[call-arg]
# https://peps.python.org/pep-0728/
# Likely a Field predicate
empty: Optional[bool]
param: Parameter | str
test: _TestPredicateType
value: Any
__extra_items__: _StatementType | OneOrSeq[_LiteralValue]
_Condition: TypeAlias = _ConditionExtra
"""A singular, non-chainable condition produced by ``.when()``."""
_Conditions: TypeAlias = t.List[_ConditionClosed]
"""Chainable conditions produced by ``.when()`` and ``Then.when()``."""
_C = TypeVar("_C", _Conditions, _Condition)
class _Conditional(TypedDict, t.Generic[_C], total=False):
condition: Required[_C]
value: Any
class _Value(TypedDict, closed=True, total=False): # type: ignore[call-arg]
# https://peps.python.org/pep-0728/
value: Required[Any]
__extra_items__: Any
def _reveal_parsed_shorthand(obj: Map, /) -> dict[str, Any]:
# Helper for producing error message on multiple field collision.
return {k: v for k, v in obj.items() if k in utils.SHORTHAND_KEYS}
def _is_extra(*objs: Any, kwds: Map) -> Iterator[bool]:
for el in objs:
if isinstance(el, (SchemaBase, t.Mapping)):
item = el.to_dict(validate=False) if isinstance(el, SchemaBase) else el
yield not (item.keys() - kwds.keys()).isdisjoint(utils.SHORTHAND_KEYS)
else:
continue
def _is_condition_extra(obj: Any, *objs: Any, kwds: Map) -> TypeIs[_Condition]:
# NOTE: Short circuits on the first conflict.
# 1 - Originated from parse_shorthand
# 2 - Used a wrapper or `dict` directly, including `extra_keys`
return isinstance(obj, str) or any(_is_extra(obj, *objs, kwds=kwds))
def _parse_when_constraints(
constraints: dict[str, _FieldEqualType], /
) -> Iterator[BinaryExpression]:
"""
Wrap kwargs with `alt.datum`.
```py
# before
alt.when(alt.datum.Origin == "Europe")
# after
alt.when(Origin="Europe")
```
"""
for name, value in constraints.items():
yield _expr_core.GetAttrExpression("datum", name) == value
def _validate_composables(
predicates: Iterable[Any], /
) -> Iterator[_ComposablePredicateType]:
for p in predicates:
if isinstance(p, (_expr_core.OperatorMixin, SelectionPredicateComposition)):
yield p
else:
msg = (
f"Predicate composition is not permitted for "
f"{type(p).__name__!r}.\n"
f"Try wrapping {p!r} in a `Parameter` first."
)
raise TypeError(msg)
def _parse_when_compose(
predicates: tuple[Any, ...],
constraints: dict[str, _FieldEqualType],
/,
) -> BinaryExpression:
"""
Compose an `&` reduction predicate.
Parameters
----------
predicates
Collected positional arguments.
constraints
Collected keyword arguments.
Raises
------
TypeError
On the first non ``_ComposablePredicateType`` of `predicates`
"""
iters = []
if predicates:
iters.append(_validate_composables(predicates))
if constraints:
iters.append(_parse_when_constraints(constraints))
r = functools.reduce(operator.and_, itertools.chain.from_iterable(iters))
return t.cast(_expr_core.BinaryExpression, r)
def _parse_when(
predicate: Optional[_PredicateType],
*more_predicates: _ComposablePredicateType,
empty: Optional[bool],
**constraints: _FieldEqualType,
) -> _ConditionType:
composed: _PredicateType
if utils.is_undefined(predicate):
if more_predicates or constraints:
composed = _parse_when_compose(more_predicates, constraints)
else:
msg = (
f"At least one predicate or constraint must be provided, "
f"but got: {predicate=}"
)
raise TypeError(msg)
elif more_predicates or constraints:
predicates = predicate, *more_predicates
composed = _parse_when_compose(predicates, constraints)
else:
composed = predicate
return _predicate_to_condition(composed, empty=empty)
def _parse_literal(val: Any, /) -> dict[str, Any]:
if isinstance(val, str):
return utils.parse_shorthand(val)
else:
msg = (
f"Expected a shorthand `str`, but got: {type(val).__name__!r}\n\n"
f"From `statement={val!r}`."
)
raise TypeError(msg)
def _parse_then(statement: _StatementType, kwds: dict[str, Any], /) -> dict[str, Any]:
if isinstance(statement, SchemaBase):
statement = statement.to_dict()
elif not isinstance(statement, dict):
statement = _parse_literal(statement)
statement.update(kwds)
return statement
def _parse_otherwise(
statement: _StatementType, conditions: _Conditional[Any], kwds: dict[str, Any], /
) -> SchemaBase | _Conditional[Any]:
selection: SchemaBase | _Conditional[Any]
if isinstance(statement, SchemaBase):
selection = statement.copy()
conditions.update(**kwds) # type: ignore[call-arg]
selection.condition = conditions["condition"]
else:
if not isinstance(statement, t.Mapping):
statement = _parse_literal(statement)
selection = conditions
selection.update(**statement, **kwds) # type: ignore[call-arg]
return selection
class _BaseWhen(Protocol):
# NOTE: Temporary solution to non-SchemaBase copy
_condition: _ConditionType
def _when_then(
self, statement: _StatementType, kwds: dict[str, Any], /
) -> _ConditionClosed | _Condition:
condition: Any = _deepcopy(self._condition)
then = _parse_then(statement, kwds)
condition.update(then)
return condition
class When(_BaseWhen):
"""
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 <https://docs.pola.rs/py-polars/html/reference/expressions/api/polars.when.html>`__
"""
def __init__(self, condition: _ConditionType, /) -> None:
self._condition = condition
def __repr__(self) -> str:
return f"{type(self).__name__}({self._condition!r})"
@overload
def then(self, statement: str, /, **kwds: Any) -> Then[_Condition]: ...
@overload
def then(self, statement: _Value, /, **kwds: Any) -> Then[_Conditions]: ...
@overload
def then(
self, statement: dict[str, Any] | SchemaBase, /, **kwds: Any
) -> Then[Any]: ...
def then(self, statement: _StatementType, /, **kwds: Any) -> Then[Any]:
"""
Attach a statement to this predicate.
Parameters
----------
statement
A spec or value to use when the preceding :func:`.when()` clause is true.
.. note::
``str`` will be encoded as `shorthand<https://altair-viz.github.io/user_guide/encodings/index.html#encoding-shorthands>`__.
**kwds
Additional keyword args are added to the resulting ``dict``.
Returns
-------
:class:`Then`
Examples
--------
Simple conditions may be expressed without defining a 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)
alt.Chart(source).mark_point(invalid=None).encode(
x="IMDB_Rating:Q",
y="Rotten_Tomatoes_Rating:Q",
color=alt.when(predicate).then(alt.value("grey")),
)
"""
condition = self._when_then(statement, kwds)
if _is_condition_extra(condition, statement, kwds=kwds):
return Then(_Conditional(condition=condition))
else:
return Then(_Conditional(condition=[condition]))
class Then(SchemaBase, t.Generic[_C]):
"""
Utility class for ``when-then-otherwise`` conditions.
Represents the state after calling :func:`.when().then()`.
This state is a valid condition on its own.
It can be further specified, via multiple chained `when-then` calls,
or finalized with :meth:`Then.otherwise()`.
References
----------
`polars.when <https://docs.pola.rs/py-polars/html/reference/expressions/api/polars.when.html>`__
"""
_schema = {"type": "object"}
def __init__(self, conditions: _Conditional[_C], /) -> None:
super().__init__(**conditions)
self.condition: _C
@overload
def otherwise(self, statement: _TSchemaBase, /, **kwds: Any) -> _TSchemaBase: ...
@overload
def otherwise(self, statement: str, /, **kwds: Any) -> _Conditional[_Condition]: ...
@overload
def otherwise(
self, statement: _Value, /, **kwds: Any
) -> _Conditional[_Conditions]: ...
@overload
def otherwise(
self, statement: dict[str, Any], /, **kwds: Any
) -> _Conditional[Any]: ...
def otherwise(
self, statement: _StatementType, /, **kwds: Any
) -> SchemaBase | _Conditional[Any]:
"""
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<https://altair-viz.github.io/user_guide/encodings/index.html#encoding-shorthands>`__.
**kwds
Additional keyword args are added to the resulting ``dict``.
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)
"""
conditions: _Conditional[Any]
is_extra = functools.partial(_is_condition_extra, kwds=kwds)
if is_extra(self.condition, statement):
current = self.condition
if isinstance(current, list) and len(current) == 1:
# This case is guaranteed to have come from `When` and not `ChainedWhen`
# The `list` isn't needed if we complete the condition here
conditions = _Conditional(condition=current[0]) # pyright: ignore[reportArgumentType]
elif isinstance(current, dict):
if not is_extra(statement):
conditions = self.to_dict()
else:
cond = _reveal_parsed_shorthand(current)
msg = (
f"Only one field may be used within a condition.\n"
f"Shorthand {statement!r} would conflict with {cond!r}\n\n"
f"Use `alt.value({statement!r})` if this is not a shorthand string."
)
raise TypeError(msg)
else:
# Generic message to cover less trivial cases
msg = (
f"Chained conditions cannot be mixed with field conditions.\n"
f"{self!r}\n\n{statement!r}"
)
raise TypeError(msg)
else:
conditions = self.to_dict()
return _parse_otherwise(statement, conditions, kwds)
def when(
self,
predicate: Optional[_PredicateType] = Undefined,
*more_predicates: _ComposablePredicateType,
empty: Optional[bool] = Undefined,
**constraints: _FieldEqualType,
) -> ChainedWhen: