JustinTX commited on
Commit
face7d9
·
verified ·
1 Parent(s): 7847df2

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +106 -0
  2. .venv/lib/python3.13/site-packages/PIL/__pycache__/Image.cpython-313.pyc +3 -0
  3. .venv/lib/python3.13/site-packages/absl_py-2.4.0.dist-info/licenses/AUTHORS +7 -0
  4. .venv/lib/python3.13/site-packages/absl_py-2.4.0.dist-info/licenses/LICENSE +202 -0
  5. .venv/lib/python3.13/site-packages/aiohttp/_websocket/mask.cpython-313-x86_64-linux-gnu.so +3 -0
  6. .venv/lib/python3.13/site-packages/aiohttp/_websocket/reader_c.cpython-313-x86_64-linux-gnu.so +3 -0
  7. .venv/lib/python3.13/site-packages/altair/datasets/__init__.py +183 -0
  8. .venv/lib/python3.13/site-packages/altair/datasets/_cache.py +460 -0
  9. .venv/lib/python3.13/site-packages/altair/datasets/_constraints.py +121 -0
  10. .venv/lib/python3.13/site-packages/altair/datasets/_data.py +358 -0
  11. .venv/lib/python3.13/site-packages/altair/datasets/_exceptions.py +107 -0
  12. .venv/lib/python3.13/site-packages/altair/datasets/_loader.py +359 -0
  13. .venv/lib/python3.13/site-packages/altair/datasets/_reader.py +572 -0
  14. .venv/lib/python3.13/site-packages/altair/datasets/_readimpl.py +511 -0
  15. .venv/lib/python3.13/site-packages/altair/datasets/_typing.py +225 -0
  16. .venv/lib/python3.13/site-packages/altair/expr/__init__.py +2086 -0
  17. .venv/lib/python3.13/site-packages/altair/expr/consts.py +13 -0
  18. .venv/lib/python3.13/site-packages/altair/expr/core.py +292 -0
  19. .venv/lib/python3.13/site-packages/altair/expr/funcs.py +167 -0
  20. .venv/lib/python3.13/site-packages/altair/jupyter/__init__.py +21 -0
  21. .venv/lib/python3.13/site-packages/altair/jupyter/js/README.md +2 -0
  22. .venv/lib/python3.13/site-packages/altair/jupyter/js/index.js +231 -0
  23. .venv/lib/python3.13/site-packages/altair/jupyter/jupyter_chart.py +404 -0
  24. .venv/lib/python3.13/site-packages/altair/typing/__init__.py +96 -0
  25. .venv/lib/python3.13/site-packages/altair/utils/__init__.py +45 -0
  26. .venv/lib/python3.13/site-packages/altair/utils/_dfi_types.py +164 -0
  27. .venv/lib/python3.13/site-packages/altair/utils/_importers.py +106 -0
  28. .venv/lib/python3.13/site-packages/altair/utils/_show.py +75 -0
  29. .venv/lib/python3.13/site-packages/altair/utils/_transformed_data.py +591 -0
  30. .venv/lib/python3.13/site-packages/altair/utils/_vegafusion_data.py +304 -0
  31. .venv/lib/python3.13/site-packages/altair/utils/compiler.py +13 -0
  32. .venv/lib/python3.13/site-packages/altair/utils/core.py +981 -0
  33. .venv/lib/python3.13/site-packages/altair/utils/data.py +435 -0
  34. .venv/lib/python3.13/site-packages/altair/utils/deprecation.py +196 -0
  35. .venv/lib/python3.13/site-packages/altair/utils/display.py +233 -0
  36. .venv/lib/python3.13/site-packages/altair/utils/execeval.py +99 -0
  37. .venv/lib/python3.13/site-packages/altair/utils/html.py +411 -0
  38. .venv/lib/python3.13/site-packages/altair/utils/mimebundle.py +377 -0
  39. .venv/lib/python3.13/site-packages/altair/utils/plugin_registry.py +291 -0
  40. .venv/lib/python3.13/site-packages/altair/utils/save.py +284 -0
  41. .venv/lib/python3.13/site-packages/altair/utils/schemapi.py +1710 -0
  42. .venv/lib/python3.13/site-packages/altair/utils/selection.py +130 -0
  43. .venv/lib/python3.13/site-packages/altair/utils/server.py +151 -0
  44. .venv/lib/python3.13/site-packages/altair/vegalite/__init__.py +2 -0
  45. .venv/lib/python3.13/site-packages/altair/vegalite/api.py +2 -0
  46. .venv/lib/python3.13/site-packages/altair/vegalite/data.py +68 -0
  47. .venv/lib/python3.13/site-packages/altair/vegalite/display.py +17 -0
  48. .venv/lib/python3.13/site-packages/altair/vegalite/schema.py +4 -0
  49. .venv/lib/python3.13/site-packages/altair/vegalite/v6/__init__.py +659 -0
  50. .venv/lib/python3.13/site-packages/altair/vegalite/v6/api.py +0 -0
.gitattributes CHANGED
@@ -605,3 +605,109 @@ py311/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBol.
605
  .venv/lib/python3.13/site-packages/jax/_src/lax/__pycache__/lax.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
606
  .venv/lib/python3.13/site-packages/jax/_src/lax/__pycache__/parallel.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
607
  .venv/lib/python3.13/site-packages/jax/_src/lax/__pycache__/slicing.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
605
  .venv/lib/python3.13/site-packages/jax/_src/lax/__pycache__/lax.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
606
  .venv/lib/python3.13/site-packages/jax/_src/lax/__pycache__/parallel.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
607
  .venv/lib/python3.13/site-packages/jax/_src/lax/__pycache__/slicing.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
608
+ .venv/lib/python3.13/site-packages/jax/_src/lax/__pycache__/linalg.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
609
+ .venv/lib/python3.13/site-packages/jax/_src/lax/control_flow/__pycache__/loops.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
610
+ .venv/lib/python3.13/site-packages/jax/_src/scipy/__pycache__/linalg.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
611
+ .venv/lib/python3.13/site-packages/jax/_src/scipy/__pycache__/special.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
612
+ .venv/lib/python3.13/site-packages/jax/_src/pallas/mosaic/__pycache__/pipeline.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
613
+ .venv/lib/python3.13/site-packages/jax/_src/pallas/mosaic_gpu/__pycache__/primitives.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
614
+ .venv/lib/python3.13/site-packages/jax/_src/pallas/mosaic_gpu/__pycache__/lowering.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
615
+ .venv/lib/python3.13/site-packages/jax/_src/pallas/fuser/__pycache__/block_spec.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
616
+ .venv/lib/python3.13/site-packages/jax/_src/export/__pycache__/shape_poly.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
617
+ .venv/lib/python3.13/site-packages/jax/_src/internal_test_util/__pycache__/test_harnesses.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
618
+ .venv/lib/python3.13/site-packages/jax/_src/pallas/triton/__pycache__/lowering.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
619
+ .venv/lib/python3.13/site-packages/jax/_src/pallas/mosaic/__pycache__/lowering.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
620
+ .venv/lib/python3.13/site-packages/jax/experimental/sparse/__pycache__/bcoo.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
621
+ .venv/lib/python3.13/site-packages/jax/experimental/mosaic/gpu/__pycache__/layout_inference.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
622
+ .venv/lib/python3.13/site-packages/jax/experimental/mosaic/gpu/__pycache__/utils.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
623
+ .venv/lib/python3.13/site-packages/jax/experimental/mosaic/gpu/__pycache__/dialect_lowering.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
624
+ .venv/lib/python3.13/site-packages/jax/experimental/mosaic/gpu/__pycache__/fragmented_array.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
625
+ .venv/lib/python3.13/site-packages/numpy/fft/_pocketfft_umath.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
626
+ .venv/lib/python3.13/site-packages/numpy/_core/_multiarray_tests.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
627
+ .venv/lib/python3.13/site-packages/imageio_ffmpeg/binaries/ffmpeg-linux-x86_64-v7.0.2 filter=lfs diff=lfs merge=lfs -text
628
+ .venv/lib/python3.13/site-packages/numpy/_core/_simd.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
629
+ .venv/lib/python3.13/site-packages/numpy/_core/_multiarray_umath.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
630
+ .venv/lib/python3.13/site-packages/numpy/random/_generator.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
631
+ .venv/lib/python3.13/site-packages/numpy/random/bit_generator.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
632
+ .venv/lib/python3.13/site-packages/numpy/random/_philox.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
633
+ .venv/lib/python3.13/site-packages/numpy/random/_mt19937.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
634
+ .venv/lib/python3.13/site-packages/numpy/random/mtrand.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
635
+ .venv/lib/python3.13/site-packages/numpy/random/_bounded_integers.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
636
+ .venv/lib/python3.13/site-packages/numpy/random/_pcg64.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
637
+ .venv/lib/python3.13/site-packages/numpy/random/_common.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
638
+ .venv/lib/python3.13/site-packages/numpy/linalg/_umath_linalg.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
639
+ .venv/lib/python3.13/site-packages/numpy/linalg/__pycache__/_linalg.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
640
+ .venv/lib/python3.13/site-packages/numpy/f2py/__pycache__/crackfortran.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
641
+ .venv/lib/python3.13/site-packages/numpy/_core/__pycache__/fromnumeric.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
642
+ .venv/lib/python3.13/site-packages/numpy/_core/__pycache__/_add_newdocs.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
643
+ .venv/lib/python3.13/site-packages/numpy/ma/__pycache__/core.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
644
+ .venv/lib/python3.13/site-packages/numpy/testing/_private/__pycache__/utils.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
645
+ .venv/lib/python3.13/site-packages/virtualenv/seed/wheels/embed/setuptools-80.9.0-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
646
+ .venv/lib/python3.13/site-packages/virtualenv/seed/wheels/embed/setuptools-75.3.2-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
647
+ .venv/lib/python3.13/site-packages/virtualenv/seed/wheels/embed/pip-25.0.1-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
648
+ .venv/lib/python3.13/site-packages/virtualenv/seed/wheels/embed/pip-25.3-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text
649
+ .venv/lib/python3.13/site-packages/numpy/lib/__pycache__/_function_base_impl.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
650
+ .venv/lib/python3.13/site-packages/pyparsing/__pycache__/core.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
651
+ .venv/lib/python3.13/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
652
+ .venv/lib/python3.13/site-packages/networkx/drawing/tests/baseline/test_display_complex.png filter=lfs diff=lfs merge=lfs -text
653
+ .venv/lib/python3.13/site-packages/idna/__pycache__/idnadata.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
654
+ .venv/lib/python3.13/site-packages/PIL/__pycache__/Image.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
655
+ .venv/lib/python3.13/site-packages/aiohttp/_websocket/mask.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
656
+ .venv/lib/python3.13/site-packages/aiohttp/_websocket/reader_c.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
657
+ .venv/lib/python3.13/site-packages/sklearn/tree/_criterion.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
658
+ .venv/lib/python3.13/site-packages/sklearn/utils/_seq_dataset.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
659
+ .venv/lib/python3.13/site-packages/sklearn/tree/_splitter.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
660
+ .venv/lib/python3.13/site-packages/sklearn/utils/arrayfuncs.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
661
+ .venv/lib/python3.13/site-packages/sklearn/utils/_typedefs.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
662
+ .venv/lib/python3.13/site-packages/sklearn/utils/sparsefuncs_fast.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
663
+ .venv/lib/python3.13/site-packages/sklearn/utils/_cython_blas.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
664
+ .venv/lib/python3.13/site-packages/sklearn/utils/murmurhash.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
665
+ .venv/lib/python3.13/site-packages/sklearn/utils/_random.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
666
+ .venv/lib/python3.13/site-packages/sklearn/linear_model/_cd_fast.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
667
+ .venv/lib/python3.13/site-packages/sklearn/linear_model/_sag_fast.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
668
+ .venv/lib/python3.13/site-packages/sklearn/metrics/_dist_metrics.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
669
+ .venv/lib/python3.13/site-packages/sklearn/metrics/_pairwise_fast.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
670
+ .venv/lib/python3.13/site-packages/sklearn/tree/_utils.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
671
+ .venv/lib/python3.13/site-packages/sklearn/tree/_partitioner.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
672
+ .venv/lib/python3.13/site-packages/sklearn/tree/_tree.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
673
+ .venv/lib/python3.13/site-packages/sklearn/utils/_fast_dict.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
674
+ .venv/lib/python3.13/site-packages/sklearn/utils/_vector_sentinel.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
675
+ .venv/lib/python3.13/site-packages/sklearn/linear_model/_sgd_fast.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
676
+ .venv/lib/python3.13/site-packages/sklearn/manifold/_barnes_hut_tsne.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
677
+ .venv/lib/python3.13/site-packages/sklearn/preprocessing/_target_encoder_fast.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
678
+ .venv/lib/python3.13/site-packages/sklearn/preprocessing/_csr_polynomial_expansion.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
679
+ .venv/lib/python3.13/site-packages/sklearn/_loss/_loss.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
680
+ .venv/lib/python3.13/site-packages/sklearn/svm/_libsvm_sparse.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
681
+ .venv/lib/python3.13/site-packages/sklearn/svm/_liblinear.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
682
+ .venv/lib/python3.13/site-packages/sklearn/svm/_libsvm.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
683
+ .venv/lib/python3.13/site-packages/sklearn/datasets/_svmlight_format_fast.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
684
+ .venv/lib/python3.13/site-packages/sklearn/decomposition/_online_lda_fast.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
685
+ .venv/lib/python3.13/site-packages/sklearn/cluster/_k_means_lloyd.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
686
+ .venv/lib/python3.13/site-packages/sklearn/cluster/_k_means_minibatch.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
687
+ .venv/lib/python3.13/site-packages/sklearn/cluster/_hierarchical_fast.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
688
+ .venv/lib/python3.13/site-packages/sklearn/cluster/_k_means_common.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
689
+ .venv/lib/python3.13/site-packages/sklearn/ensemble/_gradient_boosting.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
690
+ .venv/lib/python3.13/site-packages/sklearn/cluster/_k_means_elkan.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
691
+ .venv/lib/python3.13/site-packages/sklearn/neighbors/_ball_tree.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
692
+ .venv/lib/python3.13/site-packages/sklearn/neighbors/_quad_tree.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
693
+ .venv/lib/python3.13/site-packages/sklearn/neighbors/_kd_tree.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
694
+ .venv/lib/python3.13/site-packages/sklearn/model_selection/__pycache__/_split.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
695
+ .venv/lib/python3.13/site-packages/sklearn/ensemble/_hist_gradient_boosting/histogram.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
696
+ .venv/lib/python3.13/site-packages/sklearn/ensemble/_hist_gradient_boosting/_predictor.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
697
+ .venv/lib/python3.13/site-packages/sklearn/ensemble/_hist_gradient_boosting/splitting.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
698
+ .venv/lib/python3.13/site-packages/sklearn/cluster/_hdbscan/_reachability.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
699
+ .venv/lib/python3.13/site-packages/sklearn/cluster/_hdbscan/_tree.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
700
+ .venv/lib/python3.13/site-packages/sklearn/cluster/_hdbscan/_linkage.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
701
+ .venv/lib/python3.13/site-packages/sklearn/datasets/images/china.jpg filter=lfs diff=lfs merge=lfs -text
702
+ .venv/lib/python3.13/site-packages/sklearn/datasets/images/flower.jpg filter=lfs diff=lfs merge=lfs -text
703
+ .venv/lib/python3.13/site-packages/sklearn/linear_model/__pycache__/_coordinate_descent.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
704
+ .venv/lib/python3.13/site-packages/sklearn/linear_model/__pycache__/_ridge.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
705
+ .venv/lib/python3.13/site-packages/sklearn/utils/__pycache__/validation.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
706
+ .venv/lib/python3.13/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
707
+ .venv/lib/python3.13/site-packages/sklearn/preprocessing/__pycache__/_data.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
708
+ .venv/lib/python3.13/site-packages/sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
709
+ .venv/lib/python3.13/site-packages/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
710
+ .venv/lib/python3.13/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors_classmode.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
711
+ .venv/lib/python3.13/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
712
+ .venv/lib/python3.13/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin_classmode.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
713
+ .venv/lib/python3.13/site-packages/sklearn/metrics/__pycache__/_classification.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.13/site-packages/PIL/__pycache__/Image.cpython-313.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e24ba70bfb1277dca909aec7222b556d475a836f63a3d82c002c4909dd07875
3
+ size 172221
.venv/lib/python3.13/site-packages/absl_py-2.4.0.dist-info/licenses/AUTHORS ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # This is the list of Abseil authors for copyright purposes.
2
+ #
3
+ # This does not necessarily list everyone who has contributed code, since in
4
+ # some cases, their employer may be the copyright holder. To see the full list
5
+ # of contributors, see the revision history in source control.
6
+
7
+ Google Inc.
.venv/lib/python3.13/site-packages/absl_py-2.4.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
.venv/lib/python3.13/site-packages/aiohttp/_websocket/mask.cpython-313-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7b61199dcc3562746e2109fd3bff9e652a2c7607ba8b0a86d7c72475ea9dc759
3
+ size 246592
.venv/lib/python3.13/site-packages/aiohttp/_websocket/reader_c.cpython-313-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:92acbf3628015c2543e35d47394766064bc45af765d887181b8802db8ba297c8
3
+ size 1821608
.venv/lib/python3.13/site-packages/altair/datasets/__init__.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Load example datasets *remotely* from `vega-datasets`_.
3
+
4
+ Provides **70+** datasets, used throughout our `Example Gallery`_.
5
+
6
+ You can learn more about each dataset at `datapackage.md`_.
7
+
8
+ Examples
9
+ --------
10
+ **Primary Interface - Data Object**::
11
+
12
+ from altair.datasets import data
13
+
14
+ # Load with default engine (pandas)
15
+ cars_df = data.cars()
16
+
17
+ # Load with specific engine
18
+ cars_polars = data.cars(engine="polars")
19
+ cars_pyarrow = data.cars(engine="pyarrow")
20
+
21
+ # Get URL
22
+ cars_url = data.cars.url
23
+
24
+ # Set default engine for all datasets
25
+ data.set_default_engine("polars")
26
+ movies_df = data.movies() # Uses polars engine
27
+
28
+ # List available datasets
29
+ available_datasets = data.list_datasets()
30
+
31
+ **Expert Interface - Loader**::
32
+
33
+ from altair.datasets import Loader
34
+
35
+ load = Loader.from_backend("polars")
36
+ load("penguins")
37
+ load.url("penguins")
38
+
39
+ This method also provides *precise* <kbd>Tab</kbd> completions on the returned object::
40
+
41
+ load("cars").<Tab>
42
+ # bottom_k
43
+ # drop
44
+ # drop_in_place
45
+ # drop_nans
46
+ # dtypes
47
+ # ...
48
+
49
+ **Expert Interface - Direct Functions**::
50
+
51
+ from altair.datasets import load, url
52
+
53
+ # Load a dataset
54
+ cars_df = load("cars", backend="polars")
55
+
56
+ # Get dataset URL
57
+ cars_url = url("cars")
58
+
59
+ .. note::
60
+ Requires installation of either `polars`_, `pandas`_, or `pyarrow`_.
61
+
62
+ .. _vega-datasets:
63
+ https://github.com/vega/vega-datasets
64
+ .. _Example Gallery:
65
+ https://altair-viz.github.io/gallery/index.html#example-gallery
66
+ .. _datapackage.md:
67
+ https://github.com/vega/vega-datasets/blob/main/datapackage.md
68
+ .. _polars:
69
+ https://docs.pola.rs/user-guide/installation/
70
+ .. _pandas:
71
+ https://pandas.pydata.org/docs/getting_started/install.html
72
+ .. _pyarrow:
73
+ https://arrow.apache.org/docs/python/install.html
74
+ """
75
+
76
+ from __future__ import annotations
77
+
78
+ from typing import TYPE_CHECKING
79
+
80
+ from altair.datasets._loader import Loader as Loader
81
+
82
+ if TYPE_CHECKING:
83
+ import sys
84
+ from typing import Any
85
+
86
+ if sys.version_info >= (3, 11):
87
+ from typing import LiteralString
88
+ else:
89
+ from typing_extensions import LiteralString
90
+
91
+ from altair.datasets._data import DataObject
92
+ from altair.datasets._loader import _Load
93
+ from altair.datasets._typing import Dataset, Extension
94
+
95
+
96
+ load: _Load[Any, Any]
97
+ """
98
+ Get a remote dataset and load as tabular data.
99
+
100
+ This is an expert interface. For most users, the data object interface is recommended::
101
+
102
+ from altair.datasets import data
103
+ cars = data.cars(engine="polars")
104
+
105
+ For full <kbd>Tab</kbd> completions, instead use::
106
+
107
+ from altair.datasets import Loader
108
+ load = Loader.from_backend("polars")
109
+ cars = load("cars")
110
+ movies = load("movies")
111
+
112
+ Alternatively, specify ``backend`` during a call::
113
+
114
+ from altair.datasets import load
115
+ cars = load("cars", backend="polars")
116
+ movies = load("movies", backend="polars")
117
+ """
118
+
119
+ data: DataObject
120
+
121
+
122
+ def url(
123
+ name: Dataset | LiteralString,
124
+ suffix: Extension | None = None,
125
+ /,
126
+ ) -> str:
127
+ """
128
+ Return the address of a remote dataset.
129
+
130
+ This is an expert interface. For most users, the data object interface is recommended::
131
+
132
+ from altair.datasets import data
133
+
134
+ cars_url = data.cars.url
135
+
136
+ Parameters
137
+ ----------
138
+ name
139
+ Name of the dataset/`Path.stem`_.
140
+ suffix
141
+ File extension/`Path.suffix`_.
142
+
143
+ .. note::
144
+ Only needed if ``name`` is available in multiple formats.
145
+
146
+ Returns
147
+ -------
148
+ ``str``
149
+
150
+ .. _Path.stem:
151
+ https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem
152
+ .. _Path.suffix:
153
+ https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.suffix
154
+ """
155
+ from altair.datasets._exceptions import AltairDatasetsError
156
+
157
+ try:
158
+ from altair.datasets._loader import load
159
+
160
+ url = load.url(name, suffix)
161
+ except AltairDatasetsError:
162
+ from altair.datasets._cache import csv_cache
163
+
164
+ url = csv_cache.url(name)
165
+
166
+ return url
167
+
168
+
169
+ def __getattr__(name):
170
+ if name == "data":
171
+ from altair.datasets._data import data
172
+
173
+ return data
174
+ elif name == "load":
175
+ from altair.datasets._loader import load
176
+
177
+ return load
178
+ elif name == "__all__":
179
+ # Define __all__ dynamically to avoid ruff errors
180
+ return ["Loader", "data", "load", "url"]
181
+ else:
182
+ msg = f"module {__name__!r} has no attribute {name!r}"
183
+ raise AttributeError(msg)
.venv/lib/python3.13/site-packages/altair/datasets/_cache.py ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ from collections import defaultdict
6
+ from importlib.util import find_spec
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING, ClassVar, TypeVar, cast
9
+
10
+ import narwhals.stable.v1 as nw
11
+
12
+ from altair.datasets._exceptions import AltairDatasetsError
13
+
14
+ if sys.version_info >= (3, 12):
15
+ from typing import Protocol
16
+ else:
17
+ from typing_extensions import Protocol
18
+
19
+ if TYPE_CHECKING:
20
+ from collections.abc import (
21
+ Iterable,
22
+ Iterator,
23
+ Mapping,
24
+ MutableMapping,
25
+ MutableSequence,
26
+ Sequence,
27
+ )
28
+ from io import IOBase
29
+ from typing import Any, Final
30
+ from urllib.request import OpenerDirector
31
+
32
+ from _typeshed import StrPath
33
+ from narwhals.stable.v1.dtypes import DType
34
+ from narwhals.stable.v1.typing import IntoExpr
35
+
36
+ from altair.datasets._typing import Dataset, Metadata
37
+
38
+ if sys.version_info >= (3, 12):
39
+ from typing import Unpack
40
+ else:
41
+ from typing_extensions import Unpack
42
+ if sys.version_info >= (3, 11):
43
+ from typing import LiteralString
44
+ else:
45
+ from typing_extensions import LiteralString
46
+ if sys.version_info >= (3, 10):
47
+ from typing import TypeAlias
48
+ else:
49
+ from typing_extensions import TypeAlias
50
+ from altair.datasets._typing import FlFieldStr
51
+ from altair.vegalite.v6.schema._typing import OneOrSeq
52
+
53
+ _Dataset: TypeAlias = "Dataset | LiteralString"
54
+ _FlSchema: TypeAlias = Mapping[str, FlFieldStr]
55
+
56
+ __all__ = ["CsvCache", "DatasetCache", "SchemaCache", "csv_cache"]
57
+
58
+
59
+ _KT = TypeVar("_KT")
60
+ _VT = TypeVar("_VT")
61
+ _T = TypeVar("_T")
62
+
63
+ _METADATA_DIR: Final[Path] = Path(__file__).parent / "_metadata"
64
+
65
+ _DTYPE_TO_FIELD: Mapping[type[DType], FlFieldStr] = {
66
+ nw.Int64: "integer",
67
+ nw.Float64: "number",
68
+ nw.Boolean: "boolean",
69
+ nw.String: "string",
70
+ nw.Struct: "object",
71
+ nw.List: "array",
72
+ nw.Date: "date",
73
+ nw.Datetime: "datetime",
74
+ nw.Duration: "duration",
75
+ # nw.Time: "time" (Not Implemented, but we don't have any cases using it anyway)
76
+ }
77
+ """
78
+ Similar to `pl.datatypes.convert.dtype_to_ffiname`_.
79
+
80
+ But using `narwhals.dtypes`_ to the string repr of ``frictionless`` `Field Types`_.
81
+
82
+ .. _pl.datatypes.convert.dtype_to_ffiname:
83
+ https://github.com/pola-rs/polars/blob/85d078c066860e012f5e7e611558e6382b811b82/py-polars/polars/datatypes/convert.py#L139-L165
84
+ .. _Field Types:
85
+ https://datapackage.org/standard/table-schema/#field-types
86
+ .. _narwhals.dtypes:
87
+ https://narwhals-dev.github.io/narwhals/api-reference/dtypes/
88
+ """
89
+
90
+ _FIELD_TO_DTYPE: Mapping[FlFieldStr, type[DType]] = {
91
+ v: k for k, v in _DTYPE_TO_FIELD.items()
92
+ }
93
+
94
+
95
+ def _iter_metadata(df: nw.DataFrame[Any], /) -> Iterator[Metadata]:
96
+ """
97
+ Yield rows from ``df``, where each represents a dataset.
98
+
99
+ See Also
100
+ --------
101
+ ``altair.datasets._typing.Metadata``
102
+ """
103
+ yield from cast("Iterator[Metadata]", df.iter_rows(named=True))
104
+
105
+
106
+ class CompressedCache(Protocol[_KT, _VT]):
107
+ fp: Path
108
+ _mapping: MutableMapping[_KT, _VT]
109
+
110
+ def read(self) -> Any: ...
111
+ def __getitem__(self, key: _KT, /) -> _VT: ...
112
+
113
+ def __enter__(self) -> IOBase:
114
+ import gzip
115
+
116
+ return gzip.open(self.fp, mode="rb").__enter__()
117
+
118
+ def __exit__(self, *args) -> None:
119
+ return
120
+
121
+ def get(self, key: _KT, default: _T, /) -> _VT | _T:
122
+ return self.mapping.get(key, default)
123
+
124
+ @property
125
+ def mapping(self) -> MutableMapping[_KT, _VT]:
126
+ if not self._mapping:
127
+ self._mapping.update(self.read())
128
+ return self._mapping
129
+
130
+
131
+ class CsvCache(CompressedCache["_Dataset", "Metadata"]):
132
+ """
133
+ `csv`_, `gzip`_ -based, lazy metadata lookup.
134
+
135
+ Used as a fallback for 2 scenarios:
136
+
137
+ 1. ``url(...)`` when no optional dependencies are installed.
138
+ 2. ``(Loader|load)(...)`` when the backend is missing* ``.parquet`` support.
139
+
140
+ Notes
141
+ -----
142
+ *All backends *can* support ``.parquet``, but ``pandas`` requires an optional dependency.
143
+
144
+ .. _csv:
145
+ https://docs.python.org/3/library/csv.html
146
+ .. _gzip:
147
+ https://docs.python.org/3/library/gzip.html
148
+ """
149
+
150
+ fp = _METADATA_DIR / "metadata.csv.gz"
151
+
152
+ def __init__(
153
+ self,
154
+ *,
155
+ tp: type[MutableMapping[_Dataset, Metadata]] = dict["_Dataset", "Metadata"],
156
+ ) -> None:
157
+ self._mapping: MutableMapping[_Dataset, Metadata] = tp()
158
+ self._rotated: MutableMapping[str, MutableSequence[Any]] = defaultdict(list)
159
+
160
+ def read(self) -> Any:
161
+ import csv
162
+
163
+ with self as f:
164
+ b_lines = f.readlines()
165
+ reader = csv.reader((bs.decode() for bs in b_lines), dialect=csv.unix_dialect)
166
+ header = tuple(next(reader))
167
+ return {row[0]: dict(self._convert_row(header, row)) for row in reader}
168
+
169
+ def _convert_row(
170
+ self, header: Iterable[str], row: Iterable[str], /
171
+ ) -> Iterator[tuple[str, Any]]:
172
+ map_tf = {"true": True, "false": False}
173
+ for col, value in zip(header, row):
174
+ if col.startswith(("is_", "has_")):
175
+ yield col, map_tf[value]
176
+ elif col == "bytes":
177
+ yield col, int(value)
178
+ else:
179
+ yield col, value
180
+
181
+ @property
182
+ def rotated(self) -> Mapping[str, Sequence[Any]]:
183
+ """Columnar view."""
184
+ if not self._rotated:
185
+ for record in self.mapping.values():
186
+ for k, v in record.items():
187
+ self._rotated[k].append(v)
188
+ return self._rotated
189
+
190
+ def __getitem__(self, key: _Dataset, /) -> Metadata:
191
+ if meta := self.get(key, None):
192
+ return meta
193
+ msg = f"{key!r} does not refer to a known dataset."
194
+ raise TypeError(msg)
195
+
196
+ def url(self, name: _Dataset, /) -> str:
197
+ meta = self[name]
198
+ if meta["suffix"] == ".parquet" and not find_spec("vegafusion"):
199
+ raise AltairDatasetsError.from_url(meta)
200
+ return meta["url"]
201
+
202
+ def __repr__(self) -> str:
203
+ return f"<{type(self).__name__}: {'COLLECTED' if self._mapping else 'READY'}>"
204
+
205
+
206
+ class SchemaCache(CompressedCache["_Dataset", "_FlSchema"]):
207
+ """
208
+ `json`_, `gzip`_ -based, lazy schema lookup.
209
+
210
+ - Primarily benefits ``pandas``, which needs some help identifying **temporal** columns.
211
+ - Utilizes `data package`_ schema types.
212
+ - All methods return falsy containers instead of exceptions
213
+
214
+ .. _json:
215
+ https://docs.python.org/3/library/json.html
216
+ .. _gzip:
217
+ https://docs.python.org/3/library/gzip.html
218
+ .. _data package:
219
+ https://github.com/vega/vega-datasets/pull/631
220
+ """
221
+
222
+ fp = _METADATA_DIR / "schemas.json.gz"
223
+
224
+ def __init__(
225
+ self,
226
+ *,
227
+ tp: type[MutableMapping[_Dataset, _FlSchema]] = dict["_Dataset", "_FlSchema"],
228
+ implementation: nw.Implementation = nw.Implementation.UNKNOWN,
229
+ ) -> None:
230
+ self._mapping: MutableMapping[_Dataset, _FlSchema] = tp()
231
+ self._implementation: nw.Implementation = implementation
232
+
233
+ def read(self) -> Any:
234
+ import json
235
+
236
+ with self as f:
237
+ return json.load(f)
238
+
239
+ def __getitem__(self, key: _Dataset, /) -> _FlSchema:
240
+ return self.get(key, {})
241
+
242
+ def by_dtype(self, name: _Dataset, *dtypes: type[DType]) -> list[str]:
243
+ """
244
+ Return column names specfied in ``name``'s schema.
245
+
246
+ Parameters
247
+ ----------
248
+ name
249
+ Dataset name.
250
+ *dtypes
251
+ Optionally, only return columns matching the given data type(s).
252
+ """
253
+ if (match := self[name]) and dtypes:
254
+ include = {_DTYPE_TO_FIELD[tp] for tp in dtypes}
255
+ return [col for col, tp_str in match.items() if tp_str in include]
256
+ else:
257
+ return list(match)
258
+
259
+ def is_active(self) -> bool:
260
+ return self._implementation in {
261
+ nw.Implementation.PANDAS,
262
+ nw.Implementation.PYARROW,
263
+ nw.Implementation.MODIN,
264
+ nw.Implementation.PYARROW,
265
+ }
266
+
267
+ def schema(self, name: _Dataset, /) -> nw.Schema:
268
+ it = ((col, _FIELD_TO_DTYPE[tp_str]()) for col, tp_str in self[name].items())
269
+ return nw.Schema(it)
270
+
271
+ def schema_kwds(self, meta: Metadata, /) -> dict[str, Any]:
272
+ name: Any = meta["dataset_name"]
273
+ if self.is_active() and (self[name]):
274
+ suffix = meta["suffix"]
275
+ if self._implementation.is_pandas_like():
276
+ if cols := self.by_dtype(name, nw.Date, nw.Datetime):
277
+ if suffix == ".json":
278
+ return {"convert_dates": cols}
279
+ elif suffix in {".csv", ".tsv"}:
280
+ return {"parse_dates": cols}
281
+ else:
282
+ schema = self.schema(name).to_arrow()
283
+ if suffix in {".csv", ".tsv"}:
284
+ from pyarrow.csv import ConvertOptions
285
+
286
+ # For pyarrow CSV reading, use the schema as intended
287
+ # This will fail for non-ISO date formats, but that's the correct behavior
288
+ # Users can handle this by using a different backend or converting dates manually
289
+ return {"convert_options": ConvertOptions(column_types=schema)} # pyright: ignore[reportCallIssue]
290
+ elif suffix == ".parquet":
291
+ return {"schema": schema}
292
+
293
+ return {}
294
+
295
+
296
+ class _SupportsScanMetadata(Protocol):
297
+ _opener: ClassVar[OpenerDirector]
298
+
299
+ def _scan_metadata(
300
+ self, *predicates: OneOrSeq[IntoExpr], **constraints: Unpack[Metadata]
301
+ ) -> nw.LazyFrame[Any]: ...
302
+
303
+
304
+ class DatasetCache:
305
+ """Opt-out caching of remote dataset requests."""
306
+
307
+ _ENV_VAR: ClassVar[LiteralString] = "ALTAIR_DATASETS_DIR"
308
+ _XDG_CACHE: ClassVar[Path] = (
309
+ Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "altair"
310
+ ).resolve()
311
+
312
+ def __init__(self, reader: _SupportsScanMetadata, /) -> None:
313
+ self._rd: _SupportsScanMetadata = reader
314
+
315
+ def clear(self) -> None:
316
+ """Delete all previously cached datasets."""
317
+ self._ensure_active()
318
+ if self.is_empty():
319
+ return None
320
+ ser = (
321
+ self._rd._scan_metadata()
322
+ .select("sha", "suffix")
323
+ .unique("sha")
324
+ .select(nw.concat_str("sha", "suffix").alias("sha_suffix"))
325
+ .collect()
326
+ .get_column("sha_suffix")
327
+ )
328
+ names = set[str](ser.to_list())
329
+ for fp in self:
330
+ if fp.name in names:
331
+ fp.unlink()
332
+
333
+ def download_all(self) -> None:
334
+ """
335
+ Download any missing datasets for latest version.
336
+
337
+ Requires **30-50MB** of disk-space.
338
+ """
339
+ stems = tuple(fp.stem for fp in self)
340
+ predicates = (~(nw.col("sha").is_in(stems)),) if stems else ()
341
+ frame = (
342
+ self._rd._scan_metadata(*predicates, is_image=False)
343
+ .select("sha", "suffix", "url")
344
+ .unique("sha")
345
+ .collect()
346
+ )
347
+ if frame.is_empty():
348
+ print("Already downloaded all datasets")
349
+ return None
350
+ print(f"Downloading {len(frame)} missing datasets...")
351
+ for meta in _iter_metadata(frame):
352
+ self._download_one(meta["url"], self.path_meta(meta))
353
+ print("Finished downloads")
354
+ return None
355
+
356
+ def _maybe_download(self, meta: Metadata, /) -> Path:
357
+ fp = self.path_meta(meta)
358
+ return (
359
+ fp
360
+ if (fp.exists() and fp.stat().st_size)
361
+ else self._download_one(meta["url"], fp)
362
+ )
363
+
364
+ def _download_one(self, url: str, fp: Path, /) -> Path:
365
+ with self._rd._opener.open(url) as f:
366
+ fp.touch()
367
+ fp.write_bytes(f.read())
368
+ return fp
369
+
370
+ @property
371
+ def path(self) -> Path:
372
+ """
373
+ Returns path to datasets cache.
374
+
375
+ Defaults to (`XDG_CACHE_HOME`_)::
376
+
377
+ "$XDG_CACHE_HOME/altair/"
378
+
379
+ But can be configured using the environment variable::
380
+
381
+ "$ALTAIR_DATASETS_DIR"
382
+
383
+ You can set this for the current session via::
384
+
385
+ from pathlib import Path
386
+ from altair.datasets import load
387
+
388
+ load.cache.path = Path.home() / ".altair_cache"
389
+
390
+ load.cache.path.relative_to(Path.home()).as_posix()
391
+ ".altair_cache"
392
+
393
+ You can *later* disable caching via::
394
+
395
+ load.cache.path = None
396
+
397
+ .. _XDG_CACHE_HOME:
398
+ https://specifications.freedesktop.org/basedir-spec/latest/#variables
399
+ """
400
+ self._ensure_active()
401
+ fp = Path(usr) if (usr := os.environ.get(self._ENV_VAR)) else self._XDG_CACHE
402
+ fp.mkdir(parents=True, exist_ok=True)
403
+ return fp
404
+
405
+ @path.setter
406
+ def path(self, source: StrPath | None, /) -> None:
407
+ if source is not None:
408
+ os.environ[self._ENV_VAR] = str(Path(source).resolve())
409
+ else:
410
+ os.environ[self._ENV_VAR] = ""
411
+
412
+ def path_meta(self, meta: Metadata, /) -> Path:
413
+ return self.path / (meta["sha"] + meta["suffix"])
414
+
415
+ def __iter__(self) -> Iterator[Path]:
416
+ yield from self.path.iterdir()
417
+
418
+ def __repr__(self) -> str:
419
+ name = type(self).__name__
420
+ if self.is_not_active():
421
+ return f"{name}<UNSET>"
422
+ else:
423
+ return f"{name}<{self.path.as_posix()!r}>"
424
+
425
+ def is_active(self) -> bool:
426
+ return not self.is_not_active()
427
+
428
+ def is_not_active(self) -> bool:
429
+ return os.environ.get(self._ENV_VAR) == ""
430
+
431
+ def is_empty(self) -> bool:
432
+ """Cache is active, but no files are stored in ``self.path``."""
433
+ return next(iter(self), None) is None
434
+
435
+ def _ensure_active(self) -> None:
436
+ if self.is_not_active():
437
+ msg = (
438
+ f"Cache is unset.\n"
439
+ f"To enable dataset caching, set the environment variable:\n"
440
+ f" {self._ENV_VAR!r}\n\n"
441
+ f"You can set this for the current session via:\n"
442
+ f" from pathlib import Path\n"
443
+ f" from altair.datasets import load\n\n"
444
+ f" load.cache.path = Path.home() / '.altair_cache'"
445
+ )
446
+ raise ValueError(msg)
447
+
448
+
449
+ csv_cache: CsvCache
450
+
451
+
452
+ def __getattr__(name):
453
+ if name == "csv_cache":
454
+ global csv_cache
455
+ csv_cache = CsvCache()
456
+ return csv_cache
457
+
458
+ else:
459
+ msg = f"module {__name__!r} has no attribute {name!r}"
460
+ raise AttributeError(msg)
.venv/lib/python3.13/site-packages/altair/datasets/_constraints.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Set-like guards for matching metadata to an implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Set
6
+ from itertools import chain
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ from narwhals.stable import v1 as nw
10
+
11
+ if TYPE_CHECKING:
12
+ import sys
13
+ from collections.abc import Iterable, Iterator
14
+
15
+ from altair.datasets._typing import Metadata
16
+
17
+ if sys.version_info >= (3, 12):
18
+ from typing import Unpack
19
+ else:
20
+ from typing_extensions import Unpack
21
+ if sys.version_info >= (3, 10):
22
+ from typing import TypeAlias
23
+ else:
24
+ from typing_extensions import TypeAlias
25
+
26
+ __all__ = [
27
+ "Items",
28
+ "MetaIs",
29
+ "is_arrow",
30
+ "is_csv",
31
+ "is_json",
32
+ "is_meta",
33
+ "is_not_tabular",
34
+ "is_parquet",
35
+ "is_spatial",
36
+ "is_topo",
37
+ "is_tsv",
38
+ ]
39
+
40
+ Items: TypeAlias = Set[tuple[str, Any]]
41
+
42
+
43
+ class MetaIs(Set[tuple[str, Any]]):
44
+ _requires: frozenset[tuple[str, Any]]
45
+
46
+ def __init__(self, kwds: frozenset[tuple[str, Any]], /) -> None:
47
+ object.__setattr__(self, "_requires", kwds)
48
+
49
+ @classmethod
50
+ def from_metadata(cls, meta: Metadata, /) -> MetaIs:
51
+ return cls(frozenset(meta.items()))
52
+
53
+ def to_metadata(self) -> Metadata:
54
+ if TYPE_CHECKING:
55
+
56
+ def collect(**kwds: Unpack[Metadata]) -> Metadata:
57
+ return kwds
58
+
59
+ return collect(**dict(self))
60
+ return dict(self)
61
+
62
+ def to_expr(self) -> nw.Expr:
63
+ """Convert constraint into a narwhals expression."""
64
+ if not self:
65
+ msg = f"Unable to convert an empty set to an expression:\n\n{self!r}"
66
+ raise TypeError(msg)
67
+ return nw.all_horizontal(nw.col(name) == val for name, val in self)
68
+
69
+ def isdisjoint(self, other: Iterable[Any]) -> bool:
70
+ return super().isdisjoint(other)
71
+
72
+ def issubset(self, other: Iterable[Any]) -> bool:
73
+ return self._requires.issubset(other)
74
+
75
+ def __call__(self, meta: Items, /) -> bool:
76
+ return self._requires <= meta
77
+
78
+ def __hash__(self) -> int:
79
+ return hash(self._requires)
80
+
81
+ def __contains__(self, x: object) -> bool:
82
+ return self._requires.__contains__(x)
83
+
84
+ def __iter__(self) -> Iterator[tuple[str, Any]]:
85
+ yield from self._requires
86
+
87
+ def __len__(self) -> int:
88
+ return self._requires.__len__()
89
+
90
+ def __setattr__(self, name: str, value: Any):
91
+ msg = (
92
+ f"{type(self).__name__!r} is immutable.\n"
93
+ f"Could not assign self.{name} = {value}"
94
+ )
95
+ raise TypeError(msg)
96
+
97
+ def __repr__(self) -> str:
98
+ items = dict(self)
99
+ if not items:
100
+ contents = "<placeholder>"
101
+ elif suffix := items.pop("suffix", None):
102
+ contents = ", ".join(
103
+ chain([f"'*{suffix}'"], (f"{k}={v!r}" for k, v in items.items()))
104
+ )
105
+ else:
106
+ contents = ", ".join(f"{k}={v!r}" for k, v in items.items())
107
+ return f"is_meta({contents})"
108
+
109
+
110
+ def is_meta(**kwds: Unpack[Metadata]) -> MetaIs:
111
+ return MetaIs.from_metadata(kwds)
112
+
113
+
114
+ is_csv = is_meta(suffix=".csv")
115
+ is_json = is_meta(suffix=".json")
116
+ is_tsv = is_meta(suffix=".tsv")
117
+ is_arrow = is_meta(suffix=".arrow")
118
+ is_parquet = is_meta(suffix=".parquet")
119
+ is_spatial = is_meta(is_spatial=True)
120
+ is_topo = is_meta(is_topo=True)
121
+ is_not_tabular = is_meta(is_tabular=False)
.venv/lib/python3.13/site-packages/altair/datasets/_data.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Data object interface for Altair datasets.
3
+
4
+ This module provides a `data` object that allows accessing datasets as attributes
5
+ and calling them with backend options, similar to the vega_datasets interface.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import typing as t
11
+
12
+ from altair.datasets._loader import Loader
13
+
14
+ if t.TYPE_CHECKING:
15
+ from typing_extensions import LiteralString
16
+
17
+ import pandas as pd
18
+ import polars as pl
19
+ import pyarrow as pa
20
+
21
+ from altair.datasets._reader import _Backend
22
+ from altair.datasets._typing import Dataset
23
+
24
+
25
+ class DatasetAccessor:
26
+ """
27
+ Accessor for individual datasets that can be called with backend options.
28
+
29
+ This object provides access to a specific dataset with support for
30
+ different backends and autocompletion.
31
+
32
+ Call this object to load the dataset:
33
+ dataset_accessor(engine="polars", **kwds)
34
+
35
+ Parameters for __call__:
36
+ engine : {"polars", "pandas", "pandas[pyarrow]", "pyarrow"}, optional
37
+ The backend to use for loading the dataset.
38
+ **kwds : Any
39
+ Additional arguments passed to the loader.
40
+
41
+ Examples
42
+ --------
43
+ >>> from altair.datasets import data
44
+ >>>
45
+ >>> # Load with default backend
46
+ >>> cars_df = data.cars()
47
+ >>>
48
+ >>> # Load with specific backend
49
+ >>> cars_polars = data.cars(engine="polars")
50
+ >>> cars_pandas = data.cars(engine="pandas")
51
+ >>> # Note: pandas[pyarrow] backend requires pyarrow package
52
+ >>>
53
+ >>> # Get URL
54
+ >>> url = data.cars.url
55
+ >>>
56
+ >>> # Use explicit load method
57
+ >>> cars_df = data.cars.load(engine="polars")
58
+ """
59
+
60
+ def __init__(self, name: Dataset, backend: _Backend = "pandas") -> None:
61
+ import inspect
62
+
63
+ self._name: Dataset = name
64
+ self._backend: _Backend = backend
65
+ self._prev_loader: Loader[t.Any, t.Any]
66
+ self.__signature__ = inspect.signature(self._call_impl)
67
+
68
+ docstring = f"""Load the '{name}' dataset.
69
+
70
+ Parameters
71
+ ----------
72
+ engine : {{"polars", "pandas", "pandas[pyarrow]", "pyarrow"}}, optional
73
+ The backend to use for loading the dataset.
74
+ **kwds : Any
75
+ Additional arguments passed to the loader.
76
+
77
+ Returns
78
+ -------
79
+ DataFrame or Table
80
+ The loaded dataset.
81
+
82
+ Examples
83
+ --------
84
+ >>> data.{name}() # Load with default backend
85
+ >>> data.{name}(engine="polars") # Load with specific backend
86
+ >>> data.{name}.url # Get dataset URL
87
+ >>> data.{name}.load(engine="polars") # Explicit load method
88
+ """
89
+
90
+ self.__doc__ = docstring
91
+
92
+ def _call_impl(
93
+ self,
94
+ *,
95
+ engine: _Backend | None = None,
96
+ **kwds: t.Any,
97
+ ) -> t.Any:
98
+ load = Loader.from_backend(engine) if engine else self._loader
99
+ return load(self._name, **kwds)
100
+
101
+ @property
102
+ def _loader(self) -> Loader[t.Any, t.Any]:
103
+ if hasattr(self, "_prev_loader"):
104
+ return self._prev_loader
105
+ self._prev_loader = Loader.from_backend(self._backend)
106
+ return self._prev_loader
107
+
108
+ @_loader.setter
109
+ def _loader(self, value: Loader[t.Any, t.Any]) -> None:
110
+ self._prev_loader = value
111
+
112
+ @property
113
+ def url(self) -> str:
114
+ """
115
+ Get the URL for this dataset.
116
+
117
+ Returns
118
+ -------
119
+ str
120
+ The URL of the dataset.
121
+
122
+ Examples
123
+ --------
124
+ >>> from altair.datasets import data
125
+ >>> cars_url = data.cars.url
126
+ >>> print(cars_url)
127
+ https://cdn.jsdelivr.net/npm/vega-datasets@v3.2.1/data/cars.json
128
+ """
129
+ return self._loader.url(self._name)
130
+
131
+ def load(self, *, engine: _Backend | None = None, **kwds: t.Any) -> t.Any:
132
+ """
133
+ Load the dataset with the specified engine.
134
+
135
+ This method provides the same functionality as calling the accessor directly,
136
+ but with more explicit parameter autocompletion in some IDEs.
137
+
138
+ Parameters
139
+ ----------
140
+ engine : {"polars", "pandas", "pandas[pyarrow]", "pyarrow"}, optional
141
+ The backend to use for loading the dataset.
142
+ **kwds : Any
143
+ Additional arguments passed to the loader.
144
+
145
+ Returns
146
+ -------
147
+ DataFrame or Table
148
+ The loaded dataset.
149
+
150
+ Examples
151
+ --------
152
+ >>> from altair.datasets import data
153
+ >>> cars_df = data.cars.load(engine="polars")
154
+ >>> movies_df = data.movies.load(engine="pandas")
155
+ """
156
+ return self._call_impl(engine=engine, **kwds)
157
+
158
+ def __repr__(self) -> str:
159
+ return f"DatasetAccessor('{self._name}', default_engine='{self._backend}')"
160
+
161
+ @t.overload
162
+ def __call__(
163
+ self,
164
+ *,
165
+ engine: t.Literal["polars"],
166
+ **kwds: t.Any,
167
+ ) -> pl.DataFrame: ...
168
+
169
+ @t.overload
170
+ def __call__(
171
+ self,
172
+ *,
173
+ engine: t.Literal["pandas", "pandas[pyarrow]"],
174
+ **kwds: t.Any,
175
+ ) -> pd.DataFrame: ...
176
+
177
+ @t.overload
178
+ def __call__(
179
+ self,
180
+ *,
181
+ engine: t.Literal["pyarrow"],
182
+ **kwds: t.Any,
183
+ ) -> pa.Table: ...
184
+
185
+ @t.overload
186
+ def __call__(
187
+ self,
188
+ *,
189
+ engine: _Backend | None = None,
190
+ **kwds: t.Any,
191
+ ) -> t.Any: ...
192
+
193
+ def __call__(
194
+ self,
195
+ *,
196
+ engine: _Backend | None = None,
197
+ **kwds: t.Any,
198
+ ) -> t.Any:
199
+ """
200
+ Load the dataset with the specified engine.
201
+
202
+ Parameters
203
+ ----------
204
+ engine : {{"polars", "pandas", "pandas[pyarrow]", "pyarrow"}}, optional
205
+ The backend to use for loading the dataset.
206
+ **kwds
207
+ Additional arguments passed to the loader.
208
+
209
+ Returns
210
+ -------
211
+ The loaded dataset as a DataFrame/Table from the specified engine.
212
+
213
+ Examples
214
+ --------
215
+ >>> from altair.datasets import data
216
+ >>>
217
+ >>> # Load with default engine
218
+ >>> df = data.cars()
219
+ >>>
220
+ >>> # Load with specific engine
221
+ >>> df = data.cars(engine="polars")
222
+ """
223
+ return self._call_impl(engine=engine, **kwds)
224
+
225
+
226
+ class DataObject:
227
+ """
228
+ Main data object that provides access to all datasets as attributes.
229
+
230
+ This is the primary interface for loading Altair datasets. It provides
231
+ a simple, intuitive way to access datasets with autocompletion support.
232
+
233
+ Examples
234
+ --------
235
+ >>> from altair.datasets import data
236
+ >>>
237
+ >>> # Access datasets as attributes with autocompletion
238
+ >>> cars_df = data.cars()
239
+ >>> movies_df = data.movies(engine="pandas")
240
+ >>>
241
+ >>> # Get URLs
242
+ >>> cars_url = data.cars.url
243
+ >>> movies_url = data.movies.url
244
+ >>>
245
+ >>> # Set default engine for all datasets
246
+ >>> data.set_default_engine("polars")
247
+ >>> penguins_df = data.penguins() # Uses polars engine
248
+ >>>
249
+ >>> # List available datasets
250
+ >>> available_datasets = data.list_datasets()
251
+ >>> print(f"Available datasets: {len(available_datasets)}")
252
+ Available datasets: 72
253
+ """
254
+
255
+ def __init__(self, backend: _Backend = "pandas") -> None:
256
+ self._backend: _Backend = backend
257
+ self._accessors: dict[Dataset, DatasetAccessor] = {}
258
+ self._dataset_names: list[Dataset | LiteralString] | None = None
259
+
260
+ def _get_dataset_names(self) -> list[Dataset | LiteralString]:
261
+ """Get the list of available dataset names from metadata."""
262
+ if self._dataset_names is None:
263
+ try:
264
+ from altair.datasets._cache import CsvCache
265
+
266
+ cache = CsvCache()
267
+ self._dataset_names = list(cache.mapping.keys())
268
+ except Exception:
269
+ # Fallback if metadata is not available
270
+ self._dataset_names = []
271
+ return self._dataset_names
272
+
273
+ def __dir__(self) -> list[str]:
274
+ """Return list of available attributes for autocompletion."""
275
+ standard_attrs = list(super().__dir__())
276
+ dataset_names = self._get_dataset_names()
277
+ return standard_attrs + dataset_names
278
+
279
+ def __getattr__(self, name: Dataset) -> DatasetAccessor: # type: ignore[misc]
280
+ dataset_names = self._get_dataset_names()
281
+ if name not in dataset_names:
282
+ available_datasets = dataset_names[:10]
283
+ error_msg = (
284
+ f"Dataset '{name}' not found. Available datasets: {available_datasets}"
285
+ )
286
+ raise AttributeError(error_msg)
287
+
288
+ self._accessors[name] = DatasetAccessor(name, self._backend)
289
+ return self._accessors[name]
290
+
291
+ def set_default_engine(self, engine: _Backend) -> None:
292
+ """
293
+ Set the default engine for all datasets.
294
+
295
+ Parameters
296
+ ----------
297
+ engine : {"polars", "pandas", "pandas[pyarrow]", "pyarrow"}
298
+ The backend to use as default for all datasets.
299
+
300
+ Examples
301
+ --------
302
+ >>> from altair.datasets import data
303
+ >>> data.set_default_engine("polars")
304
+ >>> # Now all datasets will use polars by default
305
+ >>> cars_df = data.cars() # Uses polars
306
+ >>> movies_df = data.movies() # Uses polars
307
+ """
308
+ self._backend = engine
309
+ # Clear cached accessors so they use the new default
310
+ self._accessors.clear()
311
+
312
+ def list_datasets(self) -> list[Dataset | LiteralString]:
313
+ """
314
+ Get a list of all available dataset names.
315
+
316
+ Returns
317
+ -------
318
+ list[str]
319
+ List of available dataset names.
320
+
321
+ Examples
322
+ --------
323
+ >>> from altair.datasets import data
324
+ >>> datasets = data.list_datasets()
325
+ >>> print(f"Available datasets: {len(datasets)}")
326
+ Available datasets: 72
327
+ >>> print(datasets[:5]) # First 5 datasets
328
+ ['airports', 'annual_precip', 'anscombe', 'barley', 'birdstrikes']
329
+ """
330
+ return self._get_dataset_names()
331
+
332
+ def get_default_engine(self) -> _Backend:
333
+ """
334
+ Get the current default engine.
335
+
336
+ Returns
337
+ -------
338
+ str
339
+ The current default engine.
340
+
341
+ Examples
342
+ --------
343
+ >>> from altair.datasets import data
344
+ >>> data.set_default_engine("pandas")
345
+ >>> print(data.get_default_engine())
346
+ pandas
347
+ >>> data.set_default_engine("polars")
348
+ >>> print(data.get_default_engine())
349
+ polars
350
+ """
351
+ return self._backend
352
+
353
+ def __repr__(self) -> str:
354
+ dataset_count = len(self._get_dataset_names())
355
+ return f"AltairDataObject(default_engine='{self._backend}', datasets={dataset_count})"
356
+
357
+
358
+ data = DataObject()
.venv/lib/python3.13/site-packages/altair/datasets/_exceptions.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from collections.abc import Sequence
7
+
8
+ from altair.datasets._reader import _Backend
9
+ from altair.datasets._typing import Metadata
10
+
11
+
12
+ class AltairDatasetsError(Exception):
13
+ @classmethod
14
+ def from_url(cls, meta: Metadata, /) -> AltairDatasetsError:
15
+ if meta["suffix"] == ".parquet":
16
+ msg = (
17
+ f"{_failed_url(meta)}"
18
+ f"{meta['suffix']!r} datasets require `vegafusion`.\n"
19
+ "See upstream issue for details: https://github.com/vega/vega/issues/3961"
20
+ )
21
+ else:
22
+ msg = (
23
+ f"{cls.from_url.__qualname__}() called for "
24
+ f"unimplemented extension: {meta['suffix']}\n\n{meta!r}"
25
+ )
26
+ raise NotImplementedError(msg)
27
+ return cls(msg)
28
+
29
+ @classmethod
30
+ def from_tabular(cls, meta: Metadata, backend_name: str, /) -> AltairDatasetsError:
31
+ if meta["is_image"]:
32
+ reason = "Image data is non-tabular."
33
+ return cls(f"{_failed_tabular(meta)}{reason}{_suggest_url(meta)}")
34
+ elif not meta["is_tabular"] or meta["suffix"] in {".arrow", ".parquet"}:
35
+ if meta["suffix"] in {".arrow", ".parquet"}:
36
+ install: tuple[str, ...] = "pyarrow", "polars"
37
+ what = f"{meta['suffix']!r}"
38
+ else:
39
+ install = ("polars",)
40
+ if meta["is_spatial"]:
41
+ what = "Geospatial data"
42
+ elif meta["is_json"]:
43
+ what = "Non-tabular json"
44
+ else:
45
+ what = f"{meta['file_name']!r}"
46
+ reason = _why(what, backend_name)
47
+ return cls(f"{_failed_tabular(meta)}{reason}{_suggest_url(meta, *install)}")
48
+ else:
49
+ return cls(_implementation_not_found(meta))
50
+
51
+ @classmethod
52
+ def from_priority(cls, priority: Sequence[_Backend], /) -> AltairDatasetsError:
53
+ msg = f"Found no supported backend, searched:\n{priority!r}"
54
+ return cls(msg)
55
+
56
+
57
+ def module_not_found(
58
+ backend_name: str, reqs: Sequence[str], missing: str
59
+ ) -> ModuleNotFoundError:
60
+ if len(reqs) == 1:
61
+ depends = f"{reqs[0]!r} package"
62
+ else:
63
+ depends = ", ".join(f"{req!r}" for req in reqs) + " packages"
64
+ msg = (
65
+ f"Backend {backend_name!r} requires the {depends}, but {missing!r} could not be found.\n"
66
+ f"This can be installed with pip using:\n"
67
+ f" pip install {missing}\n"
68
+ f"Or with conda using:\n"
69
+ f" conda install -c conda-forge {missing}"
70
+ )
71
+ return ModuleNotFoundError(msg, name=missing)
72
+
73
+
74
+ def _failed_url(meta: Metadata, /) -> str:
75
+ return f"Unable to load {meta['file_name']!r} via url.\n"
76
+
77
+
78
+ def _failed_tabular(meta: Metadata, /) -> str:
79
+ return f"Unable to load {meta['file_name']!r} as tabular data.\n"
80
+
81
+
82
+ def _why(what: str, backend_name: str, /) -> str:
83
+ return f"{what} is not supported natively by {backend_name!r}."
84
+
85
+
86
+ def _suggest_url(meta: Metadata, *install_other: str) -> str:
87
+ other = ""
88
+ if install_other:
89
+ others = " or ".join(f"`{other}`" for other in install_other)
90
+ other = f" installing {others}, or use"
91
+ return (
92
+ f"\n\nInstead, try{other}:\n"
93
+ " from altair.datasets import data\n"
94
+ f" data.{meta['dataset_name']}.url"
95
+ )
96
+
97
+
98
+ def _implementation_not_found(meta: Metadata, /) -> str:
99
+ """Search finished without finding a *declared* incompatibility."""
100
+ INDENT = " " * 4
101
+ record = f",\n{INDENT}".join(
102
+ f"{k}={v!r}"
103
+ for k, v in meta.items()
104
+ if not (k.startswith(("is_", "sha", "bytes", "has_")))
105
+ or (v is True and k.startswith("is_"))
106
+ )
107
+ return f"Found no implementation that supports:\n{INDENT}{record}"
.venv/lib/python3.13/site-packages/altair/datasets/_loader.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import typing as t
4
+ from typing import Generic, final, overload
5
+
6
+ from narwhals.stable.v1.typing import IntoDataFrameT
7
+
8
+ from altair.datasets import _reader
9
+ from altair.datasets._reader import IntoFrameT
10
+
11
+ if t.TYPE_CHECKING:
12
+ import sys
13
+ from typing import Any, Literal
14
+
15
+ import pandas as pd
16
+ import polars as pl
17
+ import pyarrow as pa
18
+
19
+ from altair.datasets._cache import DatasetCache
20
+ from altair.datasets._reader import Reader
21
+
22
+ if sys.version_info >= (3, 11):
23
+ from typing import LiteralString, Self
24
+ else:
25
+ from typing_extensions import LiteralString, Self
26
+ from altair.datasets._reader import _Backend
27
+ from altair.datasets._typing import Dataset, Extension
28
+
29
+
30
+ __all__ = ["Loader", "load"]
31
+
32
+
33
+ class Loader(Generic[IntoDataFrameT, IntoFrameT]):
34
+ """
35
+ Load example datasets *remotely* from `vega-datasets`_, with caching.
36
+
37
+ A new ``Loader`` must be initialized by specifying a backend::
38
+
39
+ from altair.datasets import Loader
40
+
41
+ load = Loader.from_backend("polars")
42
+ load
43
+ Loader[polars]
44
+
45
+ .. _vega-datasets:
46
+ https://github.com/vega/vega-datasets
47
+ """
48
+
49
+ _reader: Reader[IntoDataFrameT, IntoFrameT]
50
+
51
+ @overload
52
+ @classmethod
53
+ def from_backend(
54
+ cls, backend_name: Literal["polars"] = ..., /
55
+ ) -> Loader[pl.DataFrame, pl.LazyFrame]: ...
56
+
57
+ @overload
58
+ @classmethod
59
+ def from_backend(
60
+ cls, backend_name: Literal["pandas", "pandas[pyarrow]"], /
61
+ ) -> Loader[pd.DataFrame, pd.DataFrame]: ...
62
+
63
+ @overload
64
+ @classmethod
65
+ def from_backend(
66
+ cls, backend_name: Literal["pyarrow"], /
67
+ ) -> Loader[pa.Table, pa.Table]: ...
68
+
69
+ @classmethod
70
+ def from_backend(
71
+ cls: type[Loader[Any, Any]], backend_name: _Backend = "polars", /
72
+ ) -> Loader[Any, Any]:
73
+ """
74
+ Initialize a new loader, with the specified backend.
75
+
76
+ Parameters
77
+ ----------
78
+ backend_name
79
+ DataFrame package/config used to return data.
80
+
81
+ * *polars*: Using `polars defaults`_
82
+ * *pandas*: Using `pandas defaults`_.
83
+ * *pandas[pyarrow]*: Using ``dtype_backend="pyarrow"``
84
+ * *pyarrow*: (*Experimental*)
85
+
86
+ .. warning::
87
+ Most datasets use a `JSON format not supported`_ by ``pyarrow``
88
+
89
+ Examples
90
+ --------
91
+ Using ``polars``::
92
+
93
+ from altair.datasets import Loader
94
+
95
+ load = Loader.from_backend("polars")
96
+ cars = load("cars")
97
+
98
+ type(cars)
99
+ polars.dataframe.frame.DataFrame
100
+
101
+ Using ``pandas``::
102
+
103
+ load = Loader.from_backend("pandas")
104
+ cars = load("cars")
105
+
106
+ type(cars)
107
+ pandas.core.frame.DataFrame
108
+
109
+ Using ``pandas``, backed by ``pyarrow`` dtypes::
110
+
111
+ load = Loader.from_backend("pandas[pyarrow]")
112
+ co2 = load("co2")
113
+
114
+ type(co2)
115
+ pandas.core.frame.DataFrame
116
+
117
+ co2.dtypes
118
+ Date datetime64[ns]
119
+ CO2 double[pyarrow]
120
+ adjusted CO2 double[pyarrow]
121
+ dtype: object
122
+
123
+ .. _polars defaults:
124
+ https://docs.pola.rs/api/python/stable/reference/io.html
125
+ .. _pandas defaults:
126
+ https://pandas.pydata.org/docs/reference/io.html
127
+ .. _JSON format not supported:
128
+ https://arrow.apache.org/docs/python/json.html#reading-json-files
129
+ """
130
+ return cls.from_reader(_reader._from_backend(backend_name))
131
+
132
+ @classmethod
133
+ def from_reader(cls, reader: Reader[IntoDataFrameT, IntoFrameT], /) -> Self:
134
+ obj = cls.__new__(cls)
135
+ obj._reader = reader
136
+ return obj
137
+
138
+ def __call__(
139
+ self,
140
+ name: Dataset | LiteralString,
141
+ suffix: Extension | None = None,
142
+ /,
143
+ **kwds: Any,
144
+ ) -> IntoDataFrameT:
145
+ """
146
+ Get a remote dataset and load as tabular data.
147
+
148
+ Parameters
149
+ ----------
150
+ name
151
+ Name of the dataset/`Path.stem`_.
152
+ suffix
153
+ File extension/`Path.suffix`_.
154
+
155
+ .. note::
156
+ Only needed if ``name`` is available in multiple formats.
157
+ **kwds
158
+ Arguments passed to the underlying read function.
159
+
160
+ Examples
161
+ --------
162
+ Using ``polars``::
163
+
164
+ from altair.datasets import Loader
165
+
166
+ load = Loader.from_backend("polars")
167
+ source = load("iowa_electricity")
168
+
169
+ source.columns
170
+ ['year', 'source', 'net_generation']
171
+
172
+ source.head(5)
173
+ shape: (5, 3)
174
+ ┌────────────┬──────────────┬────────────────┐
175
+ │ year ┆ source ┆ net_generation │
176
+ │ --- ┆ --- ┆ --- ��
177
+ │ date ┆ str ┆ i64 │
178
+ ╞════════════╪══════════════╪════════════════╡
179
+ │ 2001-01-01 ┆ Fossil Fuels ┆ 35361 │
180
+ │ 2002-01-01 ┆ Fossil Fuels ┆ 35991 │
181
+ │ 2003-01-01 ┆ Fossil Fuels ┆ 36234 │
182
+ │ 2004-01-01 ┆ Fossil Fuels ┆ 36205 │
183
+ │ 2005-01-01 ┆ Fossil Fuels ┆ 36883 │
184
+ └────────────┴──────────────┴────────────────┘
185
+
186
+ Using ``pandas``::
187
+
188
+ load = Loader.from_backend("pandas")
189
+ source = load("iowa_electricity")
190
+
191
+ source.columns
192
+ Index(['year', 'source', 'net_generation'], dtype='object')
193
+
194
+ source.head(5)
195
+ year source net_generation
196
+ 0 2001-01-01 Fossil Fuels 35361
197
+ 1 2002-01-01 Fossil Fuels 35991
198
+ 2 2003-01-01 Fossil Fuels 36234
199
+ 3 2004-01-01 Fossil Fuels 36205
200
+ 4 2005-01-01 Fossil Fuels 36883
201
+
202
+ Using ``pyarrow``::
203
+
204
+ load = Loader.from_backend("pyarrow")
205
+ source = load("iowa_electricity")
206
+
207
+ source.column_names
208
+ ['year', 'source', 'net_generation']
209
+
210
+ source.slice(0, 5)
211
+ pyarrow.Table
212
+ year: date32[day]
213
+ source: string
214
+ net_generation: int64
215
+ ----
216
+ year: [[2001-01-01,2002-01-01,2003-01-01,2004-01-01,2005-01-01]]
217
+ source: [["Fossil Fuels","Fossil Fuels","Fossil Fuels","Fossil Fuels","Fossil Fuels"]]
218
+ net_generation: [[35361,35991,36234,36205,36883]]
219
+
220
+ .. _Path.stem:
221
+ https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem
222
+ .. _Path.suffix:
223
+ https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.suffix
224
+ """
225
+ return self._reader.dataset(name, suffix, **kwds)
226
+
227
+ def url(
228
+ self,
229
+ name: Dataset | LiteralString,
230
+ suffix: Extension | None = None,
231
+ /,
232
+ ) -> str:
233
+ """
234
+ Return the address of a remote dataset.
235
+
236
+ Parameters
237
+ ----------
238
+ name
239
+ Name of the dataset/`Path.stem`_.
240
+ suffix
241
+ File extension/`Path.suffix`_.
242
+
243
+ .. note::
244
+ Only needed if ``name`` is available in multiple formats.
245
+
246
+ .. _Path.stem:
247
+ https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem
248
+ .. _Path.suffix:
249
+ https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.suffix
250
+
251
+ Examples
252
+ --------
253
+ The returned url will always point to an accessible dataset::
254
+
255
+ import altair as alt
256
+ from altair.datasets import Loader
257
+
258
+ load = Loader.from_backend("polars")
259
+ load.url("cars")
260
+ "https://cdn.jsdelivr.net/npm/vega-datasets@v2.11.0/data/cars.json"
261
+
262
+ We can pass the result directly to a chart::
263
+
264
+ url = load.url("cars")
265
+ alt.Chart(url).mark_point().encode(x="Horsepower:Q", y="Miles_per_Gallon:Q")
266
+ """
267
+ return self._reader.url(name, suffix)
268
+
269
+ @property
270
+ def cache(self) -> DatasetCache:
271
+ """
272
+ Caching of remote dataset requests.
273
+
274
+ Configure cache path::
275
+
276
+ self.cache.path = "..."
277
+
278
+ Download the latest datasets *ahead-of-time*::
279
+
280
+ self.cache.download_all()
281
+
282
+ Remove all downloaded datasets::
283
+
284
+ self.cache.clear()
285
+
286
+ Disable caching::
287
+
288
+ self.cache.path = None
289
+ """
290
+ return self._reader.cache
291
+
292
+ def __repr__(self) -> str:
293
+ return f"{type(self).__name__}[{self._reader._name}]"
294
+
295
+
296
+ @final
297
+ class _Load(Loader[IntoDataFrameT, IntoFrameT]):
298
+ @overload
299
+ def __call__( # pyright: ignore[reportOverlappingOverload]
300
+ self,
301
+ name: Dataset | LiteralString,
302
+ suffix: Extension | None = ...,
303
+ /,
304
+ backend: None = ...,
305
+ **kwds: Any,
306
+ ) -> IntoDataFrameT: ...
307
+ @overload
308
+ def __call__(
309
+ self,
310
+ name: Dataset | LiteralString,
311
+ suffix: Extension | None = ...,
312
+ /,
313
+ backend: Literal["polars"] = ...,
314
+ **kwds: Any,
315
+ ) -> pl.DataFrame: ...
316
+ @overload
317
+ def __call__(
318
+ self,
319
+ name: Dataset | LiteralString,
320
+ suffix: Extension | None = ...,
321
+ /,
322
+ backend: Literal["pandas", "pandas[pyarrow]"] = ...,
323
+ **kwds: Any,
324
+ ) -> pd.DataFrame: ...
325
+ @overload
326
+ def __call__(
327
+ self,
328
+ name: Dataset | LiteralString,
329
+ suffix: Extension | None = ...,
330
+ /,
331
+ backend: Literal["pyarrow"] = ...,
332
+ **kwds: Any,
333
+ ) -> pa.Table: ...
334
+ def __call__(
335
+ self,
336
+ name: Dataset | LiteralString,
337
+ suffix: Extension | None = None,
338
+ /,
339
+ backend: _Backend | None = None,
340
+ **kwds: Any,
341
+ ) -> IntoDataFrameT | pl.DataFrame | pd.DataFrame | pa.Table:
342
+ if backend is None:
343
+ return super().__call__(name, suffix, **kwds)
344
+ else:
345
+ return self.from_backend(backend)(name, suffix, **kwds)
346
+
347
+
348
+ load: _Load[Any, Any]
349
+
350
+
351
+ def __getattr__(name):
352
+ if name == "load":
353
+ reader = _reader.infer_backend()
354
+ global load
355
+ load = _Load.from_reader(reader)
356
+ return load
357
+ else:
358
+ msg = f"module {__name__!r} has no attribute {name!r}"
359
+ raise AttributeError(msg)
.venv/lib/python3.13/site-packages/altair/datasets/_reader.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Backend for ``alt.datasets.Loader``.
3
+
4
+ Notes
5
+ -----
6
+ Extending would be more ergonomic if `read`, `scan`, `_constraints` were available under a single export::
7
+
8
+ from altair.datasets import ext, reader
9
+ import polars as pl
10
+
11
+ impls = (
12
+ ext.read(pl.read_parquet, ext.is_parquet),
13
+ ext.read(pl.read_csv, ext.is_csv),
14
+ ext.read(pl.read_json, ext.is_json),
15
+ )
16
+ user_reader = reader(impls)
17
+ user_reader.dataset("airports")
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from collections import Counter
23
+ from collections.abc import Mapping
24
+ from importlib import import_module
25
+ from importlib.util import find_spec
26
+ from itertools import chain
27
+ from pathlib import Path
28
+ from typing import TYPE_CHECKING, Any, ClassVar, Generic, Literal, cast, overload
29
+ from urllib.request import build_opener as _build_opener
30
+
31
+ from narwhals.stable import v1 as nw
32
+ from narwhals.stable.v1.typing import IntoDataFrameT, IntoExpr
33
+ from packaging.requirements import Requirement
34
+
35
+ from altair.datasets import _readimpl
36
+ from altair.datasets._cache import CsvCache, DatasetCache, SchemaCache, _iter_metadata
37
+ from altair.datasets._constraints import is_parquet
38
+ from altair.datasets._exceptions import AltairDatasetsError, module_not_found
39
+ from altair.datasets._readimpl import IntoFrameT, is_available
40
+
41
+ if TYPE_CHECKING:
42
+ import sys
43
+ from collections.abc import Callable, Sequence
44
+ from urllib.request import OpenerDirector
45
+
46
+ import pandas as pd
47
+ import polars as pl
48
+ import pyarrow as pa
49
+
50
+ from altair.datasets._readimpl import BaseImpl, R, Read, Scan
51
+ from altair.datasets._typing import Dataset, Extension, Metadata
52
+ from altair.vegalite.v6.schema._typing import OneOrSeq
53
+
54
+ if sys.version_info >= (3, 13):
55
+ from typing import TypeIs, TypeVar
56
+ else:
57
+ from typing_extensions import TypeIs, TypeVar
58
+ if sys.version_info >= (3, 12):
59
+ from typing import Unpack
60
+ else:
61
+ from typing_extensions import Unpack
62
+ if sys.version_info >= (3, 11):
63
+ from typing import LiteralString
64
+ else:
65
+ from typing_extensions import LiteralString
66
+ if sys.version_info >= (3, 10):
67
+ from typing import TypeAlias
68
+ else:
69
+ from typing_extensions import TypeAlias
70
+ _Polars: TypeAlias = Literal["polars"]
71
+ _Pandas: TypeAlias = Literal["pandas"]
72
+ _PyArrow: TypeAlias = Literal["pyarrow"]
73
+ _PandasAny: TypeAlias = Literal[_Pandas, "pandas[pyarrow]"]
74
+ _Backend: TypeAlias = Literal[_Polars, _PandasAny, _PyArrow]
75
+ _CuDF: TypeAlias = Literal["cudf"]
76
+ _Dask: TypeAlias = Literal["dask"]
77
+ _DuckDB: TypeAlias = Literal["duckdb"]
78
+ _Ibis: TypeAlias = Literal["ibis"]
79
+ _PySpark: TypeAlias = Literal["pyspark"]
80
+ _NwSupport: TypeAlias = Literal[
81
+ _Polars, _Pandas, _PyArrow, _CuDF, _Dask, _DuckDB, _Ibis, _PySpark
82
+ ]
83
+ _NwSupportT = TypeVar(
84
+ "_NwSupportT",
85
+ _Polars,
86
+ _Pandas,
87
+ _PyArrow,
88
+ _CuDF,
89
+ _Dask,
90
+ _DuckDB,
91
+ _Ibis,
92
+ _PySpark,
93
+ )
94
+
95
+ _SupportProfile: TypeAlias = Mapping[
96
+ Literal["supported", "unsupported"], "Sequence[Dataset]"
97
+ ]
98
+ """
99
+ Dataset support varies between backends and available dependencies.
100
+
101
+ Any name listed in ``"unsupported"`` will raise an error on::
102
+
103
+ from altair.datasets import load
104
+
105
+ load("7zip")
106
+
107
+ Instead, they can be loaded via::
108
+
109
+ import altair as alt
110
+ from altair.datasets import url
111
+
112
+ alt.Chart(url("7zip"))
113
+ """
114
+
115
+
116
+ class Reader(Generic[IntoDataFrameT, IntoFrameT]):
117
+ """
118
+ Modular file reader, targeting remote & local tabular resources.
119
+
120
+ .. warning::
121
+ Use ``reader(...)`` instead of instantiating ``Reader`` directly.
122
+ """
123
+
124
+ _read: Sequence[Read[IntoDataFrameT]]
125
+ """Eager file read functions."""
126
+
127
+ _scan: Sequence[Scan[IntoFrameT]]
128
+ """Lazy file read functions."""
129
+
130
+ _name: str
131
+ """
132
+ Used in error messages, repr and matching ``@overload``(s).
133
+
134
+ Otherwise, has no concrete meaning.
135
+ """
136
+
137
+ _implementation: nw.Implementation
138
+ """
139
+ Corresponding `narwhals implementation`_.
140
+
141
+ .. _narwhals implementation:
142
+ https://github.com/narwhals-dev/narwhals/blob/9b6a355530ea46c590d5a6d1d0567be59c0b5742/narwhals/utils.py#L61-L290
143
+ """
144
+
145
+ _opener: ClassVar[OpenerDirector] = _build_opener()
146
+ _metadata_path: ClassVar[Path] = (
147
+ Path(__file__).parent / "_metadata" / "metadata.parquet"
148
+ )
149
+
150
+ def __init__(
151
+ self,
152
+ read: Sequence[Read[IntoDataFrameT]],
153
+ scan: Sequence[Scan[IntoFrameT]],
154
+ name: str,
155
+ implementation: nw.Implementation,
156
+ ) -> None:
157
+ self._read = read
158
+ self._scan = scan
159
+ self._name = name
160
+ self._implementation = implementation
161
+ self._schema_cache = SchemaCache(implementation=implementation)
162
+
163
+ def __repr__(self) -> str:
164
+ from textwrap import indent
165
+
166
+ PREFIX = " " * 4
167
+ NL = "\n"
168
+ body = f"read\n{indent(NL.join(str(el) for el in self._read), PREFIX)}"
169
+ if self._scan:
170
+ body += f"\nscan\n{indent(NL.join(str(el) for el in self._scan), PREFIX)}"
171
+ return f"Reader[{self._name}] {self._implementation!r}\n{body}"
172
+
173
+ def read_fn(self, meta: Metadata, /) -> Callable[..., IntoDataFrameT]:
174
+ return self._solve(meta, self._read)
175
+
176
+ def scan_fn(self, meta: Metadata | Path | str, /) -> Callable[..., IntoFrameT]:
177
+ meta = meta if isinstance(meta, Mapping) else {"suffix": _into_suffix(meta)}
178
+ return self._solve(meta, self._scan)
179
+
180
+ @property
181
+ def cache(self) -> DatasetCache:
182
+ return DatasetCache(self)
183
+
184
+ def _handle_pyarrow_date_error(self, e: Exception, name: str) -> None:
185
+ """Handle PyArrow date parsing errors with informative error messages, see https://github.com/apache/arrow/issues/41488."""
186
+ if "CSV conversion error to date" in str(e) and "pyarrow" in str(
187
+ type(e).__module__
188
+ ):
189
+ message = (
190
+ f"PyArrow cannot parse date format in dataset '{name}'. "
191
+ f"This is a known limitation of PyArrow's CSV reader for non-ISO date formats.\n\n"
192
+ f"Alternatives:\n"
193
+ f"1. Use a different backend: data.{name}(engine='pandas') or data.{name}(engine='polars')\n"
194
+ f"2. Convert dates manually after loading as strings\n\n"
195
+ f"Original error: {e}"
196
+ )
197
+ raise AltairDatasetsError(message) from e
198
+ raise e
199
+
200
+ def dataset(
201
+ self,
202
+ name: Dataset | LiteralString,
203
+ suffix: Extension | None = None,
204
+ /,
205
+ **kwds: Any,
206
+ ) -> IntoDataFrameT:
207
+ frame = self._query(name, suffix)
208
+ meta = next(_iter_metadata(frame))
209
+ fn = self.read_fn(meta)
210
+ fn_kwds = self._merge_kwds(meta, kwds)
211
+ if self.cache.is_active():
212
+ fp = self.cache._maybe_download(meta)
213
+ try:
214
+ return fn(fp, **fn_kwds)
215
+ except Exception as e:
216
+ self._handle_pyarrow_date_error(e, name)
217
+ raise
218
+ else:
219
+ with self._opener.open(meta["url"]) as f:
220
+ try:
221
+ return fn(f, **fn_kwds)
222
+ except Exception as e:
223
+ self._handle_pyarrow_date_error(e, name)
224
+ raise
225
+
226
+ def url(
227
+ self, name: Dataset | LiteralString, suffix: Extension | None = None, /
228
+ ) -> str:
229
+ frame = self._query(name, suffix)
230
+ meta = next(_iter_metadata(frame))
231
+ if is_parquet(meta.items()) and not is_available("vegafusion"):
232
+ raise AltairDatasetsError.from_url(meta)
233
+ url = meta["url"]
234
+ if isinstance(url, str):
235
+ return url
236
+ else:
237
+ msg = f"Expected 'str' but got {type(url).__name__!r}\nfrom {url!r}."
238
+ raise TypeError(msg)
239
+
240
+ # TODO: (Multiple)
241
+ # - Settle on a better name
242
+ # - Add method to `Loader`
243
+ # - Move docs to `Loader.{new name}`
244
+ def open_markdown(self, name: Dataset, /) -> None:
245
+ """
246
+ Learn more about a dataset, opening `vega-datasets/datapackage.md`_ with the default browser.
247
+
248
+ Additional info *may* include: `description`_, `schema`_, `sources`_, `licenses`_.
249
+
250
+ .. _vega-datasets/datapackage.md:
251
+ https://github.com/vega/vega-datasets/blob/main/datapackage.md
252
+ .. _description:
253
+ https://datapackage.org/standard/data-resource/#description
254
+ .. _schema:
255
+ https://datapackage.org/standard/table-schema/#schema
256
+ .. _sources:
257
+ https://datapackage.org/standard/data-package/#sources
258
+ .. _licenses:
259
+ https://datapackage.org/standard/data-package/#licenses
260
+ """
261
+ import webbrowser
262
+
263
+ from altair.utils import VERSIONS
264
+
265
+ ref = self._query(name).get_column("file_name").item(0).replace(".", "")
266
+ tag = VERSIONS["vega-datasets"]
267
+ url = f"https://github.com/vega/vega-datasets/blob/v{tag}/datapackage.md#{ref}"
268
+ webbrowser.open(url)
269
+
270
+ @overload
271
+ def profile(self, *, show: Literal[False] = ...) -> _SupportProfile: ...
272
+
273
+ @overload
274
+ def profile(self, *, show: Literal[True]) -> None: ...
275
+
276
+ def profile(self, *, show: bool = False) -> _SupportProfile | None:
277
+ """
278
+ Describe which datasets can be loaded as tabular data.
279
+
280
+ Parameters
281
+ ----------
282
+ show
283
+ Print a densely formatted repr *instead of* returning a mapping.
284
+ """
285
+ relevant_columns = set(
286
+ chain.from_iterable(impl._relevant_columns for impl in self._read)
287
+ )
288
+ frame = self._scan_metadata().select("dataset_name", *relevant_columns)
289
+ inc_expr = nw.any_horizontal(impl._include_expr for impl in self._read)
290
+ result: _SupportProfile = {
291
+ "unsupported": _dataset_names(frame, ~inc_expr),
292
+ "supported": _dataset_names(frame, inc_expr),
293
+ }
294
+ if show:
295
+ import pprint
296
+
297
+ pprint.pprint(result, compact=True, sort_dicts=False)
298
+ return None
299
+ return result
300
+
301
+ def _query(
302
+ self, name: Dataset | LiteralString, suffix: Extension | None = None, /
303
+ ) -> nw.DataFrame[IntoDataFrameT]:
304
+ """
305
+ Query a tabular version of `vega-datasets/datapackage.json`_.
306
+
307
+ Applies a filter, erroring out when no results would be returned.
308
+
309
+ .. _vega-datasets/datapackage.json:
310
+ https://github.com/vega/vega-datasets/blob/main/datapackage.json
311
+ """
312
+ constraints = _into_constraints(name, suffix)
313
+ frame = self._scan_metadata(**constraints).collect()
314
+ if not frame.is_empty():
315
+ return frame
316
+ else:
317
+ msg = f"Found no results for:\n {constraints!r}"
318
+ raise ValueError(msg)
319
+
320
+ def _merge_kwds(self, meta: Metadata, kwds: dict[str, Any], /) -> Mapping[str, Any]:
321
+ """
322
+ Extend user-provided arguments with dataset & library-specfic defaults.
323
+
324
+ .. important:: User-provided arguments have a higher precedence.
325
+ """
326
+ if self._schema_cache.is_active() and (
327
+ schema := self._schema_cache.schema_kwds(meta)
328
+ ):
329
+ kwds = schema | kwds if kwds else schema
330
+ return kwds
331
+
332
+ @property
333
+ def _metadata_frame(self) -> nw.LazyFrame[IntoFrameT]:
334
+ fp = self._metadata_path
335
+ return nw.from_native(self.scan_fn(fp)(fp)).lazy()
336
+
337
+ def _scan_metadata(
338
+ self, *predicates: OneOrSeq[IntoExpr], **constraints: Unpack[Metadata]
339
+ ) -> nw.LazyFrame[IntoFrameT]:
340
+ if predicates or constraints:
341
+ return self._metadata_frame.filter(*predicates, **constraints)
342
+ return self._metadata_frame
343
+
344
+ def _solve(
345
+ self, meta: Metadata, impls: Sequence[BaseImpl[R]], /
346
+ ) -> Callable[..., R]:
347
+ """
348
+ Return the first function that satisfies dataset constraints.
349
+
350
+ See Also
351
+ --------
352
+ ``altair.datasets._readimpl.BaseImpl.unwrap_or_skip``
353
+ """
354
+ items = meta.items()
355
+ it = (some for impl in impls if (some := impl.unwrap_or_skip(items)))
356
+ if fn_or_err := next(it, None):
357
+ if _is_err(fn_or_err):
358
+ raise fn_or_err.from_tabular(meta, self._name)
359
+ return fn_or_err
360
+ raise AltairDatasetsError.from_tabular(meta, self._name)
361
+
362
+
363
+ def _dataset_names(
364
+ frame: nw.LazyFrame, *predicates: OneOrSeq[IntoExpr]
365
+ ) -> Sequence[Dataset]:
366
+ # NOTE: helper function for `Reader.profile`
367
+ return (
368
+ frame.filter(*predicates)
369
+ .select("dataset_name")
370
+ .collect()
371
+ .get_column("dataset_name")
372
+ .to_list()
373
+ )
374
+
375
+
376
+ class _NoParquetReader(Reader[IntoDataFrameT, IntoFrameT]):
377
+ def __repr__(self) -> str:
378
+ return f"{super().__repr__()}\ncsv_cache\n {self.csv_cache!r}"
379
+
380
+ @property
381
+ def csv_cache(self) -> CsvCache:
382
+ if not hasattr(self, "_csv_cache"):
383
+ self._csv_cache = CsvCache()
384
+ return self._csv_cache
385
+
386
+ @property
387
+ def _metadata_frame(self) -> nw.LazyFrame[IntoFrameT]:
388
+ data = cast("dict[str, Any]", self.csv_cache.rotated)
389
+ impl = self._implementation
390
+ return nw.maybe_convert_dtypes(nw.from_dict(data, backend=impl)).lazy()
391
+
392
+
393
+ @overload
394
+ def reader(
395
+ read_fns: Sequence[Read[IntoDataFrameT]],
396
+ scan_fns: tuple[()] = ...,
397
+ *,
398
+ name: str | None = ...,
399
+ implementation: nw.Implementation = ...,
400
+ ) -> Reader[IntoDataFrameT, nw.LazyFrame[IntoDataFrameT]]: ...
401
+
402
+
403
+ @overload
404
+ def reader(
405
+ read_fns: Sequence[Read[IntoDataFrameT]],
406
+ scan_fns: Sequence[Scan[IntoFrameT]],
407
+ *,
408
+ name: str | None = ...,
409
+ implementation: nw.Implementation = ...,
410
+ ) -> Reader[IntoDataFrameT, IntoFrameT]: ...
411
+
412
+
413
+ def reader(
414
+ read_fns: Sequence[Read[IntoDataFrameT]],
415
+ scan_fns: Sequence[Scan[IntoFrameT]] = (),
416
+ *,
417
+ name: str | None = None,
418
+ implementation: nw.Implementation = nw.Implementation.UNKNOWN,
419
+ ) -> (
420
+ Reader[IntoDataFrameT, IntoFrameT]
421
+ | Reader[IntoDataFrameT, nw.LazyFrame[IntoDataFrameT]]
422
+ ):
423
+ name = name or Counter(el._inferred_package for el in read_fns).most_common(1)[0][0]
424
+ if implementation is nw.Implementation.UNKNOWN:
425
+ implementation = _into_implementation(Requirement(name))
426
+ if scan_fns:
427
+ return Reader(read_fns, scan_fns, name, implementation)
428
+ if stolen := _steal_eager_parquet(read_fns):
429
+ return Reader(read_fns, stolen, name, implementation)
430
+ else:
431
+ return _NoParquetReader[IntoDataFrameT](read_fns, (), name, implementation)
432
+
433
+
434
+ def infer_backend(
435
+ *, priority: Sequence[_Backend] = ("polars", "pandas[pyarrow]", "pandas", "pyarrow")
436
+ ) -> Reader[Any, Any]:
437
+ """
438
+ Return the first available reader in order of `priority`.
439
+
440
+ Notes
441
+ -----
442
+ - ``"polars"``: can natively load every dataset (including ``(Geo|Topo)JSON``)
443
+ - ``"pandas[pyarrow]"``: can load *most* datasets, guarantees ``.parquet`` support
444
+ - ``"pandas"``: supports ``.parquet``, if `fastparquet`_ is installed
445
+ - ``"pyarrow"``: least reliable
446
+
447
+ .. _fastparquet:
448
+ https://github.com/dask/fastparquet
449
+ """
450
+ it = (_from_backend(name) for name in priority if is_available(_requirements(name)))
451
+ if reader := next(it, None):
452
+ return reader
453
+ raise AltairDatasetsError.from_priority(priority)
454
+
455
+
456
+ @overload
457
+ def _from_backend(name: _Polars, /) -> Reader[pl.DataFrame, pl.LazyFrame]: ...
458
+ @overload
459
+ def _from_backend(name: _PandasAny, /) -> Reader[pd.DataFrame, pd.DataFrame]: ...
460
+ @overload
461
+ def _from_backend(name: _PyArrow, /) -> Reader[pa.Table, pa.Table]: ...
462
+
463
+
464
+ # FIXME: The order this is defined in makes splitting the module complicated
465
+ # - Can't use a classmethod, since some result in a subclass used
466
+ def _from_backend(name: _Backend, /) -> Reader[Any, Any]:
467
+ """
468
+ Reader initialization dispatcher.
469
+
470
+ FIXME: Works, but defining these in mixed shape functions seems off.
471
+ """
472
+ if not _is_backend(name):
473
+ msg = f"Unknown backend {name!r}"
474
+ raise TypeError(msg)
475
+ implementation = _into_implementation(name)
476
+ if name == "polars":
477
+ rd, sc = _readimpl.pl_only()
478
+ return reader(rd, sc, name=name, implementation=implementation)
479
+ elif name == "pandas[pyarrow]":
480
+ return reader(_readimpl.pd_pyarrow(), name=name, implementation=implementation)
481
+ elif name == "pandas":
482
+ return reader(_readimpl.pd_only(), name=name, implementation=implementation)
483
+ elif name == "pyarrow":
484
+ return reader(_readimpl.pa_any(), name=name, implementation=implementation)
485
+
486
+
487
+ def _is_backend(obj: Any) -> TypeIs[_Backend]:
488
+ return obj in {"polars", "pandas", "pandas[pyarrow]", "pyarrow"}
489
+
490
+
491
+ def _is_err(obj: Any) -> TypeIs[type[AltairDatasetsError]]:
492
+ return obj is AltairDatasetsError
493
+
494
+
495
+ def _into_constraints(
496
+ name: Dataset | LiteralString, suffix: Extension | None, /
497
+ ) -> Metadata:
498
+ """Transform args into a mapping to column names."""
499
+ m: Metadata = {}
500
+ if "." in name:
501
+ m["file_name"] = name
502
+ elif suffix is None:
503
+ m["dataset_name"] = name
504
+ elif suffix.startswith("."):
505
+ m = {"dataset_name": name, "suffix": suffix}
506
+ else:
507
+ from typing import get_args
508
+
509
+ from altair.datasets._typing import Extension
510
+
511
+ msg = (
512
+ f"Expected 'suffix' to be one of {get_args(Extension)!r},\n"
513
+ f"but got: {suffix!r}"
514
+ )
515
+ raise TypeError(msg)
516
+ return m
517
+
518
+
519
+ def _into_implementation(
520
+ backend: _NwSupport | _PandasAny | Requirement, /
521
+ ) -> nw.Implementation:
522
+ primary = _import_guarded(backend)
523
+ impl = nw.Implementation.from_backend(primary)
524
+ if impl is not nw.Implementation.UNKNOWN:
525
+ return impl
526
+ msg = f"Package {primary!r} is not supported by `narwhals`."
527
+ raise ValueError(msg)
528
+
529
+
530
+ def _into_suffix(obj: Path | str, /) -> Any:
531
+ if isinstance(obj, Path):
532
+ return obj.suffix
533
+ elif isinstance(obj, str):
534
+ return obj
535
+ else:
536
+ msg = f"Unexpected type {type(obj).__name__!r}"
537
+ raise TypeError(msg)
538
+
539
+
540
+ def _steal_eager_parquet(
541
+ read_fns: Sequence[Read[IntoDataFrameT]], /
542
+ ) -> Sequence[Scan[nw.LazyFrame[IntoDataFrameT]]] | None:
543
+ if convertable := next((rd for rd in read_fns if rd.include <= is_parquet), None):
544
+ return (_readimpl.into_scan(convertable),)
545
+ return None
546
+
547
+
548
+ @overload
549
+ def _import_guarded(req: _PandasAny, /) -> _Pandas: ...
550
+
551
+
552
+ @overload
553
+ def _import_guarded(req: _NwSupportT, /) -> _NwSupportT: ...
554
+
555
+
556
+ @overload
557
+ def _import_guarded(req: Requirement, /) -> LiteralString: ...
558
+
559
+
560
+ def _import_guarded(req: Any, /) -> LiteralString:
561
+ requires = _requirements(req)
562
+ for name in requires:
563
+ if spec := find_spec(name):
564
+ import_module(spec.name)
565
+ else:
566
+ raise module_not_found(str(req), requires, missing=name)
567
+ return requires[0]
568
+
569
+
570
+ def _requirements(req: Requirement | str, /) -> tuple[Any, ...]:
571
+ req = Requirement(req) if isinstance(req, str) else req
572
+ return (req.name, *req.extras)
.venv/lib/python3.13/site-packages/altair/datasets/_readimpl.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Individual read functions and siuations they support."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from enum import Enum
7
+ from functools import partial, wraps
8
+ from importlib.util import find_spec
9
+ from itertools import chain
10
+ from operator import itemgetter
11
+ from pathlib import Path
12
+ from typing import TYPE_CHECKING, Any, Generic, Literal
13
+
14
+ from narwhals.stable import v1 as nw
15
+ from narwhals.stable.v1.dependencies import get_pandas, get_polars
16
+ from narwhals.stable.v1.typing import IntoDataFrameT
17
+
18
+ from altair.datasets._constraints import (
19
+ is_arrow,
20
+ is_csv,
21
+ is_json,
22
+ is_meta,
23
+ is_not_tabular,
24
+ is_parquet,
25
+ is_spatial,
26
+ is_topo,
27
+ is_tsv,
28
+ )
29
+ from altair.datasets._exceptions import AltairDatasetsError
30
+
31
+ if sys.version_info >= (3, 13):
32
+ from typing import TypeVar
33
+ else:
34
+ from typing_extensions import TypeVar
35
+ if sys.version_info >= (3, 12):
36
+ from typing import TypeAliasType
37
+ else:
38
+ from typing_extensions import TypeAliasType
39
+
40
+ if TYPE_CHECKING:
41
+ from collections.abc import Callable, Iterable, Iterator, Sequence
42
+ from io import IOBase
43
+ from types import ModuleType
44
+
45
+ import pandas as pd
46
+ import polars as pl
47
+ import pyarrow as pa
48
+ from narwhals.stable.v1 import typing as nwt
49
+
50
+ from altair.datasets._constraints import Items, MetaIs
51
+
52
+ __all__ = ["is_available", "pa_any", "pd_only", "pd_pyarrow", "pl_only", "read", "scan"]
53
+
54
+ R = TypeVar("R", bound="nwt.IntoFrame", covariant=True)
55
+ IntoFrameT = TypeVar(
56
+ "IntoFrameT",
57
+ bound="nwt.NativeFrame | nw.DataFrame[Any] | nw.LazyFrame[Any] | nwt.DataFrameLike",
58
+ default=nw.LazyFrame[Any],
59
+ )
60
+ Read = TypeAliasType("Read", "BaseImpl[IntoDataFrameT]", type_params=(IntoDataFrameT,))
61
+ """An *eager* file read function."""
62
+
63
+ Scan = TypeAliasType("Scan", "BaseImpl[IntoFrameT]", type_params=(IntoFrameT,))
64
+ """A *lazy* file read function."""
65
+
66
+
67
+ class Skip(Enum):
68
+ """Falsy sentinel."""
69
+
70
+ skip = 0
71
+
72
+ def __bool__(self) -> Literal[False]:
73
+ return False
74
+
75
+ def __repr__(self) -> Literal["<Skip>"]:
76
+ return "<Skip>"
77
+
78
+
79
+ class BaseImpl(Generic[R]):
80
+ """
81
+ A function wrapped with dataset support constraints.
82
+
83
+ The ``include``, ``exclude`` properties form a `NIMPLY gate`_ (`Material nonimplication`_).
84
+
85
+ Examples
86
+ --------
87
+ For some dataset ``D``, we can use ``fn`` if::
88
+
89
+ impl: BaseImpl
90
+ impl.include(D) and not impl.exclude(D)
91
+
92
+
93
+ .. _NIMPLY gate:
94
+ https://en.m.wikipedia.org/wiki/NIMPLY_gate
95
+ .. _Material nonimplication:
96
+ https://en.m.wikipedia.org/wiki/Material_nonimplication#Truth_table
97
+ """
98
+
99
+ fn: Callable[..., R]
100
+ """Wrapped read/scan function."""
101
+
102
+ include: MetaIs
103
+ """Constraint indicating ``fn`` **supports** reading a dataset."""
104
+
105
+ exclude: MetaIs
106
+ """Constraint *subsetting* ``include`` to mark **non-support**."""
107
+
108
+ def __init__(
109
+ self,
110
+ fn: Callable[..., R],
111
+ include: MetaIs,
112
+ exclude: MetaIs | None,
113
+ kwds: dict[str, Any],
114
+ /,
115
+ ) -> None:
116
+ exclude = exclude or self._exclude_none()
117
+ if not include.isdisjoint(exclude):
118
+ intersection = ", ".join(f"{k}={v!r}" for k, v in include & exclude)
119
+ msg = f"Constraints overlap at: `{intersection}`\ninclude={include!r}\nexclude={exclude!r}"
120
+ raise TypeError(msg)
121
+ object.__setattr__(self, "fn", partial(fn, **kwds) if kwds else fn)
122
+ object.__setattr__(self, "include", include)
123
+ object.__setattr__(self, "exclude", exclude)
124
+
125
+ def unwrap_or_skip(
126
+ self, meta: Items, /
127
+ ) -> Callable[..., R] | type[AltairDatasetsError] | Skip:
128
+ """
129
+ Indicate an action to take for a dataset.
130
+
131
+ **Supports** dataset, use this function::
132
+
133
+ Callable[..., R]
134
+
135
+ Has explicitly marked as **not supported**::
136
+
137
+ type[AltairDatasetsError]
138
+
139
+ No relevant constraints overlap, safe to check others::
140
+
141
+ Skip
142
+ """
143
+ if self.include.issubset(meta):
144
+ return self.fn if self.exclude.isdisjoint(meta) else AltairDatasetsError
145
+ return Skip.skip
146
+
147
+ @classmethod
148
+ def _exclude_none(cls) -> MetaIs:
149
+ """Represents the empty set."""
150
+ return is_meta()
151
+
152
+ def __setattr__(self, name: str, value: Any):
153
+ msg = (
154
+ f"{type(self).__name__!r} is immutable.\n"
155
+ f"Could not assign self.{name} = {value}"
156
+ )
157
+ raise TypeError(msg)
158
+
159
+ @property
160
+ def _inferred_package(self) -> str:
161
+ return _root_package_name(_unwrap_partial(self.fn), "UNKNOWN")
162
+
163
+ def __repr__(self) -> str:
164
+ tp_name = f"{type(self).__name__}[{self._inferred_package}?]"
165
+ return f"{tp_name}({self})"
166
+
167
+ def __str__(self) -> str:
168
+ if isinstance(self.fn, partial):
169
+ fn = _unwrap_partial(self.fn)
170
+ kwds = self.fn.keywords.items()
171
+ fn_repr = f"{fn.__name__}(..., {', '.join(f'{k}={v!r}' for k, v in kwds)})"
172
+ else:
173
+ fn_repr = f"{self.fn.__name__}(...)"
174
+ inc, exc = self.include, self.exclude
175
+ return f"{fn_repr}, {f'include={inc!r}, exclude={exc!r}' if exc else repr(inc)}"
176
+
177
+ @property
178
+ def _relevant_columns(self) -> Iterator[str]:
179
+ name = itemgetter(0)
180
+ yield from (name(obj) for obj in chain(self.include, self.exclude))
181
+
182
+ @property
183
+ def _include_expr(self) -> nw.Expr:
184
+ return (
185
+ self.include.to_expr() & ~self.exclude.to_expr()
186
+ if self.exclude
187
+ else self.include.to_expr()
188
+ )
189
+
190
+ @property
191
+ def _exclude_expr(self) -> nw.Expr:
192
+ if self.exclude:
193
+ return self.include.to_expr() & self.exclude.to_expr()
194
+ msg = f"Unable to generate an exclude expression without setting exclude\n\n{self!r}"
195
+ raise TypeError(msg)
196
+
197
+
198
+ def read(
199
+ fn: Callable[..., IntoDataFrameT],
200
+ /,
201
+ include: MetaIs,
202
+ exclude: MetaIs | None = None,
203
+ **kwds: Any,
204
+ ) -> Read[IntoDataFrameT]:
205
+ return BaseImpl(fn, include, exclude, kwds)
206
+
207
+
208
+ def scan(
209
+ fn: Callable[..., IntoFrameT],
210
+ /,
211
+ include: MetaIs,
212
+ exclude: MetaIs | None = None,
213
+ **kwds: Any,
214
+ ) -> Scan[IntoFrameT]:
215
+ return BaseImpl(fn, include, exclude, kwds)
216
+
217
+
218
+ def into_scan(impl: Read[IntoDataFrameT], /) -> Scan[nw.LazyFrame[IntoDataFrameT]]:
219
+ def scan_fn(
220
+ fn: Callable[..., IntoDataFrameT], /
221
+ ) -> Callable[..., nw.LazyFrame[IntoDataFrameT]]:
222
+ @wraps(_unwrap_partial(fn))
223
+ def wrapper(*args: Any, **kwds: Any) -> nw.LazyFrame[IntoDataFrameT]:
224
+ return nw.from_native(fn(*args, **kwds)).lazy()
225
+
226
+ return wrapper
227
+
228
+ return scan(scan_fn(impl.fn), impl.include, impl.exclude)
229
+
230
+
231
+ def is_available(
232
+ pkg_names: str | Iterable[str], *more_pkg_names: str, require_all: bool = True
233
+ ) -> bool:
234
+ """
235
+ Check for importable package(s), without raising on failure.
236
+
237
+ Parameters
238
+ ----------
239
+ pkg_names, more_pkg_names
240
+ One or more packages.
241
+ require_all
242
+ * ``True`` every package.
243
+ * ``False`` at least one package.
244
+ """
245
+ if not more_pkg_names and isinstance(pkg_names, str):
246
+ return find_spec(pkg_names) is not None
247
+ pkgs_names = pkg_names if not isinstance(pkg_names, str) else (pkg_names,)
248
+ names = chain(pkgs_names, more_pkg_names)
249
+ fn = all if require_all else any
250
+ return fn(find_spec(name) is not None for name in names)
251
+
252
+
253
+ def _root_package_name(obj: Any, default: str, /) -> str:
254
+ # NOTE: Defers importing `inspect`, if we can get the module name
255
+ if hasattr(obj, "__module__"):
256
+ return obj.__module__.split(".")[0]
257
+ else:
258
+ from inspect import getmodule
259
+
260
+ module = getmodule(obj)
261
+ if module and (pkg := module.__package__):
262
+ return pkg.split(".")[0]
263
+ return default
264
+
265
+
266
+ def _unwrap_partial(fn: Any, /) -> Any:
267
+ # NOTE: ``functools._unwrap_partial``
268
+ func = fn
269
+ while isinstance(func, partial):
270
+ func = func.func
271
+ return func
272
+
273
+
274
+ def pl_only() -> tuple[Sequence[Read[pl.DataFrame]], Sequence[Scan[pl.LazyFrame]]]:
275
+ import polars as pl
276
+
277
+ pl_read_json = read(_pl_read_json_roundtrip(get_polars()), is_json)
278
+ if is_available("polars_st"):
279
+ fn_json: Sequence[Read[pl.DataFrame]] = (
280
+ _pl_read_json_polars_st_topo_impl(), # TopoJSON files first
281
+ _pl_read_json_polars_st_impl(), # Then other spatial JSON
282
+ pl_read_json,
283
+ )
284
+ else:
285
+ fn_json = (pl_read_json,)
286
+
287
+ read_fns = (
288
+ read(pl.read_csv, is_csv, try_parse_dates=True),
289
+ *fn_json,
290
+ read(pl.read_csv, is_tsv, separator="\t", try_parse_dates=True),
291
+ read(pl.read_ipc, is_arrow),
292
+ read(pl.read_parquet, is_parquet),
293
+ )
294
+ scan_fns = (scan(pl.scan_parquet, is_parquet),)
295
+ return read_fns, scan_fns
296
+
297
+
298
+ def pd_only() -> Sequence[Read[pd.DataFrame]]:
299
+ import pandas as pd
300
+
301
+ opt: Sequence[Read[pd.DataFrame]]
302
+ if is_available("pyarrow"):
303
+ opt = read(pd.read_feather, is_arrow), read(pd.read_parquet, is_parquet)
304
+ elif is_available("fastparquet"):
305
+ opt = (read(pd.read_parquet, is_parquet),)
306
+ else:
307
+ opt = ()
308
+ pd_read_json = read(_pd_read_json(get_pandas()), is_json, exclude=is_spatial)
309
+ if is_available("geopandas"):
310
+ fn_json: Sequence[Read[pd.DataFrame]] = (
311
+ _pd_read_json_geopandas_impl(),
312
+ pd_read_json,
313
+ )
314
+ else:
315
+ fn_json = (pd_read_json,)
316
+ return (
317
+ read(pd.read_csv, is_csv),
318
+ *fn_json,
319
+ read(pd.read_csv, is_tsv, sep="\t"),
320
+ *opt,
321
+ )
322
+
323
+
324
+ def pd_pyarrow() -> Sequence[Read[pd.DataFrame]]:
325
+ import pandas as pd
326
+
327
+ kwds: dict[str, Any] = {"dtype_backend": "pyarrow"}
328
+ pd_read_json = read(
329
+ _pd_read_json(get_pandas()), is_json, exclude=is_spatial, **kwds
330
+ )
331
+ if is_available("geopandas"):
332
+ fn_json: Sequence[Read[pd.DataFrame]] = (
333
+ _pd_read_json_geopandas_impl(),
334
+ pd_read_json,
335
+ )
336
+ else:
337
+ fn_json = (pd_read_json,)
338
+ return (
339
+ read(pd.read_csv, is_csv, **kwds),
340
+ *fn_json,
341
+ read(pd.read_csv, is_tsv, sep="\t", **kwds),
342
+ read(pd.read_feather, is_arrow, **kwds),
343
+ read(pd.read_parquet, is_parquet, **kwds),
344
+ )
345
+
346
+
347
+ def pa_any() -> Sequence[Read[pa.Table]]:
348
+ from pyarrow import csv, feather, parquet
349
+
350
+ return (
351
+ read(csv.read_csv, is_csv),
352
+ _pa_read_json_impl(),
353
+ read(csv.read_csv, is_tsv, parse_options=csv.ParseOptions(delimiter="\t")), # pyright: ignore[reportCallIssue]
354
+ read(feather.read_table, is_arrow),
355
+ read(parquet.read_table, is_parquet),
356
+ )
357
+
358
+
359
+ def _pa_read_json_impl() -> Read[pa.Table]:
360
+ """
361
+ Mitigating ``pyarrow``'s `line-delimited`_ JSON requirement.
362
+
363
+ .. _line-delimited:
364
+ https://arrow.apache.org/docs/python/json.html#reading-json-files
365
+ """
366
+ if is_available("polars"):
367
+ polars_ns = get_polars()
368
+ if polars_ns is not None:
369
+ return read(_pl_read_json_roundtrip_to_arrow(polars_ns), is_json)
370
+ if is_available("pandas"):
371
+ pandas_ns = get_pandas()
372
+ if pandas_ns is not None:
373
+ return read(_pd_read_json_to_arrow(pandas_ns), is_json, exclude=is_spatial)
374
+ return read(_stdlib_read_json_to_arrow, is_json, exclude=is_not_tabular)
375
+
376
+
377
+ def _pd_read_json(ns: ModuleType, /) -> Callable[..., pd.DataFrame]:
378
+ @wraps(ns.read_json)
379
+ def fn(source: Path | Any, /, **kwds: Any) -> pd.DataFrame:
380
+ return _pd_fix_dtypes_nw(ns.read_json(source, **kwds), **kwds).to_native()
381
+
382
+ return fn
383
+
384
+
385
+ def _pd_read_json_geopandas_impl() -> Read[pd.DataFrame]:
386
+ import geopandas
387
+
388
+ @wraps(geopandas.read_file)
389
+ def fn(source: Path | Any, /, schema: Any = None, **kwds: Any) -> pd.DataFrame:
390
+ return geopandas.read_file(source, **kwds)
391
+
392
+ return read(fn, is_meta(is_spatial=True, suffix=".json"))
393
+
394
+
395
+ def _pd_fix_dtypes_nw(
396
+ df: pd.DataFrame, /, *, dtype_backend: Any = None, **kwds: Any
397
+ ) -> nw.DataFrame[pd.DataFrame]:
398
+ kwds = {"dtype_backend": dtype_backend} if dtype_backend else {}
399
+ return (
400
+ df.convert_dtypes(**kwds)
401
+ .pipe(nw.from_native, eager_only=True)
402
+ .with_columns(nw.selectors.by_dtype(nw.Object).cast(nw.String))
403
+ )
404
+
405
+
406
+ def _pd_read_json_to_arrow(ns: ModuleType, /) -> Callable[..., pa.Table]:
407
+ @wraps(ns.read_json)
408
+ def fn(source: Path | Any, /, *, schema: Any = None, **kwds: Any) -> pa.Table:
409
+ """``schema`` is only here to swallow the ``SchemaCache`` if used."""
410
+ return (
411
+ ns.read_json(source, **kwds)
412
+ .pipe(_pd_fix_dtypes_nw, dtype_backend="pyarrow")
413
+ .to_arrow()
414
+ )
415
+
416
+ return fn
417
+
418
+
419
+ def _pl_read_json_polars_st_impl() -> Read[pl.DataFrame]:
420
+ import polars_st as st
421
+
422
+ @wraps(st.read_file)
423
+ def fn(source: Path | Any, /, schema: Any = None, **kwds: Any) -> pl.DataFrame:
424
+ return st.read_file(source, **kwds)
425
+
426
+ return read(fn, is_meta(is_spatial=True, suffix=".json"))
427
+
428
+
429
+ def _pl_read_json_polars_st_topo_impl() -> Read[pl.DataFrame]:
430
+ import polars_st as st
431
+
432
+ @wraps(st.read_file)
433
+ def fn(source: Path | Any, /, schema: Any = None, **kwds: Any) -> pl.DataFrame:
434
+ # Add TopoJSON driver prefix for URLs
435
+ if isinstance(source, str) and source.startswith("http"):
436
+ source = f"TopoJSON:{source}"
437
+ return st.read_file(source, **kwds)
438
+
439
+ return read(fn, is_topo)
440
+
441
+
442
+ def _pl_read_json_roundtrip(ns: ModuleType, /) -> Callable[..., pl.DataFrame]:
443
+ """
444
+ Try to utilize better date parsing available in `pl.read_csv`_.
445
+
446
+ `pl.read_json`_ has few options when compared to `pl.read_csv`_.
447
+
448
+ Chaining the two together - *where possible* - is still usually faster than `pandas.read_json`_.
449
+
450
+ .. _pl.read_json:
451
+ https://docs.pola.rs/api/python/stable/reference/api/polars.read_json.html
452
+ .. _pl.read_csv:
453
+ https://docs.pola.rs/api/python/stable/reference/api/polars.read_csv.html
454
+ .. _pandas.read_json:
455
+ https://pandas.pydata.org/docs/reference/api/pandas.read_json.html
456
+ """
457
+ from io import BytesIO
458
+
459
+ @wraps(ns.read_json)
460
+ def fn(source: Path | IOBase, /, **kwds: Any) -> pl.DataFrame:
461
+ df = ns.read_json(source, **kwds)
462
+ if any(tp.is_nested() for tp in df.schema.dtypes()):
463
+ return df
464
+ buf = BytesIO()
465
+ df.write_csv(buf)
466
+ if kwds:
467
+ SHARED_KWDS = {"schema", "schema_overrides", "infer_schema_length"}
468
+ kwds = {k: v for k, v in kwds.items() if k in SHARED_KWDS}
469
+ return ns.read_csv(buf, try_parse_dates=True, **kwds)
470
+
471
+ return fn
472
+
473
+
474
+ def _pl_read_json_roundtrip_to_arrow(ns: ModuleType, /) -> Callable[..., pa.Table]:
475
+ eager = _pl_read_json_roundtrip(ns)
476
+
477
+ @wraps(ns.read_json)
478
+ def fn(source: Path | IOBase, /, **kwds: Any) -> pa.Table:
479
+ return eager(source).to_arrow()
480
+
481
+ return fn
482
+
483
+
484
+ def _stdlib_read_json(source: Path | Any, /) -> Any:
485
+ import json
486
+
487
+ if not isinstance(source, Path):
488
+ return json.load(source)
489
+ else:
490
+ with Path(source).open(encoding="utf-8") as f:
491
+ return json.load(f)
492
+
493
+
494
+ def _stdlib_read_json_to_arrow(source: Path | Any, /, **kwds: Any) -> pa.Table:
495
+ import pyarrow as pa
496
+
497
+ rows: list[dict[str, Any]] = _stdlib_read_json(source)
498
+ try:
499
+ return pa.Table.from_pylist(rows, **kwds)
500
+ except TypeError:
501
+ import csv
502
+ import io
503
+
504
+ from pyarrow import csv as pa_csv
505
+
506
+ with io.StringIO() as f:
507
+ writer = csv.DictWriter(f, rows[0].keys(), dialect=csv.unix_dialect)
508
+ writer.writeheader()
509
+ writer.writerows(rows)
510
+ with io.BytesIO(f.getvalue().encode()) as f2:
511
+ return pa_csv.read_csv(f2)
.venv/lib/python3.13/site-packages/altair/datasets/_typing.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The contents of this file are automatically written by
2
+ # tools/datasets.__init__.py. Do not modify directly.
3
+
4
+ from __future__ import annotations
5
+
6
+ import sys
7
+ from typing import Literal
8
+
9
+ if sys.version_info >= (3, 15):
10
+ from typing import TypedDict
11
+ else:
12
+ from typing_extensions import TypedDict
13
+
14
+ if sys.version_info >= (3, 11):
15
+ from typing import LiteralString
16
+ else:
17
+ from typing_extensions import LiteralString
18
+
19
+ if sys.version_info >= (3, 10):
20
+ from typing import TypeAlias
21
+ else:
22
+ from typing_extensions import TypeAlias
23
+
24
+
25
+ __all__ = ["Dataset", "Extension", "Metadata"]
26
+
27
+ Dataset: TypeAlias = Literal[
28
+ "airports",
29
+ "annual_precip",
30
+ "anscombe",
31
+ "barley",
32
+ "birdstrikes",
33
+ "budget",
34
+ "budgets",
35
+ "burtin",
36
+ "cars",
37
+ "co2_concentration",
38
+ "countries",
39
+ "crimea",
40
+ "disasters",
41
+ "driving",
42
+ "earthquakes",
43
+ "ffox",
44
+ "flare",
45
+ "flare_dependencies",
46
+ "flights_10k",
47
+ "flights_200k_arrow",
48
+ "flights_200k_json",
49
+ "flights_20k",
50
+ "flights_2k",
51
+ "flights_3m",
52
+ "flights_5k",
53
+ "flights_airport",
54
+ "football",
55
+ "gapminder",
56
+ "gapminder_health_income",
57
+ "gimp",
58
+ "github",
59
+ "global_temp",
60
+ "icon_7zip",
61
+ "income",
62
+ "iowa_electricity",
63
+ "jobs",
64
+ "la_riots",
65
+ "london_boroughs",
66
+ "london_centroids",
67
+ "london_tube_lines",
68
+ "lookup_groups",
69
+ "lookup_people",
70
+ "miserables",
71
+ "monarchs",
72
+ "movies",
73
+ "normal_2d",
74
+ "obesity",
75
+ "ohlc",
76
+ "penguins",
77
+ "platformer_terrain",
78
+ "political_contributions",
79
+ "population",
80
+ "population_engineers_hurricanes",
81
+ "seattle_weather",
82
+ "seattle_weather_hourly_normals",
83
+ "sp500",
84
+ "sp500_2000",
85
+ "species",
86
+ "stocks",
87
+ "udistrict",
88
+ "unemployment",
89
+ "unemployment_across_industries",
90
+ "uniform_2d",
91
+ "us_10m",
92
+ "us_employment",
93
+ "us_state_capitals",
94
+ "volcano",
95
+ "weather",
96
+ "weekly_weather",
97
+ "wheat",
98
+ "windvectors",
99
+ "world_110m",
100
+ "zipcodes",
101
+ ]
102
+ Extension: TypeAlias = Literal[".arrow", ".csv", ".json", ".parquet", ".png", ".tsv"]
103
+
104
+
105
+ class Metadata(TypedDict, total=False):
106
+ """
107
+ Full schema for ``metadata.parquet``.
108
+
109
+ Parameters
110
+ ----------
111
+ dataset_name
112
+ Name of the dataset from the resource name field.
113
+ suffix
114
+ File extension/`Path.suffix`_.
115
+ file_name
116
+ Equivalent to `Path.name`_.
117
+ bytes
118
+ File size in *bytes*.
119
+ is_image
120
+ Only accessible via url.
121
+ is_tabular
122
+ Can be read as tabular data.
123
+ is_geo
124
+ `GeoJSON`_ format.
125
+ is_topo
126
+ `TopoJSON`_ format.
127
+ is_spatial
128
+ Any geospatial format. Only natively supported by ``polars``.
129
+ is_json
130
+ Not supported natively by ``pyarrow``.
131
+ has_schema
132
+ Data types available for improved ``pandas`` parsing.
133
+ sha
134
+ Unique hash for the dataset.
135
+
136
+ .. note::
137
+ E.g. if the dataset did *not* change between ``v1.0.0``-``v2.0.0``;
138
+
139
+ then this value would remain stable.
140
+ url
141
+ Remote url used to access dataset.
142
+
143
+ .. _Path.stem:
144
+ https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem
145
+ .. _Path.name:
146
+ https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.name
147
+ .. _Path.suffix:
148
+ https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.suffix
149
+ .. _GeoJSON:
150
+ https://en.wikipedia.org/wiki/GeoJSON
151
+ .. _TopoJSON:
152
+ https://en.wikipedia.org/wiki/GeoJSON#TopoJSON
153
+
154
+
155
+ Examples
156
+ --------
157
+ ``Metadata`` keywords form constraints to filter a table like the below sample:
158
+
159
+ ```
160
+ shape: (73, 13)
161
+ ┌────────────────┬────────┬────────────────┬───┬───────────────┬───────────────┐
162
+ │ dataset_name ┆ suffix ┆ file_name ┆ … ┆ sha ┆ url │
163
+ │ --- ┆ --- ┆ --- ┆ ┆ --- ┆ --- │
164
+ │ str ┆ str ┆ str ┆ ┆ str ┆ str │
165
+ ╞════════════════╪════════╪════════════════╪═══╪═══════════════╪═══════════════╡
166
+ │ airports ┆ .csv ┆ airports.csv ┆ … ┆ 608ba6d51fa70 ┆ https://cdn.j │
167
+ │ ┆ ┆ ┆ ┆ 584c3fa1d31e… ┆ sdelivr.net/… │
168
+ │ annual_precip ┆ .json ┆ annual-precip. ┆ … ┆ 719e73406cfc0 ┆ https://cdn.j │
169
+ │ ┆ ┆ json ┆ ┆ 8f16dda65151… ┆ sdelivr.net/… │
170
+ │ anscombe ┆ .json ┆ anscombe.json ┆ … ┆ 11ae97090b626 ┆ https://cdn.j │
171
+ │ ┆ ┆ ┆ ┆ 3bdf0c866115… ┆ sdelivr.net/… │
172
+ │ barley ┆ .json ┆ barley.json ┆ … ┆ 8dc50de2509b6 ┆ https://cdn.j │
173
+ │ ┆ ┆ ┆ ┆ e197ce95c24c… ┆ sdelivr.net/… │
174
+ │ birdstrikes ┆ .csv ┆ birdstrikes.cs ┆ … ┆ 1b8b190c9bc02 ┆ https://cdn.j │
175
+ │ ┆ ┆ v ┆ ┆ ef7bcbfe5a8a… ┆ sdelivr.net/… │
176
+ │ … ┆ … ┆ … ┆ … ┆ … ┆ … │
177
+ │ weekly_weather ┆ .json ┆ weekly-weather ┆ … ┆ bd42a3e2403e7 ┆ https://cdn.j │
178
+ │ ┆ ┆ .json ┆ ┆ ccd6baaa89f9… ┆ sdelivr.net/… │
179
+ │ wheat ┆ .json ┆ wheat.json ┆ … ┆ cde46b43fc82f ┆ https://cdn.j │
180
+ │ ┆ ┆ ┆ ┆ 4c3c2a37ddcf… ┆ sdelivr.net/… │
181
+ │ windvectors ┆ .csv ┆ windvectors.cs ┆ … ┆ ed686b0ba613a ┆ https://cdn.j │
182
+ │ ┆ ┆ v ┆ ┆ bd59d09fcd94… ┆ sdelivr.net/… │
183
+ │ world_110m ┆ .json ┆ world-110m.jso ┆ … ┆ a1ce852de6f27 ┆ https://cdn.j │
184
+ │ ┆ ┆ n ┆ ┆ 13c94c0c2840… ┆ sdelivr.net/… │
185
+ │ zipcodes ┆ .csv ┆ zipcodes.csv ┆ … ┆ d3df33e12be0d ┆ https://cdn.j │
186
+ │ ┆ ┆ ┆ ┆ 0544c95f1bd4… ┆ sdelivr.net/… │
187
+ └────────────────┴────────┴────────────────┴───┴───────────────┴───────────────┘
188
+ ```
189
+ """
190
+
191
+ dataset_name: Dataset | LiteralString
192
+ suffix: Extension
193
+ file_name: str
194
+ bytes: int
195
+ is_image: bool
196
+ is_tabular: bool
197
+ is_geo: bool
198
+ is_topo: bool
199
+ is_spatial: bool
200
+ is_json: bool
201
+ has_schema: bool
202
+ sha: str
203
+ url: str
204
+
205
+
206
+ FlFieldStr: TypeAlias = Literal[
207
+ "integer",
208
+ "number",
209
+ "boolean",
210
+ "string",
211
+ "object",
212
+ "array",
213
+ "date",
214
+ "datetime",
215
+ "time",
216
+ "duration",
217
+ ]
218
+ """
219
+ String representation of `frictionless`_ `Field Types`_.
220
+
221
+ .. _frictionless:
222
+ https://github.com/frictionlessdata/frictionless-py
223
+ .. _Field Types:
224
+ https://datapackage.org/standard/table-schema/#field-types
225
+ """
.venv/lib/python3.13/site-packages/altair/expr/__init__.py ADDED
@@ -0,0 +1,2086 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The contents of this file are automatically written by
2
+ # tools/generate_schema_wrapper.py. Do not modify directly.
3
+
4
+ """Tools for creating transform & filter expressions with a python syntax."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import sys
9
+ from typing import TYPE_CHECKING, Any
10
+
11
+ from altair.expr.core import ConstExpression, FunctionExpression
12
+ from altair.vegalite.v6.schema.core import ExprRef as _ExprRef
13
+
14
+ if sys.version_info >= (3, 12):
15
+ from typing import override
16
+ else:
17
+ from typing_extensions import override
18
+
19
+ if TYPE_CHECKING:
20
+ from altair.expr.core import Expression, IntoExpression
21
+
22
+
23
+ class _ExprMeta(type):
24
+ """
25
+ Metaclass for :class:`expr`.
26
+
27
+ Currently providing read-only class properties, representing JavaScript constants.
28
+ """
29
+
30
+ @property
31
+ def NaN(cls) -> Expression:
32
+ """Not a number (same as JavaScript literal NaN)."""
33
+ return ConstExpression("NaN")
34
+
35
+ @property
36
+ def LN10(cls) -> Expression:
37
+ """The natural log of 10 (alias to Math.LN10)."""
38
+ return ConstExpression("LN10")
39
+
40
+ @property
41
+ def E(cls) -> Expression:
42
+ """The transcendental number e (alias to Math.E)."""
43
+ return ConstExpression("E")
44
+
45
+ @property
46
+ def LOG10E(cls) -> Expression:
47
+ """The base 10 logarithm e (alias to Math.LOG10E)."""
48
+ return ConstExpression("LOG10E")
49
+
50
+ @property
51
+ def LOG2E(cls) -> Expression:
52
+ """The base 2 logarithm of e (alias to Math.LOG2E)."""
53
+ return ConstExpression("LOG2E")
54
+
55
+ @property
56
+ def SQRT1_2(cls) -> Expression:
57
+ """The square root of 0.5 (alias to Math.SQRT1_2)."""
58
+ return ConstExpression("SQRT1_2")
59
+
60
+ @property
61
+ def LN2(cls) -> Expression:
62
+ """The natural log of 2 (alias to Math.LN2)."""
63
+ return ConstExpression("LN2")
64
+
65
+ @property
66
+ def SQRT2(cls) -> Expression:
67
+ """The square root of 2 (alias to Math.SQRT1_2)."""
68
+ return ConstExpression("SQRT2")
69
+
70
+ @property
71
+ def PI(cls) -> Expression:
72
+ """The transcendental number pi (alias to Math.PI)."""
73
+ return ConstExpression("PI")
74
+
75
+
76
+ class expr(_ExprRef, metaclass=_ExprMeta):
77
+ """
78
+ Utility providing *constants* and *classmethods* to construct expressions.
79
+
80
+ `Expressions`_ can be used to write basic formulas that enable custom interactions.
81
+
82
+ Alternatively, an `inline expression`_ may be defined via :class:`expr()`.
83
+
84
+ Parameters
85
+ ----------
86
+ expr: str
87
+ A `vega expression`_ string.
88
+
89
+ Returns
90
+ -------
91
+ ``ExprRef``
92
+
93
+ .. _Expressions:
94
+ https://altair-viz.github.io/user_guide/interactions/expressions.html
95
+ .. _inline expression:
96
+ https://altair-viz.github.io/user_guide/interactions/expressions.html#inline-expressions
97
+ .. _vega expression:
98
+ https://vega.github.io/vega/docs/expressions/
99
+
100
+ Examples
101
+ --------
102
+ >>> import altair as alt
103
+
104
+ >>> bind_range = alt.binding_range(min=100, max=300, name="Slider value: ")
105
+ >>> param_width = alt.param(bind=bind_range, name="param_width")
106
+ >>> param_color = alt.param(
107
+ ... expr=alt.expr.if_(param_width < 200, "red", "black"),
108
+ ... name="param_color",
109
+ ... )
110
+ >>> y = alt.Y("yval").axis(titleColor=param_color)
111
+
112
+ >>> y
113
+ Y({
114
+ axis: {'titleColor': Parameter('param_color', VariableParameter({
115
+ expr: if((param_width < 200),'red','black'),
116
+ name: 'param_color'
117
+ }))},
118
+ shorthand: 'yval'
119
+ })
120
+
121
+ .. _Number.isNaN:
122
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNan
123
+ .. _Number.isFinite:
124
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite
125
+ .. _Math.abs:
126
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs
127
+ .. _Math.acos:
128
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/acos
129
+ .. _Math.asin:
130
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/asin
131
+ .. _Math.atan:
132
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan
133
+ .. _Math.atan2:
134
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2
135
+ .. _Math.ceil:
136
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil
137
+ .. _Math.cos:
138
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cos
139
+ .. _Math.exp:
140
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/exp
141
+ .. _Math.floor:
142
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
143
+ .. _Math.hypot:
144
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot
145
+ .. _Math.log:
146
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log
147
+ .. _Math.max:
148
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
149
+ .. _Math.min:
150
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min
151
+ .. _Math.pow:
152
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow
153
+ .. _Math.random:
154
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
155
+ .. _Math.round:
156
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
157
+ .. _Math.sin:
158
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sin
159
+ .. _Math.sqrt:
160
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt
161
+ .. _Math.tan:
162
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/tan
163
+ .. _normal (Gaussian) probability distribution:
164
+ https://en.wikipedia.org/wiki/Normal_distribution
165
+ .. _cumulative distribution function:
166
+ https://en.wikipedia.org/wiki/Cumulative_distribution_function
167
+ .. _probability density function:
168
+ https://en.wikipedia.org/wiki/Probability_density_function
169
+ .. _log-normal probability distribution:
170
+ https://en.wikipedia.org/wiki/Log-normal_distribution
171
+ .. _continuous uniform probability distribution:
172
+ https://en.wikipedia.org/wiki/Continuous_uniform_distribution
173
+ .. _*unit*:
174
+ https://vega.github.io/vega/docs/api/time/#time-units
175
+ .. _ascending from Vega Utils:
176
+ https://vega.github.io/vega/docs/api/util/#ascending
177
+ .. _JavaScript's String.replace:
178
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
179
+ .. _Base64:
180
+ https://developer.mozilla.org/en-US/docs/Glossary/Base64
181
+ .. _ASCII:
182
+ https://developer.mozilla.org/en-US/docs/Glossary/ASCII
183
+ .. _Window.btoa():
184
+ https://developer.mozilla.org/en-US/docs/Web/API/Window/btoa
185
+ .. _Window.atob():
186
+ https://developer.mozilla.org/en-US/docs/Web/API/Window/atob
187
+ .. _d3-format specifier:
188
+ https://github.com/d3/d3-format/
189
+ .. _*units*:
190
+ https://vega.github.io/vega/docs/api/time/#time-units
191
+ .. _timeUnitSpecifier API documentation:
192
+ https://vega.github.io/vega/docs/api/time/#timeUnitSpecifier
193
+ .. _timeFormat:
194
+ https://vega.github.io/vega/docs/expressions/#timeFormat
195
+ .. _utcFormat:
196
+ https://vega.github.io/vega/docs/expressions/#utcFormat
197
+ .. _d3-time-format specifier:
198
+ https://github.com/d3/d3-time-format/
199
+ .. _TimeMultiFormat object:
200
+ https://vega.github.io/vega/docs/types/#TimeMultiFormat
201
+ .. _UTC:
202
+ https://en.wikipedia.org/wiki/Coordinated_Universal_Time
203
+ .. _JavaScript's RegExp:
204
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
205
+ .. _RGB:
206
+ https://en.wikipedia.org/wiki/RGB_color_model
207
+ .. _d3-color's rgb function:
208
+ https://github.com/d3/d3-color#rgb
209
+ .. _HSL:
210
+ https://en.wikipedia.org/wiki/HSL_and_HSV
211
+ .. _d3-color's hsl function:
212
+ https://github.com/d3/d3-color#hsl
213
+ .. _CIE LAB:
214
+ https://en.wikipedia.org/wiki/Lab_color_space#CIELAB
215
+ .. _d3-color's lab function:
216
+ https://github.com/d3/d3-color#lab
217
+ .. _HCL:
218
+ https://en.wikipedia.org/wiki/Lab_color_space#CIELAB
219
+ .. _d3-color's hcl function:
220
+ https://github.com/d3/d3-color#hcl
221
+ .. _W3C Web Content Accessibility Guidelines:
222
+ https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
223
+ .. _continuous color scheme:
224
+ https://vega.github.io/vega/docs/schemes
225
+ .. _geoArea:
226
+ https://github.com/d3/d3-geo#geoArea
227
+ .. _path.area:
228
+ https://github.com/d3/d3-geo#path_area
229
+ .. _geoBounds:
230
+ https://github.com/d3/d3-geo#geoBounds
231
+ .. _path.bounds:
232
+ https://github.com/d3/d3-geo#path_bounds
233
+ .. _geoCentroid:
234
+ https://github.com/d3/d3-geo#geoCentroid
235
+ .. _path.centroid:
236
+ https://github.com/d3/d3-geo#path_centroid
237
+ .. _window.screen:
238
+ https://developer.mozilla.org/en-US/docs/Web/API/Window/screen
239
+ """
240
+
241
+ @override
242
+ def __new__(cls: type[_ExprRef], expr: str) -> _ExprRef: # type: ignore[misc]
243
+ return _ExprRef(expr=expr)
244
+
245
+ @classmethod
246
+ def isArray(cls, value: IntoExpression, /) -> Expression:
247
+ """Returns true if ``value`` is an array, false otherwise."""
248
+ return FunctionExpression("isArray", (value,))
249
+
250
+ @classmethod
251
+ def isBoolean(cls, value: IntoExpression, /) -> Expression:
252
+ """Returns true if ``value`` is a boolean (``true`` or ``false``), false otherwise."""
253
+ return FunctionExpression("isBoolean", (value,))
254
+
255
+ @classmethod
256
+ def isDate(cls, value: IntoExpression, /) -> Expression:
257
+ """
258
+ Returns true if ``value`` is a Date object, false otherwise.
259
+
260
+ This method will return false for timestamp numbers or date-formatted strings; it recognizes
261
+ Date objects only.
262
+ """
263
+ return FunctionExpression("isDate", (value,))
264
+
265
+ @classmethod
266
+ def isDefined(cls, value: IntoExpression, /) -> Expression:
267
+ """
268
+ Returns true if ``value`` is a defined value, false if ``value`` equals ``undefined``.
269
+
270
+ This method will return true for ``null`` and ``NaN`` values.
271
+ """
272
+ return FunctionExpression("isDefined", (value,))
273
+
274
+ @classmethod
275
+ def isNumber(cls, value: IntoExpression, /) -> Expression:
276
+ """
277
+ Returns true if ``value`` is a number, false otherwise.
278
+
279
+ ``NaN`` and ``Infinity`` are considered numbers.
280
+ """
281
+ return FunctionExpression("isNumber", (value,))
282
+
283
+ @classmethod
284
+ def isObject(cls, value: IntoExpression, /) -> Expression:
285
+ """Returns true if ``value`` is an object (including arrays and Dates), false otherwise."""
286
+ return FunctionExpression("isObject", (value,))
287
+
288
+ @classmethod
289
+ def isRegExp(cls, value: IntoExpression, /) -> Expression:
290
+ """Returns true if ``value`` is a RegExp (regular expression) object, false otherwise."""
291
+ return FunctionExpression("isRegExp", (value,))
292
+
293
+ @classmethod
294
+ def isString(cls, value: IntoExpression, /) -> Expression:
295
+ """Returns true if ``value`` is a string, false otherwise."""
296
+ return FunctionExpression("isString", (value,))
297
+
298
+ @classmethod
299
+ def isValid(cls, value: IntoExpression, /) -> Expression:
300
+ """Returns true if ``value`` is not ``null``, ``undefined``, or ``NaN``, false otherwise."""
301
+ return FunctionExpression("isValid", (value,))
302
+
303
+ @classmethod
304
+ def toBoolean(cls, value: IntoExpression, /) -> Expression:
305
+ """
306
+ Coerces the input ``value`` to a string.
307
+
308
+ Null values and empty strings are mapped to ``null``.
309
+ """
310
+ return FunctionExpression("toBoolean", (value,))
311
+
312
+ @classmethod
313
+ def toDate(cls, value: IntoExpression, /) -> Expression:
314
+ """
315
+ Coerces the input ``value`` to a Date instance.
316
+
317
+ Null values and empty strings are mapped to ``null``. If an optional *parser* function is
318
+ provided, it is used to perform date parsing, otherwise ``Date.parse`` is used. Be aware
319
+ that ``Date.parse`` has different implementations across browsers!
320
+ """
321
+ return FunctionExpression("toDate", (value,))
322
+
323
+ @classmethod
324
+ def toNumber(cls, value: IntoExpression, /) -> Expression:
325
+ """
326
+ Coerces the input ``value`` to a number.
327
+
328
+ Null values and empty strings are mapped to ``null``.
329
+ """
330
+ return FunctionExpression("toNumber", (value,))
331
+
332
+ @classmethod
333
+ def toString(cls, value: IntoExpression, /) -> Expression:
334
+ """
335
+ Coerces the input ``value`` to a string.
336
+
337
+ Null values and empty strings are mapped to ``null``.
338
+ """
339
+ return FunctionExpression("toString", (value,))
340
+
341
+ @classmethod
342
+ def if_(
343
+ cls,
344
+ test: IntoExpression,
345
+ thenValue: IntoExpression,
346
+ elseValue: IntoExpression,
347
+ /,
348
+ ) -> Expression:
349
+ """
350
+ If ``test`` is truthy, returns ``thenValue``.
351
+
352
+ Otherwise, returns ``elseValue``. The *if* function is equivalent to the ternary operator
353
+ ``a ? b : c``.
354
+ """
355
+ return FunctionExpression("if", (test, thenValue, elseValue))
356
+
357
+ @classmethod
358
+ def isNaN(cls, value: IntoExpression, /) -> Expression:
359
+ """
360
+ Returns true if ``value`` is not a number.
361
+
362
+ Same as JavaScript's `Number.isNaN`_.
363
+
364
+ .. _Number.isNaN:
365
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNan
366
+ """
367
+ return FunctionExpression("isNaN", (value,))
368
+
369
+ @classmethod
370
+ def isFinite(cls, value: IntoExpression, /) -> Expression:
371
+ """
372
+ Returns true if ``value`` is a finite number.
373
+
374
+ Same as JavaScript's `Number.isFinite`_.
375
+
376
+ .. _Number.isFinite:
377
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite
378
+ """
379
+ return FunctionExpression("isFinite", (value,))
380
+
381
+ @classmethod
382
+ def abs(cls, value: IntoExpression, /) -> Expression:
383
+ """
384
+ Returns the absolute value of ``value``.
385
+
386
+ Same as JavaScript's `Math.abs`_.
387
+
388
+ .. _Math.abs:
389
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs
390
+ """
391
+ return FunctionExpression("abs", (value,))
392
+
393
+ @classmethod
394
+ def acos(cls, value: IntoExpression, /) -> Expression:
395
+ """
396
+ Trigonometric arccosine.
397
+
398
+ Same as JavaScript's `Math.acos`_.
399
+
400
+ .. _Math.acos:
401
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/acos
402
+ """
403
+ return FunctionExpression("acos", (value,))
404
+
405
+ @classmethod
406
+ def asin(cls, value: IntoExpression, /) -> Expression:
407
+ """
408
+ Trigonometric arcsine.
409
+
410
+ Same as JavaScript's `Math.asin`_.
411
+
412
+ .. _Math.asin:
413
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/asin
414
+ """
415
+ return FunctionExpression("asin", (value,))
416
+
417
+ @classmethod
418
+ def atan(cls, value: IntoExpression, /) -> Expression:
419
+ """
420
+ Trigonometric arctangent.
421
+
422
+ Same as JavaScript's `Math.atan`_.
423
+
424
+ .. _Math.atan:
425
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan
426
+ """
427
+ return FunctionExpression("atan", (value,))
428
+
429
+ @classmethod
430
+ def atan2(cls, dy: IntoExpression, dx: IntoExpression, /) -> Expression:
431
+ """
432
+ Returns the arctangent of *dy / dx*.
433
+
434
+ Same as JavaScript's `Math.atan2`_.
435
+
436
+ .. _Math.atan2:
437
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2
438
+ """
439
+ return FunctionExpression("atan2", (dy, dx))
440
+
441
+ @classmethod
442
+ def ceil(cls, value: IntoExpression, /) -> Expression:
443
+ """
444
+ Rounds ``value`` to the nearest integer of equal or greater value.
445
+
446
+ Same as JavaScript's `Math.ceil`_.
447
+
448
+ .. _Math.ceil:
449
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil
450
+ """
451
+ return FunctionExpression("ceil", (value,))
452
+
453
+ @classmethod
454
+ def clamp(
455
+ cls, value: IntoExpression, min: IntoExpression, max: IntoExpression, /
456
+ ) -> Expression:
457
+ """Restricts ``value`` to be between the specified ``min`` and ``max``."""
458
+ return FunctionExpression("clamp", (value, min, max))
459
+
460
+ @classmethod
461
+ def cos(cls, value: IntoExpression, /) -> Expression:
462
+ """
463
+ Trigonometric cosine.
464
+
465
+ Same as JavaScript's `Math.cos`_.
466
+
467
+ .. _Math.cos:
468
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cos
469
+ """
470
+ return FunctionExpression("cos", (value,))
471
+
472
+ @classmethod
473
+ def exp(cls, exponent: IntoExpression, /) -> Expression:
474
+ """
475
+ Returns the value of *e* raised to the provided ``exponent``.
476
+
477
+ Same as JavaScript's `Math.exp`_.
478
+
479
+ .. _Math.exp:
480
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/exp
481
+ """
482
+ return FunctionExpression("exp", (exponent,))
483
+
484
+ @classmethod
485
+ def floor(cls, value: IntoExpression, /) -> Expression:
486
+ """
487
+ Rounds ``value`` to the nearest integer of equal or lower value.
488
+
489
+ Same as JavaScript's `Math.floor`_.
490
+
491
+ .. _Math.floor:
492
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
493
+ """
494
+ return FunctionExpression("floor", (value,))
495
+
496
+ @classmethod
497
+ def hypot(cls, value: IntoExpression, /) -> Expression:
498
+ """
499
+ Returns the square root of the sum of squares of its arguments.
500
+
501
+ Same as JavaScript's `Math.hypot`_.
502
+
503
+ .. _Math.hypot:
504
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot
505
+ """
506
+ return FunctionExpression("hypot", (value,))
507
+
508
+ @classmethod
509
+ def log(cls, value: IntoExpression, /) -> Expression:
510
+ """
511
+ Returns the natural logarithm of ``value``.
512
+
513
+ Same as JavaScript's `Math.log`_.
514
+
515
+ .. _Math.log:
516
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log
517
+ """
518
+ return FunctionExpression("log", (value,))
519
+
520
+ @classmethod
521
+ def max(
522
+ cls, value1: IntoExpression, value2: IntoExpression, *args: Any
523
+ ) -> Expression:
524
+ """
525
+ Returns the maximum argument value.
526
+
527
+ Same as JavaScript's `Math.max`_.
528
+
529
+ .. _Math.max:
530
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
531
+ """
532
+ return FunctionExpression("max", (value1, value2, *args))
533
+
534
+ @classmethod
535
+ def min(
536
+ cls, value1: IntoExpression, value2: IntoExpression, *args: Any
537
+ ) -> Expression:
538
+ """
539
+ Returns the minimum argument value.
540
+
541
+ Same as JavaScript's `Math.min`_.
542
+
543
+ .. _Math.min:
544
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min
545
+ """
546
+ return FunctionExpression("min", (value1, value2, *args))
547
+
548
+ @classmethod
549
+ def pow(cls, value: IntoExpression, exponent: IntoExpression, /) -> Expression:
550
+ """
551
+ Returns ``value`` raised to the given ``exponent``.
552
+
553
+ Same as JavaScript's `Math.pow`_.
554
+
555
+ .. _Math.pow:
556
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow
557
+ """
558
+ return FunctionExpression("pow", (value, exponent))
559
+
560
+ @classmethod
561
+ def random(cls) -> Expression:
562
+ """
563
+ Returns a pseudo-random number in the range [0,1).
564
+
565
+ Same as JavaScript's `Math.random`_.
566
+
567
+ .. _Math.random:
568
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
569
+ """
570
+ return FunctionExpression("random", ())
571
+
572
+ @classmethod
573
+ def round(cls, value: IntoExpression, /) -> Expression:
574
+ """
575
+ Rounds ``value`` to the nearest integer.
576
+
577
+ Same as JavaScript's `Math.round`_.
578
+
579
+ .. _Math.round:
580
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
581
+ """
582
+ return FunctionExpression("round", (value,))
583
+
584
+ @classmethod
585
+ def sin(cls, value: IntoExpression, /) -> Expression:
586
+ """
587
+ Trigonometric sine.
588
+
589
+ Same as JavaScript's `Math.sin`_.
590
+
591
+ .. _Math.sin:
592
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sin
593
+ """
594
+ return FunctionExpression("sin", (value,))
595
+
596
+ @classmethod
597
+ def sqrt(cls, value: IntoExpression, /) -> Expression:
598
+ """
599
+ Square root function.
600
+
601
+ Same as JavaScript's `Math.sqrt`_.
602
+
603
+ .. _Math.sqrt:
604
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt
605
+ """
606
+ return FunctionExpression("sqrt", (value,))
607
+
608
+ @classmethod
609
+ def tan(cls, value: IntoExpression, /) -> Expression:
610
+ """
611
+ Trigonometric tangent.
612
+
613
+ Same as JavaScript's `Math.tan`_.
614
+
615
+ .. _Math.tan:
616
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/tan
617
+ """
618
+ return FunctionExpression("tan", (value,))
619
+
620
+ @classmethod
621
+ def sampleNormal(
622
+ cls, mean: IntoExpression = None, stdev: IntoExpression = None, /
623
+ ) -> Expression:
624
+ """
625
+ Returns a sample from a univariate `normal (Gaussian) probability distribution`_ with specified ``mean`` and standard deviation ``stdev``.
626
+
627
+ If unspecified, the mean defaults to ``0`` and the standard deviation defaults to ``1``.
628
+
629
+ .. _normal (Gaussian) probability distribution:
630
+ https://en.wikipedia.org/wiki/Normal_distribution
631
+ """
632
+ return FunctionExpression("sampleNormal", (mean, stdev))
633
+
634
+ @classmethod
635
+ def cumulativeNormal(
636
+ cls,
637
+ value: IntoExpression,
638
+ mean: IntoExpression = None,
639
+ stdev: IntoExpression = None,
640
+ /,
641
+ ) -> Expression:
642
+ """
643
+ Returns the value of the `cumulative distribution function`_ at the given input domain ``value`` for a normal distribution with specified ``mean`` and standard deviation ``stdev``.
644
+
645
+ If unspecified, the mean defaults to ``0`` and the standard deviation defaults to ``1``.
646
+
647
+ .. _cumulative distribution function:
648
+ https://en.wikipedia.org/wiki/Cumulative_distribution_function
649
+ """
650
+ return FunctionExpression("cumulativeNormal", (value, mean, stdev))
651
+
652
+ @classmethod
653
+ def densityNormal(
654
+ cls,
655
+ value: IntoExpression,
656
+ mean: IntoExpression = None,
657
+ stdev: IntoExpression = None,
658
+ /,
659
+ ) -> Expression:
660
+ """
661
+ Returns the value of the `probability density function`_ at the given input domain ``value``, for a normal distribution with specified ``mean`` and standard deviation ``stdev``.
662
+
663
+ If unspecified, the mean defaults to ``0`` and the standard deviation defaults to ``1``.
664
+
665
+ .. _probability density function:
666
+ https://en.wikipedia.org/wiki/Probability_density_function
667
+ """
668
+ return FunctionExpression("densityNormal", (value, mean, stdev))
669
+
670
+ @classmethod
671
+ def quantileNormal(
672
+ cls,
673
+ probability: IntoExpression,
674
+ mean: IntoExpression = None,
675
+ stdev: IntoExpression = None,
676
+ /,
677
+ ) -> Expression:
678
+ """
679
+ Returns the quantile value (the inverse of the `cumulative distribution function`_) for the given input ``probability``, for a normal distribution with specified ``mean`` and standard deviation ``stdev``.
680
+
681
+ If unspecified, the mean defaults to ``0`` and the standard deviation defaults to ``1``.
682
+
683
+ .. _cumulative distribution function:
684
+ https://en.wikipedia.org/wiki/Cumulative_distribution_function
685
+ """
686
+ return FunctionExpression("quantileNormal", (probability, mean, stdev))
687
+
688
+ @classmethod
689
+ def sampleLogNormal(
690
+ cls, mean: IntoExpression = None, stdev: IntoExpression = None, /
691
+ ) -> Expression:
692
+ """
693
+ Returns a sample from a univariate `log-normal probability distribution`_ with specified log ``mean`` and log standard deviation ``stdev``.
694
+
695
+ If unspecified, the log mean defaults to ``0`` and the log standard deviation defaults to
696
+ ``1``.
697
+
698
+ .. _log-normal probability distribution:
699
+ https://en.wikipedia.org/wiki/Log-normal_distribution
700
+ """
701
+ return FunctionExpression("sampleLogNormal", (mean, stdev))
702
+
703
+ @classmethod
704
+ def cumulativeLogNormal(
705
+ cls,
706
+ value: IntoExpression,
707
+ mean: IntoExpression = None,
708
+ stdev: IntoExpression = None,
709
+ /,
710
+ ) -> Expression:
711
+ """
712
+ Returns the value of the `cumulative distribution function`_ at the given input domain ``value`` for a log-normal distribution with specified log ``mean`` and log standard deviation ``stdev``.
713
+
714
+ If unspecified, the log mean defaults to ``0`` and the log standard deviation defaults to
715
+ ``1``.
716
+
717
+ .. _cumulative distribution function:
718
+ https://en.wikipedia.org/wiki/Cumulative_distribution_function
719
+ """
720
+ return FunctionExpression("cumulativeLogNormal", (value, mean, stdev))
721
+
722
+ @classmethod
723
+ def densityLogNormal(
724
+ cls,
725
+ value: IntoExpression,
726
+ mean: IntoExpression = None,
727
+ stdev: IntoExpression = None,
728
+ /,
729
+ ) -> Expression:
730
+ """
731
+ Returns the value of the `probability density function`_ at the given input domain ``value``, for a log-normal distribution with specified log ``mean`` and log standard deviation ``stdev``.
732
+
733
+ If unspecified, the log mean defaults to ``0`` and the log standard deviation defaults to
734
+ ``1``.
735
+
736
+ .. _probability density function:
737
+ https://en.wikipedia.org/wiki/Probability_density_function
738
+ """
739
+ return FunctionExpression("densityLogNormal", (value, mean, stdev))
740
+
741
+ @classmethod
742
+ def quantileLogNormal(
743
+ cls,
744
+ probability: IntoExpression,
745
+ mean: IntoExpression = None,
746
+ stdev: IntoExpression = None,
747
+ /,
748
+ ) -> Expression:
749
+ """
750
+ Returns the quantile value (the inverse of the `cumulative distribution function`_) for the given input ``probability``, for a log-normal distribution with specified log ``mean`` and log standard deviation ``stdev``.
751
+
752
+ If unspecified, the log mean defaults to ``0`` and the log standard deviation defaults to
753
+ ``1``.
754
+
755
+ .. _cumulative distribution function:
756
+ https://en.wikipedia.org/wiki/Cumulative_distribution_function
757
+ """
758
+ return FunctionExpression("quantileLogNormal", (probability, mean, stdev))
759
+
760
+ @classmethod
761
+ def sampleUniform(
762
+ cls, min: IntoExpression = None, max: IntoExpression = None, /
763
+ ) -> Expression:
764
+ """
765
+ Returns a sample from a univariate `continuous uniform probability distribution`_ over the interval [``min``, ``max``).
766
+
767
+ If unspecified, ``min`` defaults to ``0`` and ``max`` defaults to ``1``. If only one
768
+ argument is provided, it is interpreted as the ``max`` value.
769
+
770
+ .. _continuous uniform probability distribution:
771
+ https://en.wikipedia.org/wiki/Continuous_uniform_distribution
772
+ """
773
+ return FunctionExpression("sampleUniform", (min, max))
774
+
775
+ @classmethod
776
+ def cumulativeUniform(
777
+ cls,
778
+ value: IntoExpression,
779
+ min: IntoExpression = None,
780
+ max: IntoExpression = None,
781
+ /,
782
+ ) -> Expression:
783
+ """
784
+ Returns the value of the `cumulative distribution function`_ at the given input domain ``value`` for a uniform distribution over the interval [``min``, ``max``).
785
+
786
+ If unspecified, ``min`` defaults to ``0`` and ``max`` defaults to ``1``. If only one
787
+ argument is provided, it is interpreted as the ``max`` value.
788
+
789
+ .. _cumulative distribution function:
790
+ https://en.wikipedia.org/wiki/Cumulative_distribution_function
791
+ """
792
+ return FunctionExpression("cumulativeUniform", (value, min, max))
793
+
794
+ @classmethod
795
+ def densityUniform(
796
+ cls,
797
+ value: IntoExpression,
798
+ min: IntoExpression = None,
799
+ max: IntoExpression = None,
800
+ /,
801
+ ) -> Expression:
802
+ """
803
+ Returns the value of the `probability density function`_ at the given input domain ``value``, for a uniform distribution over the interval [``min``, ``max``).
804
+
805
+ If unspecified, ``min`` defaults to ``0`` and ``max`` defaults to ``1``. If only one
806
+ argument is provided, it is interpreted as the ``max`` value.
807
+
808
+ .. _probability density function:
809
+ https://en.wikipedia.org/wiki/Probability_density_function
810
+ """
811
+ return FunctionExpression("densityUniform", (value, min, max))
812
+
813
+ @classmethod
814
+ def quantileUniform(
815
+ cls,
816
+ probability: IntoExpression,
817
+ min: IntoExpression = None,
818
+ max: IntoExpression = None,
819
+ /,
820
+ ) -> Expression:
821
+ """
822
+ Returns the quantile value (the inverse of the `cumulative distribution function`_) for the given input ``probability``, for a uniform distribution over the interval [``min``, ``max``).
823
+
824
+ If unspecified, ``min`` defaults to ``0`` and ``max`` defaults to ``1``. If only one
825
+ argument is provided, it is interpreted as the ``max`` value.
826
+
827
+ .. _cumulative distribution function:
828
+ https://en.wikipedia.org/wiki/Cumulative_distribution_function
829
+ """
830
+ return FunctionExpression("quantileUniform", (probability, min, max))
831
+
832
+ @classmethod
833
+ def now(cls) -> Expression:
834
+ """Returns the timestamp for the current time."""
835
+ return FunctionExpression("now", ())
836
+
837
+ @classmethod
838
+ def datetime(
839
+ cls,
840
+ year: IntoExpression,
841
+ month: IntoExpression,
842
+ day: IntoExpression = None,
843
+ hour: IntoExpression = None,
844
+ min: IntoExpression = None,
845
+ sec: IntoExpression = None,
846
+ millisec: IntoExpression = None,
847
+ /,
848
+ ) -> Expression:
849
+ """
850
+ Returns a new ``Date`` instance.
851
+
852
+ The ``month`` is 0-based, such that ``1`` represents February.
853
+ """
854
+ return FunctionExpression(
855
+ "datetime", (year, month, day, hour, min, sec, millisec)
856
+ )
857
+
858
+ @classmethod
859
+ def date(cls, datetime: IntoExpression, /) -> Expression:
860
+ """Returns the day of the month for the given ``datetime`` value, in local time."""
861
+ return FunctionExpression("date", (datetime,))
862
+
863
+ @classmethod
864
+ def day(cls, datetime: IntoExpression, /) -> Expression:
865
+ """Returns the day of the week for the given ``datetime`` value, in local time."""
866
+ return FunctionExpression("day", (datetime,))
867
+
868
+ @classmethod
869
+ def dayofyear(cls, datetime: IntoExpression, /) -> Expression:
870
+ """Returns the one-based day of the year for the given ``datetime`` value, in local time."""
871
+ return FunctionExpression("dayofyear", (datetime,))
872
+
873
+ @classmethod
874
+ def year(cls, datetime: IntoExpression, /) -> Expression:
875
+ """Returns the year for the given ``datetime`` value, in local time."""
876
+ return FunctionExpression("year", (datetime,))
877
+
878
+ @classmethod
879
+ def quarter(cls, datetime: IntoExpression, /) -> Expression:
880
+ """Returns the quarter of the year (0-3) for the given ``datetime`` value, in local time."""
881
+ return FunctionExpression("quarter", (datetime,))
882
+
883
+ @classmethod
884
+ def month(cls, datetime: IntoExpression, /) -> Expression:
885
+ """Returns the (zero-based) month for the given ``datetime`` value, in local time."""
886
+ return FunctionExpression("month", (datetime,))
887
+
888
+ @classmethod
889
+ def week(cls, date: IntoExpression, /) -> Expression:
890
+ """
891
+ Returns the week number of the year for the given *datetime*, in local time.
892
+
893
+ This function assumes Sunday-based weeks. Days before the first Sunday of the year are
894
+ considered to be in week 0, the first Sunday of the year is the start of week 1, the second
895
+ Sunday week 2, *etc.*.
896
+ """
897
+ return FunctionExpression("week", (date,))
898
+
899
+ @classmethod
900
+ def hours(cls, datetime: IntoExpression, /) -> Expression:
901
+ """Returns the hours component for the given ``datetime`` value, in local time."""
902
+ return FunctionExpression("hours", (datetime,))
903
+
904
+ @classmethod
905
+ def minutes(cls, datetime: IntoExpression, /) -> Expression:
906
+ """Returns the minutes component for the given ``datetime`` value, in local time."""
907
+ return FunctionExpression("minutes", (datetime,))
908
+
909
+ @classmethod
910
+ def seconds(cls, datetime: IntoExpression, /) -> Expression:
911
+ """Returns the seconds component for the given ``datetime`` value, in local time."""
912
+ return FunctionExpression("seconds", (datetime,))
913
+
914
+ @classmethod
915
+ def milliseconds(cls, datetime: IntoExpression, /) -> Expression:
916
+ """Returns the milliseconds component for the given ``datetime`` value, in local time."""
917
+ return FunctionExpression("milliseconds", (datetime,))
918
+
919
+ @classmethod
920
+ def time(cls, datetime: IntoExpression, /) -> Expression:
921
+ """Returns the epoch-based timestamp for the given ``datetime`` value."""
922
+ return FunctionExpression("time", (datetime,))
923
+
924
+ @classmethod
925
+ def timezoneoffset(cls, datetime: IntoExpression, /) -> Expression:
926
+ """Returns the timezone offset from the local timezone to UTC for the given ``datetime`` value."""
927
+ return FunctionExpression("timezoneoffset", (datetime,))
928
+
929
+ @classmethod
930
+ def timeOffset(
931
+ cls, unit: IntoExpression, date: IntoExpression, step: IntoExpression = None, /
932
+ ) -> Expression:
933
+ """
934
+ Returns a new ``Date`` instance that offsets the given ``date`` by the specified time `*unit*`_ in the local timezone.
935
+
936
+ The optional ``step`` argument indicates the number of time unit steps to offset by (default
937
+ 1).
938
+
939
+ .. _*unit*:
940
+ https://vega.github.io/vega/docs/api/time/#time-units
941
+ """
942
+ return FunctionExpression("timeOffset", (unit, date, step))
943
+
944
+ @classmethod
945
+ def timeSequence(
946
+ cls,
947
+ unit: IntoExpression,
948
+ start: IntoExpression,
949
+ stop: IntoExpression,
950
+ step: IntoExpression = None,
951
+ /,
952
+ ) -> Expression:
953
+ """
954
+ Returns an array of ``Date`` instances from ``start`` (inclusive) to ``stop`` (exclusive), with each entry separated by the given time `*unit*`_ in the local timezone.
955
+
956
+ The optional ``step`` argument indicates the number of time unit steps to take between each
957
+ sequence entry (default 1).
958
+
959
+ .. _*unit*:
960
+ https://vega.github.io/vega/docs/api/time/#time-units
961
+ """
962
+ return FunctionExpression("timeSequence", (unit, start, stop, step))
963
+
964
+ @classmethod
965
+ def utc(
966
+ cls,
967
+ year: IntoExpression,
968
+ month: IntoExpression,
969
+ day: IntoExpression = None,
970
+ hour: IntoExpression = None,
971
+ min: IntoExpression = None,
972
+ sec: IntoExpression = None,
973
+ millisec: IntoExpression = None,
974
+ /,
975
+ ) -> Expression:
976
+ """
977
+ Returns a timestamp for the given UTC date.
978
+
979
+ The ``month`` is 0-based, such that ``1`` represents February.
980
+ """
981
+ return FunctionExpression("utc", (year, month, day, hour, min, sec, millisec))
982
+
983
+ @classmethod
984
+ def utcdate(cls, datetime: IntoExpression, /) -> Expression:
985
+ """Returns the day of the month for the given ``datetime`` value, in UTC time."""
986
+ return FunctionExpression("utcdate", (datetime,))
987
+
988
+ @classmethod
989
+ def utcday(cls, datetime: IntoExpression, /) -> Expression:
990
+ """Returns the day of the week for the given ``datetime`` value, in UTC time."""
991
+ return FunctionExpression("utcday", (datetime,))
992
+
993
+ @classmethod
994
+ def utcdayofyear(cls, datetime: IntoExpression, /) -> Expression:
995
+ """Returns the one-based day of the year for the given ``datetime`` value, in UTC time."""
996
+ return FunctionExpression("utcdayofyear", (datetime,))
997
+
998
+ @classmethod
999
+ def utcyear(cls, datetime: IntoExpression, /) -> Expression:
1000
+ """Returns the year for the given ``datetime`` value, in UTC time."""
1001
+ return FunctionExpression("utcyear", (datetime,))
1002
+
1003
+ @classmethod
1004
+ def utcquarter(cls, datetime: IntoExpression, /) -> Expression:
1005
+ """Returns the quarter of the year (0-3) for the given ``datetime`` value, in UTC time."""
1006
+ return FunctionExpression("utcquarter", (datetime,))
1007
+
1008
+ @classmethod
1009
+ def utcmonth(cls, datetime: IntoExpression, /) -> Expression:
1010
+ """Returns the (zero-based) month for the given ``datetime`` value, in UTC time."""
1011
+ return FunctionExpression("utcmonth", (datetime,))
1012
+
1013
+ @classmethod
1014
+ def utcweek(cls, date: IntoExpression, /) -> Expression:
1015
+ """
1016
+ Returns the week number of the year for the given *datetime*, in UTC time.
1017
+
1018
+ This function assumes Sunday-based weeks. Days before the first Sunday of the year are
1019
+ considered to be in week 0, the first Sunday of the year is the start of week 1, the second
1020
+ Sunday week 2, *etc.*.
1021
+ """
1022
+ return FunctionExpression("utcweek", (date,))
1023
+
1024
+ @classmethod
1025
+ def utchours(cls, datetime: IntoExpression, /) -> Expression:
1026
+ """Returns the hours component for the given ``datetime`` value, in UTC time."""
1027
+ return FunctionExpression("utchours", (datetime,))
1028
+
1029
+ @classmethod
1030
+ def utcminutes(cls, datetime: IntoExpression, /) -> Expression:
1031
+ """Returns the minutes component for the given ``datetime`` value, in UTC time."""
1032
+ return FunctionExpression("utcminutes", (datetime,))
1033
+
1034
+ @classmethod
1035
+ def utcseconds(cls, datetime: IntoExpression, /) -> Expression:
1036
+ """Returns the seconds component for the given ``datetime`` value, in UTC time."""
1037
+ return FunctionExpression("utcseconds", (datetime,))
1038
+
1039
+ @classmethod
1040
+ def utcmilliseconds(cls, datetime: IntoExpression, /) -> Expression:
1041
+ """Returns the milliseconds component for the given ``datetime`` value, in UTC time."""
1042
+ return FunctionExpression("utcmilliseconds", (datetime,))
1043
+
1044
+ @classmethod
1045
+ def utcOffset(
1046
+ cls, unit: IntoExpression, date: IntoExpression, step: IntoExpression = None, /
1047
+ ) -> Expression:
1048
+ """
1049
+ Returns a new ``Date`` instance that offsets the given ``date`` by the specified time `*unit*`_ in UTC time.
1050
+
1051
+ The optional ``step`` argument indicates the number of time unit steps to offset by (default
1052
+ 1).
1053
+
1054
+ .. _*unit*:
1055
+ https://vega.github.io/vega/docs/api/time/#time-units
1056
+ """
1057
+ return FunctionExpression("utcOffset", (unit, date, step))
1058
+
1059
+ @classmethod
1060
+ def utcSequence(
1061
+ cls,
1062
+ unit: IntoExpression,
1063
+ start: IntoExpression,
1064
+ stop: IntoExpression,
1065
+ step: IntoExpression = None,
1066
+ /,
1067
+ ) -> Expression:
1068
+ """
1069
+ Returns an array of ``Date`` instances from ``start`` (inclusive) to ``stop`` (exclusive), with each entry separated by the given time `*unit*`_ in UTC time.
1070
+
1071
+ The optional ``step`` argument indicates the number of time unit steps to take between each
1072
+ sequence entry (default 1).
1073
+
1074
+ .. _*unit*:
1075
+ https://vega.github.io/vega/docs/api/time/#time-units
1076
+ """
1077
+ return FunctionExpression("utcSequence", (unit, start, stop, step))
1078
+
1079
+ @classmethod
1080
+ def extent(cls, array: IntoExpression, /) -> Expression:
1081
+ """Returns a new *[min, max]* array with the minimum and maximum values of the input array, ignoring ``null``, ``undefined``, and ``NaN`` values."""
1082
+ return FunctionExpression("extent", (array,))
1083
+
1084
+ @classmethod
1085
+ def clampRange(
1086
+ cls, range: IntoExpression, min: IntoExpression, max: IntoExpression, /
1087
+ ) -> Expression:
1088
+ """
1089
+ Clamps a two-element ``range`` array in a span-preserving manner.
1090
+
1091
+ If the span of the input ``range`` is less than *(max - min)* and an endpoint exceeds either
1092
+ the ``min`` or ``max`` value, the range is translated such that the span is preserved and
1093
+ one endpoint touches the boundary of the *[min, max]* range. If the span exceeds *(max -
1094
+ min)*, the range *[min, max]* is returned.
1095
+ """
1096
+ return FunctionExpression("clampRange", (range, min, max))
1097
+
1098
+ @classmethod
1099
+ def indexof(cls, array: IntoExpression, value: IntoExpression, /) -> Expression:
1100
+ """Returns the first index of ``value`` in the input ``array``."""
1101
+ return FunctionExpression("indexof", (array, value))
1102
+
1103
+ @classmethod
1104
+ def inrange(cls, value: IntoExpression, range: IntoExpression, /) -> Expression:
1105
+ """Tests whether ``value`` lies within (or is equal to either) the first and last values of the ``range`` array."""
1106
+ return FunctionExpression("inrange", (value, range))
1107
+
1108
+ @classmethod
1109
+ def join(
1110
+ cls, array: IntoExpression, separator: IntoExpression = None, /
1111
+ ) -> Expression:
1112
+ """Returns a new string by concatenating all of the elements of the input ``array``, separated by commas or a specified ``separator`` string."""
1113
+ return FunctionExpression("join", (array, separator))
1114
+
1115
+ @classmethod
1116
+ def lastindexof(cls, array: IntoExpression, value: IntoExpression, /) -> Expression:
1117
+ """Returns the last index of ``value`` in the input ``array``."""
1118
+ return FunctionExpression("lastindexof", (array, value))
1119
+
1120
+ @classmethod
1121
+ def length(cls, array: IntoExpression, /) -> Expression:
1122
+ """Returns the length of the input ``array``."""
1123
+ return FunctionExpression("length", (array,))
1124
+
1125
+ @classmethod
1126
+ def lerp(cls, array: IntoExpression, fraction: IntoExpression, /) -> Expression:
1127
+ """
1128
+ Returns the linearly interpolated value between the first and last entries in the ``array`` for the provided interpolation ``fraction`` (typically between 0 and 1).
1129
+
1130
+ For example, ``alt.expr.lerp([0, 50], 0.5)`` returns 25.
1131
+ """
1132
+ return FunctionExpression("lerp", (array, fraction))
1133
+
1134
+ @classmethod
1135
+ def peek(cls, array: IntoExpression, /) -> Expression:
1136
+ """
1137
+ Returns the last element in the input ``array``.
1138
+
1139
+ Similar to the built-in ``Array.pop`` method, except that it does not remove the last
1140
+ element. This method is a convenient shorthand for ``array[array.length - 1]``.
1141
+ """
1142
+ return FunctionExpression("peek", (array,))
1143
+
1144
+ @classmethod
1145
+ def pluck(cls, array: IntoExpression, field: IntoExpression, /) -> Expression:
1146
+ """
1147
+ Retrieves the value for the specified ``field`` from a given ``array`` of objects.
1148
+
1149
+ The input ``field`` string may include nested properties (e.g., ``foo.bar.bz``).
1150
+ """
1151
+ return FunctionExpression("pluck", (array, field))
1152
+
1153
+ @classmethod
1154
+ def reverse(cls, array: IntoExpression, /) -> Expression:
1155
+ """
1156
+ Returns a new array with elements in a reverse order of the input ``array``.
1157
+
1158
+ The first array element becomes the last, and the last array element becomes the first.
1159
+ """
1160
+ return FunctionExpression("reverse", (array,))
1161
+
1162
+ @classmethod
1163
+ def sequence(cls, *args: Any) -> Expression:
1164
+ """
1165
+ Returns an array containing an arithmetic sequence of numbers.
1166
+
1167
+ If ``step`` is omitted, it defaults to 1. If ``start`` is omitted, it defaults to 0. The
1168
+ ``stop`` value is exclusive; it is not included in the result. If ``step`` is positive, the
1169
+ last element is the largest *start + i * step* less than ``stop``; if ``step`` is negative,
1170
+ the last element is the smallest *start + i * step* greater than ``stop``. If the returned
1171
+ array would contain an infinite number of values, an empty range is returned. The arguments
1172
+ are not required to be integers.
1173
+ """
1174
+ return FunctionExpression("sequence", args)
1175
+
1176
+ @classmethod
1177
+ def slice(
1178
+ cls, array: IntoExpression, start: IntoExpression, end: IntoExpression = None, /
1179
+ ) -> Expression:
1180
+ """
1181
+ Returns a section of ``array`` between the ``start`` and ``end`` indices.
1182
+
1183
+ If the ``end`` argument is negative, it is treated as an offset from the end of the array
1184
+ (*alt.expr.length(array) + end*).
1185
+ """
1186
+ return FunctionExpression("slice", (array, start, end))
1187
+
1188
+ @classmethod
1189
+ def sort(cls, array: IntoExpression, /) -> Expression:
1190
+ """
1191
+ Sorts the array in natural order using `ascending from Vega Utils`_.
1192
+
1193
+ .. _ascending from Vega Utils:
1194
+ https://vega.github.io/vega/docs/api/util/#ascending
1195
+ """
1196
+ return FunctionExpression("sort", (array,))
1197
+
1198
+ @classmethod
1199
+ def span(cls, array: IntoExpression, /) -> Expression:
1200
+ """Returns the span of ``array``: the difference between the last and first elements, or *array[array.length-1] - array[0]*."""
1201
+ return FunctionExpression("span", (array,))
1202
+
1203
+ @classmethod
1204
+ def lower(cls, string: IntoExpression, /) -> Expression:
1205
+ """Transforms ``string`` to lower-case letters."""
1206
+ return FunctionExpression("lower", (string,))
1207
+
1208
+ @classmethod
1209
+ def pad(
1210
+ cls,
1211
+ string: IntoExpression,
1212
+ length: IntoExpression,
1213
+ character: IntoExpression = None,
1214
+ align: IntoExpression = None,
1215
+ /,
1216
+ ) -> Expression:
1217
+ """
1218
+ Pads a ``string`` value with repeated instances of a ``character`` up to a specified ``length``.
1219
+
1220
+ If ``character`` is not specified, a space (' ') is used. By default, padding is added to
1221
+ the end of a string. An optional ``align`` parameter specifies if padding should be added to
1222
+ the ``'left'`` (beginning), ``'center'``, or ``'right'`` (end) of the input string.
1223
+ """
1224
+ return FunctionExpression("pad", (string, length, character, align))
1225
+
1226
+ @classmethod
1227
+ def parseFloat(cls, string: IntoExpression, /) -> Expression:
1228
+ """
1229
+ Parses the input ``string`` to a floating-point value.
1230
+
1231
+ Same as JavaScript's ``parseFloat``.
1232
+ """
1233
+ return FunctionExpression("parseFloat", (string,))
1234
+
1235
+ @classmethod
1236
+ def parseInt(cls, string: IntoExpression, /) -> Expression:
1237
+ """
1238
+ Parses the input ``string`` to an integer value.
1239
+
1240
+ Same as JavaScript's ``parseInt``.
1241
+ """
1242
+ return FunctionExpression("parseInt", (string,))
1243
+
1244
+ @classmethod
1245
+ def replace(
1246
+ cls,
1247
+ string: IntoExpression,
1248
+ pattern: IntoExpression,
1249
+ replacement: IntoExpression,
1250
+ /,
1251
+ ) -> Expression:
1252
+ """
1253
+ Returns a new string with some or all matches of ``pattern`` replaced by a ``replacement`` string.
1254
+
1255
+ The ``pattern`` can be a string or a regular expression. If ``pattern`` is a string, only
1256
+ the first instance will be replaced. Same as `JavaScript's String.replace`_.
1257
+
1258
+ .. _JavaScript's String.replace:
1259
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
1260
+ """
1261
+ return FunctionExpression("replace", (string, pattern, replacement))
1262
+
1263
+ @classmethod
1264
+ def substring(
1265
+ cls,
1266
+ string: IntoExpression,
1267
+ start: IntoExpression,
1268
+ end: IntoExpression = None,
1269
+ /,
1270
+ ) -> Expression:
1271
+ """Returns a section of ``string`` between the ``start`` and ``end`` indices."""
1272
+ return FunctionExpression("substring", (string, start, end))
1273
+
1274
+ @classmethod
1275
+ def trim(cls, string: IntoExpression, /) -> Expression:
1276
+ """Returns a trimmed string with preceding and trailing whitespace removed."""
1277
+ return FunctionExpression("trim", (string,))
1278
+
1279
+ @classmethod
1280
+ def truncate(
1281
+ cls,
1282
+ string: IntoExpression,
1283
+ length: IntoExpression,
1284
+ align: IntoExpression = None,
1285
+ ellipsis: IntoExpression = None,
1286
+ /,
1287
+ ) -> Expression:
1288
+ """
1289
+ Truncates an input ``string`` to a target ``length``.
1290
+
1291
+ The optional ``align`` argument indicates what part of the string should be truncated:
1292
+ ``'left'`` (the beginning), ``'center'``, or ``'right'`` (the end). By default, the
1293
+ ``'right'`` end of the string is truncated. The optional ``ellipsis`` argument indicates the
1294
+ string to use to indicate truncated content; by default the ellipsis character ``…``
1295
+ (``\u2026``) is used.
1296
+ """
1297
+ return FunctionExpression("truncate", (string, length, align, ellipsis))
1298
+
1299
+ @classmethod
1300
+ def upper(cls, string: IntoExpression, /) -> Expression:
1301
+ """Transforms ``string`` to upper-case letters."""
1302
+ return FunctionExpression("upper", (string,))
1303
+
1304
+ @classmethod
1305
+ def btoa(cls, string: IntoExpression, /) -> Expression:
1306
+ """
1307
+ Creates a `Base64`_-encoded `ASCII`_ string.
1308
+
1309
+ Same as JavaScript's `Window.alt.expr.btoa()`_.
1310
+
1311
+ .. _Base64:
1312
+ https://developer.mozilla.org/en-US/docs/Glossary/Base64
1313
+ .. _ASCII:
1314
+ https://developer.mozilla.org/en-US/docs/Glossary/ASCII
1315
+ .. _Window.alt.expr.btoa():
1316
+ https://developer.mozilla.org/en-US/docs/Web/API/Window/btoa
1317
+ """
1318
+ return FunctionExpression("btoa", (string,))
1319
+
1320
+ @classmethod
1321
+ def atob(cls, string: IntoExpression, /) -> Expression:
1322
+ """
1323
+ Decodes an `ASCII`_ string that was encoded with `Base64`_.
1324
+
1325
+ Same as JavaScript's `Window.alt.expr.atob()`_.
1326
+
1327
+ .. _ASCII:
1328
+ https://developer.mozilla.org/en-US/docs/Glossary/ASCII
1329
+ .. _Base64:
1330
+ https://developer.mozilla.org/en-US/docs/Glossary/Base64
1331
+ .. _Window.alt.expr.atob():
1332
+ https://developer.mozilla.org/en-US/docs/Web/API/Window/atob
1333
+ """
1334
+ return FunctionExpression("atob", (string,))
1335
+
1336
+ @classmethod
1337
+ def merge(
1338
+ cls, object1: IntoExpression, object2: IntoExpression = None, *args: Any
1339
+ ) -> Expression:
1340
+ """
1341
+ Merges the input objects ``object1``, ``object2``, etc into a new output object.
1342
+
1343
+ Inputs are visited in sequential order, such that key values from later arguments can
1344
+ overwrite those from earlier arguments. Example: ``alt.expr.merge({a:1, b:2}, {a:3}) ->
1345
+ {a:3, b:2}``.
1346
+ """
1347
+ return FunctionExpression("merge", (object1, object2, *args))
1348
+
1349
+ @classmethod
1350
+ def dayFormat(cls, day: IntoExpression, /) -> Expression:
1351
+ """
1352
+ Formats a (0-6) *weekday* number as a full week day name, according to the current locale.
1353
+
1354
+ For example: ``alt.expr.dayFormat(0) -> "Sunday"``.
1355
+ """
1356
+ return FunctionExpression("dayFormat", (day,))
1357
+
1358
+ @classmethod
1359
+ def dayAbbrevFormat(cls, day: IntoExpression, /) -> Expression:
1360
+ """
1361
+ Formats a (0-6) *weekday* number as an abbreviated week day name, according to the current locale.
1362
+
1363
+ For example: ``alt.expr.dayAbbrevFormat(0) -> "Sun"``.
1364
+ """
1365
+ return FunctionExpression("dayAbbrevFormat", (day,))
1366
+
1367
+ @classmethod
1368
+ def format(cls, value: IntoExpression, specifier: IntoExpression, /) -> Expression:
1369
+ """
1370
+ Formats a numeric ``value`` as a string.
1371
+
1372
+ The ``specifier`` must be a valid `d3-format specifier`_ (e.g., ``alt.expr.format(value,
1373
+ ',.2f')``. Null values are formatted as ``"null"``.
1374
+
1375
+ .. _d3-format specifier:
1376
+ https://github.com/d3/d3-format/
1377
+ """
1378
+ return FunctionExpression("format", (value, specifier))
1379
+
1380
+ @classmethod
1381
+ def monthFormat(cls, month: IntoExpression, /) -> Expression:
1382
+ """
1383
+ Formats a (zero-based) ``month`` number as a full month name, according to the current locale.
1384
+
1385
+ For example: ``alt.expr.monthFormat(0) -> "January"``.
1386
+ """
1387
+ return FunctionExpression("monthFormat", (month,))
1388
+
1389
+ @classmethod
1390
+ def monthAbbrevFormat(cls, month: IntoExpression, /) -> Expression:
1391
+ """
1392
+ Formats a (zero-based) ``month`` number as an abbreviated month name, according to the current locale.
1393
+
1394
+ For example: ``alt.expr.monthAbbrevFormat(0) -> "Jan"``.
1395
+ """
1396
+ return FunctionExpression("monthAbbrevFormat", (month,))
1397
+
1398
+ @classmethod
1399
+ def timeUnitSpecifier(
1400
+ cls, units: IntoExpression, specifiers: IntoExpression = None, /
1401
+ ) -> Expression:
1402
+ """
1403
+ Returns a time format specifier string for the given time `*units*`_.
1404
+
1405
+ The optional ``specifiers`` object provides a set of specifier sub-strings for customizing
1406
+ the format; for more, see the `timeUnitSpecifier API documentation`_. The resulting
1407
+ specifier string can then be used as input to the `timeFormat`_ or `utcFormat`_ functions,
1408
+ or as the *format* parameter of an axis or legend. For example: ``alt.expr.timeFormat(date,
1409
+ alt.expr.timeUnitSpecifier('year'))`` or ``alt.expr.timeFormat(date,
1410
+ alt.expr.timeUnitSpecifier(['hours', 'minutes']))``.
1411
+
1412
+ .. _*units*:
1413
+ https://vega.github.io/vega/docs/api/time/#time-units
1414
+ .. _timeUnitSpecifier API documentation:
1415
+ https://vega.github.io/vega/docs/api/time/#timeUnitSpecifier
1416
+ .. _timeFormat:
1417
+ https://vega.github.io/vega/docs/expressions/#timeFormat
1418
+ .. _utcFormat:
1419
+ https://vega.github.io/vega/docs/expressions/#utcFormat
1420
+ """
1421
+ return FunctionExpression("timeUnitSpecifier", (units, specifiers))
1422
+
1423
+ @classmethod
1424
+ def timeFormat(
1425
+ cls, value: IntoExpression, specifier: IntoExpression, /
1426
+ ) -> Expression:
1427
+ """
1428
+ Formats a datetime ``value`` (either a ``Date`` object or timestamp) as a string, according to the local time.
1429
+
1430
+ The ``specifier`` must be a valid `d3-time-format specifier`_ or `TimeMultiFormat object`_.
1431
+ For example: ``alt.expr.timeFormat(timestamp, '%A')``. Null values are formatted as
1432
+ ``"null"``.
1433
+
1434
+ .. _d3-time-format specifier:
1435
+ https://github.com/d3/d3-time-format/
1436
+ .. _TimeMultiFormat object:
1437
+ https://vega.github.io/vega/docs/types/#TimeMultiFormat
1438
+ """
1439
+ return FunctionExpression("timeFormat", (value, specifier))
1440
+
1441
+ @classmethod
1442
+ def timeParse(
1443
+ cls, string: IntoExpression, specifier: IntoExpression, /
1444
+ ) -> Expression:
1445
+ """
1446
+ Parses a ``string`` value to a Date object, according to the local time.
1447
+
1448
+ The ``specifier`` must be a valid `d3-time-format specifier`_. For example:
1449
+ ``alt.expr.timeParse('June 30, 2015', '%B %d, %Y')``.
1450
+
1451
+ .. _d3-time-format specifier:
1452
+ https://github.com/d3/d3-time-format/
1453
+ """
1454
+ return FunctionExpression("timeParse", (string, specifier))
1455
+
1456
+ @classmethod
1457
+ def utcFormat(
1458
+ cls, value: IntoExpression, specifier: IntoExpression, /
1459
+ ) -> Expression:
1460
+ """
1461
+ Formats a datetime ``value`` (either a ``Date`` object or timestamp) as a string, according to `UTC`_ time.
1462
+
1463
+ The ``specifier`` must be a valid `d3-time-format specifier`_ or `TimeMultiFormat object`_.
1464
+ For example: ``alt.expr.utcFormat(timestamp, '%A')``. Null values are formatted as
1465
+ ``"null"``.
1466
+
1467
+ .. _UTC:
1468
+ https://en.wikipedia.org/wiki/Coordinated_Universal_Time
1469
+ .. _d3-time-format specifier:
1470
+ https://github.com/d3/d3-time-format/
1471
+ .. _TimeMultiFormat object:
1472
+ https://vega.github.io/vega/docs/types/#TimeMultiFormat
1473
+ """
1474
+ return FunctionExpression("utcFormat", (value, specifier))
1475
+
1476
+ @classmethod
1477
+ def utcParse(
1478
+ cls, value: IntoExpression, specifier: IntoExpression, /
1479
+ ) -> Expression:
1480
+ """
1481
+ Parses a *string* value to a Date object, according to `UTC`_ time.
1482
+
1483
+ The ``specifier`` must be a valid `d3-time-format specifier`_. For example:
1484
+ ``alt.expr.utcParse('June 30, 2015', '%B %d, %Y')``.
1485
+
1486
+ .. _UTC:
1487
+ https://en.wikipedia.org/wiki/Coordinated_Universal_Time
1488
+ .. _d3-time-format specifier:
1489
+ https://github.com/d3/d3-time-format/
1490
+ """
1491
+ return FunctionExpression("utcParse", (value, specifier))
1492
+
1493
+ @classmethod
1494
+ def regexp(
1495
+ cls, pattern: IntoExpression, flags: IntoExpression = None, /
1496
+ ) -> Expression:
1497
+ """
1498
+ Creates a regular expression instance from an input ``pattern`` string and optional ``flags``.
1499
+
1500
+ Same as `JavaScript's RegExp`_.
1501
+
1502
+ .. _JavaScript's RegExp:
1503
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
1504
+ """
1505
+ return FunctionExpression("regexp", (pattern, flags))
1506
+
1507
+ @classmethod
1508
+ def test(
1509
+ cls, regexp: IntoExpression, string: IntoExpression = None, /
1510
+ ) -> Expression:
1511
+ r"""
1512
+ Evaluates a regular expression ``regexp`` against the input ``string``, returning ``true`` if the string matches the pattern, ``false`` otherwise.
1513
+
1514
+ For example: ``alt.expr.test(/\\d{3}/, "32-21-9483") -> true``.
1515
+ """
1516
+ return FunctionExpression("test", (regexp, string))
1517
+
1518
+ @classmethod
1519
+ def rgb(cls, *args: Any) -> Expression:
1520
+ """
1521
+ Constructs a new `RGB`_ color.
1522
+
1523
+ If ``r``, ``g`` and ``b`` are specified, these represent the channel values of the returned
1524
+ color; an ``opacity`` may also be specified. If a CSS Color Module Level 3 *specifier*
1525
+ string is specified, it is parsed and then converted to the RGB color space. Uses
1526
+ `d3-color's rgb function`_.
1527
+
1528
+ .. _RGB:
1529
+ https://en.wikipedia.org/wiki/RGB_color_model
1530
+ .. _d3-color's rgb function:
1531
+ https://github.com/d3/d3-color#rgb
1532
+ """
1533
+ return FunctionExpression("rgb", args)
1534
+
1535
+ @classmethod
1536
+ def hsl(cls, *args: Any) -> Expression:
1537
+ """
1538
+ Constructs a new `HSL`_ color.
1539
+
1540
+ If ``h``, ``s`` and ``l`` are specified, these represent the channel values of the returned
1541
+ color; an ``opacity`` may also be specified. If a CSS Color Module Level 3 *specifier*
1542
+ string is specified, it is parsed and then converted to the HSL color space. Uses
1543
+ `d3-color's hsl function`_.
1544
+
1545
+ .. _HSL:
1546
+ https://en.wikipedia.org/wiki/HSL_and_HSV
1547
+ .. _d3-color's hsl function:
1548
+ https://github.com/d3/d3-color#hsl
1549
+ """
1550
+ return FunctionExpression("hsl", args)
1551
+
1552
+ @classmethod
1553
+ def lab(cls, *args: Any) -> Expression:
1554
+ """
1555
+ Constructs a new `CIE LAB`_ color.
1556
+
1557
+ If ``l``, ``a`` and ``b`` are specified, these represent the channel values of the returned
1558
+ color; an ``opacity`` may also be specified. If a CSS Color Module Level 3 *specifier*
1559
+ string is specified, it is parsed and then converted to the LAB color space. Uses
1560
+ `d3-color's lab function`_.
1561
+
1562
+ .. _CIE LAB:
1563
+ https://en.wikipedia.org/wiki/Lab_color_space#CIELAB
1564
+ .. _d3-color's lab function:
1565
+ https://github.com/d3/d3-color#lab
1566
+ """
1567
+ return FunctionExpression("lab", args)
1568
+
1569
+ @classmethod
1570
+ def hcl(cls, *args: Any) -> Expression:
1571
+ """
1572
+ Constructs a new `HCL`_ (hue, chroma, luminance) color.
1573
+
1574
+ If ``h``, ``c`` and ``l`` are specified, these represent the channel values of the returned
1575
+ color; an ``opacity`` may also be specified. If a CSS Color Module Level 3 *specifier*
1576
+ string is specified, it is parsed and then converted to the HCL color space. Uses
1577
+ `d3-color's hcl function`_.
1578
+
1579
+ .. _HCL:
1580
+ https://en.wikipedia.org/wiki/Lab_color_space#CIELAB
1581
+ .. _d3-color's hcl function:
1582
+ https://github.com/d3/d3-color#hcl
1583
+ """
1584
+ return FunctionExpression("hcl", args)
1585
+
1586
+ @classmethod
1587
+ def luminance(cls, specifier: IntoExpression, /) -> Expression:
1588
+ """
1589
+ Returns the luminance for the given color ``specifier`` (compatible with `d3-color's rgb function`_).
1590
+
1591
+ The luminance is calculated according to the `W3C Web Content Accessibility Guidelines`_.
1592
+
1593
+ .. _d3-color's rgb function:
1594
+ https://github.com/d3/d3-color#rgb
1595
+ .. _W3C Web Content Accessibility Guidelines:
1596
+ https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
1597
+ """
1598
+ return FunctionExpression("luminance", (specifier,))
1599
+
1600
+ @classmethod
1601
+ def contrast(
1602
+ cls, specifier1: IntoExpression, specifier2: IntoExpression, /
1603
+ ) -> Expression:
1604
+ """
1605
+ Returns the contrast ratio between the input color specifiers as a float between 1 and 21.
1606
+
1607
+ The contrast is calculated according to the `W3C Web Content Accessibility Guidelines`_.
1608
+
1609
+ .. _W3C Web Content Accessibility Guidelines:
1610
+ https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
1611
+ """
1612
+ return FunctionExpression("contrast", (specifier1, specifier2))
1613
+
1614
+ @classmethod
1615
+ def item(cls) -> Expression:
1616
+ """Returns the current scenegraph item that is the target of the event."""
1617
+ return FunctionExpression("item", ())
1618
+
1619
+ @classmethod
1620
+ def group(cls, name: IntoExpression = None, /) -> Expression:
1621
+ """
1622
+ Returns the scenegraph group mark item in which the current event has occurred.
1623
+
1624
+ If no arguments are provided, the immediate parent group is returned. If a group name is
1625
+ provided, the matching ancestor group item is returned.
1626
+ """
1627
+ return FunctionExpression("group", (name,))
1628
+
1629
+ @classmethod
1630
+ def xy(cls, item: IntoExpression = None, /) -> Expression:
1631
+ """
1632
+ Returns the x- and y-coordinates for the current event as a two-element array.
1633
+
1634
+ If no arguments are provided, the top-level coordinate space of the view is used. If a
1635
+ scenegraph ``item`` (or string group name) is provided, the coordinate space of the group
1636
+ item is used.
1637
+ """
1638
+ return FunctionExpression("xy", (item,))
1639
+
1640
+ @classmethod
1641
+ def x(cls, item: IntoExpression = None, /) -> Expression:
1642
+ """
1643
+ Returns the x coordinate for the current event.
1644
+
1645
+ If no arguments are provided, the top-level coordinate space of the view is used. If a
1646
+ scenegraph ``item`` (or string group name) is provided, the coordinate space of the group
1647
+ item is used.
1648
+ """
1649
+ return FunctionExpression("x", (item,))
1650
+
1651
+ @classmethod
1652
+ def y(cls, item: IntoExpression = None, /) -> Expression:
1653
+ """
1654
+ Returns the y coordinate for the current event.
1655
+
1656
+ If no arguments are provided, the top-level coordinate space of the view is used. If a
1657
+ scenegraph ``item`` (or string group name) is provided, the coordinate space of the group
1658
+ item is used.
1659
+ """
1660
+ return FunctionExpression("y", (item,))
1661
+
1662
+ @classmethod
1663
+ def pinchDistance(cls, event: IntoExpression, /) -> Expression:
1664
+ """Returns the pixel distance between the first two touch points of a multi-touch event."""
1665
+ return FunctionExpression("pinchDistance", (event,))
1666
+
1667
+ @classmethod
1668
+ def pinchAngle(cls, event: IntoExpression, /) -> Expression:
1669
+ """Returns the angle of the line connecting the first two touch points of a multi-touch event."""
1670
+ return FunctionExpression("pinchAngle", (event,))
1671
+
1672
+ @classmethod
1673
+ def inScope(cls, item: IntoExpression, /) -> Expression:
1674
+ """Returns true if the given scenegraph ``item`` is a descendant of the group mark in which the event handler was defined, false otherwise."""
1675
+ return FunctionExpression("inScope", (item,))
1676
+
1677
+ @classmethod
1678
+ def data(cls, name: IntoExpression, /) -> Expression:
1679
+ """
1680
+ Returns the array of data objects for the Vega data set with the given ``name``.
1681
+
1682
+ If the data set is not found, returns an empty array.
1683
+ """
1684
+ return FunctionExpression("data", (name,))
1685
+
1686
+ @classmethod
1687
+ def indata(
1688
+ cls, name: IntoExpression, field: IntoExpression, value: IntoExpression, /
1689
+ ) -> Expression:
1690
+ """
1691
+ Tests if the data set with a given ``name`` contains a datum with a ``field`` value that matches the input ``value``.
1692
+
1693
+ For example: ``alt.expr.indata('table', 'category', value)``.
1694
+ """
1695
+ return FunctionExpression("indata", (name, field, value))
1696
+
1697
+ @classmethod
1698
+ def scale(
1699
+ cls,
1700
+ name: IntoExpression,
1701
+ value: IntoExpression,
1702
+ group: IntoExpression = None,
1703
+ /,
1704
+ ) -> Expression:
1705
+ """
1706
+ Applies the named scale transform (or projection) to the specified ``value``.
1707
+
1708
+ The optional ``group`` argument takes a scenegraph group mark item to indicate the specific
1709
+ scope in which to look up the scale or projection.
1710
+ """
1711
+ return FunctionExpression("scale", (name, value, group))
1712
+
1713
+ @classmethod
1714
+ def invert(
1715
+ cls,
1716
+ name: IntoExpression,
1717
+ value: IntoExpression,
1718
+ group: IntoExpression = None,
1719
+ /,
1720
+ ) -> Expression:
1721
+ """
1722
+ Inverts the named scale transform (or projection) for the specified ``value``.
1723
+
1724
+ The optional ``group`` argument takes a scenegraph group mark item to indicate the specific
1725
+ scope in which to look up the scale or projection.
1726
+ """
1727
+ return FunctionExpression("invert", (name, value, group))
1728
+
1729
+ @classmethod
1730
+ def copy(cls, name: IntoExpression, group: IntoExpression = None, /) -> Expression: # type: ignore[override]
1731
+ """
1732
+ Returns a copy (a new cloned instance) of the named scale transform of projection, or ``undefined`` if no scale or projection is found.
1733
+
1734
+ The optional ``group`` argument takes a scenegraph group mark item to indicate the specific
1735
+ scope in which to look up the scale or projection.
1736
+ """
1737
+ return FunctionExpression("copy", (name, group))
1738
+
1739
+ @classmethod
1740
+ def domain(
1741
+ cls, name: IntoExpression, group: IntoExpression = None, /
1742
+ ) -> Expression:
1743
+ """
1744
+ Returns the scale domain array for the named scale transform, or an empty array if the scale is not found.
1745
+
1746
+ The optional ``group`` argument takes a scenegraph group mark item to indicate the specific
1747
+ scope in which to look up the scale.
1748
+ """
1749
+ return FunctionExpression("domain", (name, group))
1750
+
1751
+ @classmethod
1752
+ def range(cls, name: IntoExpression, group: IntoExpression = None, /) -> Expression:
1753
+ """
1754
+ Returns the scale range array for the named scale transform, or an empty array if the scale is not found.
1755
+
1756
+ The optional ``group`` argument takes a scenegraph group mark item to indicate the specific
1757
+ scope in which to look up the scale.
1758
+ """
1759
+ return FunctionExpression("range", (name, group))
1760
+
1761
+ @classmethod
1762
+ def bandwidth(
1763
+ cls, name: IntoExpression, group: IntoExpression = None, /
1764
+ ) -> Expression:
1765
+ """
1766
+ Returns the current band width for the named band scale transform, or zero if the scale is not found or is not a band scale.
1767
+
1768
+ The optional ``group`` argument takes a scenegraph group mark item to indicate the specific
1769
+ scope in which to look up the scale.
1770
+ """
1771
+ return FunctionExpression("bandwidth", (name, group))
1772
+
1773
+ @classmethod
1774
+ def bandspace(
1775
+ cls,
1776
+ count: IntoExpression,
1777
+ paddingInner: IntoExpression = None,
1778
+ paddingOuter: IntoExpression = None,
1779
+ /,
1780
+ ) -> Expression:
1781
+ """
1782
+ Returns the number of steps needed within a band scale, based on the ``count`` of domain elements and the inner and outer padding values.
1783
+
1784
+ While normally calculated within the scale itself, this function can be helpful for
1785
+ determining the size of a chart's layout.
1786
+ """
1787
+ return FunctionExpression("bandspace", (count, paddingInner, paddingOuter))
1788
+
1789
+ @classmethod
1790
+ def gradient(
1791
+ cls,
1792
+ scale: IntoExpression,
1793
+ p0: IntoExpression,
1794
+ p1: IntoExpression,
1795
+ count: IntoExpression = None,
1796
+ /,
1797
+ ) -> Expression:
1798
+ """
1799
+ Returns a linear color gradient for the ``scale`` (whose range must be a `continuous color scheme`_) and starting and ending points ``p0`` and ``p1``, each an *[x, y]* array.
1800
+
1801
+ The points ``p0`` and ``p1`` should be expressed in normalized coordinates in the domain [0,
1802
+ 1], relative to the bounds of the item being colored. If unspecified, ``p0`` defaults to
1803
+ ``[0, 0]`` and ``p1`` defaults to ``[1, 0]``, for a horizontal gradient that spans the full
1804
+ bounds of an item. The optional ``count`` argument indicates a desired target number of
1805
+ sample points to take from the color scale.
1806
+
1807
+ .. _continuous color scheme:
1808
+ https://vega.github.io/vega/docs/schemes
1809
+ """
1810
+ return FunctionExpression("gradient", (scale, p0, p1, count))
1811
+
1812
+ @classmethod
1813
+ def panLinear(cls, domain: IntoExpression, delta: IntoExpression, /) -> Expression:
1814
+ """
1815
+ Given a linear scale ``domain`` array with numeric or datetime values, returns a new two-element domain array that is the result of panning the domain by a fractional ``delta``.
1816
+
1817
+ The ``delta`` value represents fractional units of the scale range; for example, ``0.5``
1818
+ indicates panning the scale domain to the right by half the scale range.
1819
+ """
1820
+ return FunctionExpression("panLinear", (domain, delta))
1821
+
1822
+ @classmethod
1823
+ def panLog(cls, domain: IntoExpression, delta: IntoExpression, /) -> Expression:
1824
+ """
1825
+ Given a log scale ``domain`` array with numeric or datetime values, returns a new two-element domain array that is the result of panning the domain by a fractional ``delta``.
1826
+
1827
+ The ``delta`` value represents fractional units of the scale range; for example, ``0.5``
1828
+ indicates panning the scale domain to the right by half the scale range.
1829
+ """
1830
+ return FunctionExpression("panLog", (domain, delta))
1831
+
1832
+ @classmethod
1833
+ def panPow(
1834
+ cls, domain: IntoExpression, delta: IntoExpression, exponent: IntoExpression, /
1835
+ ) -> Expression:
1836
+ """
1837
+ Given a power scale ``domain`` array with numeric or datetime values and the given ``exponent``, returns a new two-element domain array that is the result of panning the domain by a fractional ``delta``.
1838
+
1839
+ The ``delta`` value represents fractional units of the scale range; for example, ``0.5``
1840
+ indicates panning the scale domain to the right by half the scale range.
1841
+ """
1842
+ return FunctionExpression("panPow", (domain, delta, exponent))
1843
+
1844
+ @classmethod
1845
+ def panSymlog(
1846
+ cls, domain: IntoExpression, delta: IntoExpression, constant: IntoExpression, /
1847
+ ) -> Expression:
1848
+ """
1849
+ Given a symmetric log scale ``domain`` array with numeric or datetime values parameterized by the given ``constant``, returns a new two-element domain array that is the result of panning the domain by a fractional ``delta``.
1850
+
1851
+ The ``delta`` value represents fractional units of the scale range; for example, ``0.5``
1852
+ indicates panning the scale domain to the right by half the scale range.
1853
+ """
1854
+ return FunctionExpression("panSymlog", (domain, delta, constant))
1855
+
1856
+ @classmethod
1857
+ def zoomLinear(
1858
+ cls,
1859
+ domain: IntoExpression,
1860
+ anchor: IntoExpression,
1861
+ scaleFactor: IntoExpression,
1862
+ /,
1863
+ ) -> Expression:
1864
+ """
1865
+ Given a linear scale ``domain`` array with numeric or datetime values, returns a new two-element domain array that is the result of zooming the domain by a ``scaleFactor``, centered at the provided fractional ``anchor``.
1866
+
1867
+ The ``anchor`` value represents the zoom position in terms of fractional units of the scale
1868
+ range; for example, ``0.5`` indicates a zoom centered on the mid-point of the scale range.
1869
+ """
1870
+ return FunctionExpression("zoomLinear", (domain, anchor, scaleFactor))
1871
+
1872
+ @classmethod
1873
+ def zoomLog(
1874
+ cls,
1875
+ domain: IntoExpression,
1876
+ anchor: IntoExpression,
1877
+ scaleFactor: IntoExpression,
1878
+ /,
1879
+ ) -> Expression:
1880
+ """
1881
+ Given a log scale ``domain`` array with numeric or datetime values, returns a new two-element domain array that is the result of zooming the domain by a ``scaleFactor``, centered at the provided fractional ``anchor``.
1882
+
1883
+ The ``anchor`` value represents the zoom position in terms of fractional units of the scale
1884
+ range; for example, ``0.5`` indicates a zoom centered on the mid-point of the scale range.
1885
+ """
1886
+ return FunctionExpression("zoomLog", (domain, anchor, scaleFactor))
1887
+
1888
+ @classmethod
1889
+ def zoomPow(
1890
+ cls,
1891
+ domain: IntoExpression,
1892
+ anchor: IntoExpression,
1893
+ scaleFactor: IntoExpression,
1894
+ exponent: IntoExpression,
1895
+ /,
1896
+ ) -> Expression:
1897
+ """
1898
+ Given a power scale ``domain`` array with numeric or datetime values and the given ``exponent``, returns a new two-element domain array that is the result of zooming the domain by a ``scaleFactor``, centered at the provided fractional ``anchor``.
1899
+
1900
+ The ``anchor`` value represents the zoom position in terms of fractional units of the scale
1901
+ range; for example, ``0.5`` indicates a zoom centered on the mid-point of the scale range.
1902
+ """
1903
+ return FunctionExpression("zoomPow", (domain, anchor, scaleFactor, exponent))
1904
+
1905
+ @classmethod
1906
+ def zoomSymlog(
1907
+ cls,
1908
+ domain: IntoExpression,
1909
+ anchor: IntoExpression,
1910
+ scaleFactor: IntoExpression,
1911
+ constant: IntoExpression,
1912
+ /,
1913
+ ) -> Expression:
1914
+ """
1915
+ Given a symmetric log scale ``domain`` array with numeric or datetime values parameterized by the given ``constant``, returns a new two-element domain array that is the result of zooming the domain by a ``scaleFactor``, centered at the provided fractional ``anchor``.
1916
+
1917
+ The ``anchor`` value represents the zoom position in terms of fractional units of the scale
1918
+ range; for example, ``0.5`` indicates a zoom centered on the mid-point of the scale range.
1919
+ """
1920
+ return FunctionExpression("zoomSymlog", (domain, anchor, scaleFactor, constant))
1921
+
1922
+ @classmethod
1923
+ def geoArea(
1924
+ cls,
1925
+ projection: IntoExpression,
1926
+ feature: IntoExpression,
1927
+ group: IntoExpression = None,
1928
+ /,
1929
+ ) -> Expression:
1930
+ """
1931
+ Returns the projected planar area (typically in square pixels) of a GeoJSON ``feature`` according to the named ``projection``.
1932
+
1933
+ If the ``projection`` argument is ``null``, computes the spherical area in steradians using
1934
+ unprojected longitude, latitude coordinates. The optional ``group`` argument takes a
1935
+ scenegraph group mark item to indicate the specific scope in which to look up the
1936
+ projection. Uses d3-geo's `geoArea`_ and `path.area`_ methods.
1937
+
1938
+ .. _geoArea:
1939
+ https://github.com/d3/d3-geo#geoArea
1940
+ .. _path.area:
1941
+ https://github.com/d3/d3-geo#path_area
1942
+ """
1943
+ return FunctionExpression("geoArea", (projection, feature, group))
1944
+
1945
+ @classmethod
1946
+ def geoBounds(
1947
+ cls,
1948
+ projection: IntoExpression,
1949
+ feature: IntoExpression,
1950
+ group: IntoExpression = None,
1951
+ /,
1952
+ ) -> Expression:
1953
+ """
1954
+ Returns the projected planar bounding box (typically in pixels) for the specified GeoJSON ``feature``, according to the named ``projection``.
1955
+
1956
+ The bounding box is represented by a two-dimensional array: [[*x₀*, *y₀*], [*x₁*, *y₁*]],
1957
+ where *x₀* is the minimum x-coordinate, *y₀* is the minimum y-coordinate, *x₁* is the
1958
+ maximum x-coordinate, and *y₁* is the maximum y-coordinate. If the ``projection`` argument
1959
+ is ``null``, computes the spherical bounding box using unprojected longitude, latitude
1960
+ coordinates. The optional ``group`` argument takes a scenegraph group mark item to indicate
1961
+ the specific scope in which to look up the projection. Uses d3-geo's `geoBounds`_ and
1962
+ `path.bounds`_ methods.
1963
+
1964
+ .. _geoBounds:
1965
+ https://github.com/d3/d3-geo#geoBounds
1966
+ .. _path.bounds:
1967
+ https://github.com/d3/d3-geo#path_bounds
1968
+ """
1969
+ return FunctionExpression("geoBounds", (projection, feature, group))
1970
+
1971
+ @classmethod
1972
+ def geoCentroid(
1973
+ cls,
1974
+ projection: IntoExpression,
1975
+ feature: IntoExpression,
1976
+ group: IntoExpression = None,
1977
+ /,
1978
+ ) -> Expression:
1979
+ """
1980
+ Returns the projected planar centroid (typically in pixels) for the specified GeoJSON ``feature``, according to the named ``projection``.
1981
+
1982
+ If the ``projection`` argument is ``null``, computes the spherical centroid using
1983
+ unprojected longitude, latitude coordinates. The optional ``group`` argument takes a
1984
+ scenegraph group mark item to indicate the specific scope in which to look up the
1985
+ projection. Uses d3-geo's `geoCentroid`_ and `path.centroid`_ methods.
1986
+
1987
+ .. _geoCentroid:
1988
+ https://github.com/d3/d3-geo#geoCentroid
1989
+ .. _path.centroid:
1990
+ https://github.com/d3/d3-geo#path_centroid
1991
+ """
1992
+ return FunctionExpression("geoCentroid", (projection, feature, group))
1993
+
1994
+ @classmethod
1995
+ def geoScale(
1996
+ cls, projection: IntoExpression, group: IntoExpression = None, /
1997
+ ) -> Expression:
1998
+ """
1999
+ Returns the scale value for the named ``projection``.
2000
+
2001
+ The optional ``group`` argument takes a scenegraph group mark item to indicate the specific
2002
+ scope in which to look up the projection.
2003
+ """
2004
+ return FunctionExpression("geoScale", (projection, group))
2005
+
2006
+ @classmethod
2007
+ def treePath(
2008
+ cls, name: IntoExpression, source: IntoExpression, target: IntoExpression, /
2009
+ ) -> Expression:
2010
+ """
2011
+ For the hierarchy data set with the given ``name``, returns the shortest path through from the ``source`` node id to the ``target`` node id.
2012
+
2013
+ The path starts at the ``source`` node, ascends to the least common ancestor of the
2014
+ ``source`` node and the ``target`` node, and then descends to the ``target`` node.
2015
+ """
2016
+ return FunctionExpression("treePath", (name, source, target))
2017
+
2018
+ @classmethod
2019
+ def treeAncestors(cls, name: IntoExpression, node: IntoExpression, /) -> Expression:
2020
+ """For the hierarchy data set with the given ``name``, returns the array of ancestors nodes, starting with the input ``node``, then followed by each parent up to the root."""
2021
+ return FunctionExpression("treeAncestors", (name, node))
2022
+
2023
+ @classmethod
2024
+ def containerSize(cls) -> Expression:
2025
+ """
2026
+ Returns the current CSS box size (``[el.clientWidth, el.clientHeight]``) of the parent DOM element that contains the Vega view.
2027
+
2028
+ If there is no container element, returns ``[undefined, undefined]``.
2029
+ """
2030
+ return FunctionExpression("containerSize", ())
2031
+
2032
+ @classmethod
2033
+ def screen(cls) -> Expression:
2034
+ """
2035
+ Returns the `window.screen`_ object, or ``{}`` if Vega is not running in a browser environment.
2036
+
2037
+ .. _window.screen:
2038
+ https://developer.mozilla.org/en-US/docs/Web/API/Window/screen
2039
+ """
2040
+ return FunctionExpression("screen", ())
2041
+
2042
+ @classmethod
2043
+ def windowSize(cls) -> Expression:
2044
+ """Returns the current window size (``[window.innerWidth, window.innerHeight]``) or ``[undefined, undefined]`` if Vega is not running in a browser environment."""
2045
+ return FunctionExpression("windowSize", ())
2046
+
2047
+ @classmethod
2048
+ def warn(
2049
+ cls, value1: IntoExpression, value2: IntoExpression = None, *args: Any
2050
+ ) -> Expression:
2051
+ """
2052
+ Logs a warning message and returns the last argument.
2053
+
2054
+ For the message to appear in the console, the visualization view must have the appropriate
2055
+ logging level set.
2056
+ """
2057
+ return FunctionExpression("warn", (value1, value2, *args))
2058
+
2059
+ @classmethod
2060
+ def info(
2061
+ cls, value1: IntoExpression, value2: IntoExpression = None, *args: Any
2062
+ ) -> Expression:
2063
+ """
2064
+ Logs an informative message and returns the last argument.
2065
+
2066
+ For the message to appear in the console, the visualization view must have the appropriate
2067
+ logging level set.
2068
+ """
2069
+ return FunctionExpression("info", (value1, value2, *args))
2070
+
2071
+ @classmethod
2072
+ def debug(
2073
+ cls, value1: IntoExpression, value2: IntoExpression = None, *args: Any
2074
+ ) -> Expression:
2075
+ """
2076
+ Logs a debugging message and returns the last argument.
2077
+
2078
+ For the message to appear in the console, the visualization view must have the appropriate
2079
+ logging level set.
2080
+ """
2081
+ return FunctionExpression("debug", (value1, value2, *args))
2082
+
2083
+
2084
+ _ExprType = expr
2085
+ # NOTE: Compatibility alias for previous type of `alt.expr`.
2086
+ # `_ExprType` was not referenced in any internal imports/tests.
.venv/lib/python3.13/site-packages/altair/expr/consts.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ CONST_LISTING = {
4
+ "NaN": "not a number (same as JavaScript literal NaN)",
5
+ "LN10": "the natural log of 10 (alias to Math.LN10)",
6
+ "E": "the transcendental number e (alias to Math.E)",
7
+ "LOG10E": "the base 10 logarithm e (alias to Math.LOG10E)",
8
+ "LOG2E": "the base 2 logarithm of e (alias to Math.LOG2E)",
9
+ "SQRT1_2": "the square root of 0.5 (alias to Math.SQRT1_2)",
10
+ "LN2": "the natural log of 2 (alias to Math.LN2)",
11
+ "SQRT2": "the square root of 2 (alias to Math.SQRT1_2)",
12
+ "PI": "the transcendental number pi (alias to Math.PI)",
13
+ }
.venv/lib/python3.13/site-packages/altair/expr/core.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import datetime as dt
4
+ import sys
5
+ from typing import TYPE_CHECKING, Any, Literal, Union
6
+
7
+ from altair.utils import SchemaBase
8
+
9
+ if TYPE_CHECKING:
10
+ from altair.vegalite.v6.schema._typing import Map, PrimitiveValue_T
11
+
12
+ if sys.version_info >= (3, 10):
13
+ from typing import TypeAlias
14
+ else:
15
+ from typing_extensions import TypeAlias
16
+
17
+
18
+ class DatumType:
19
+ """An object to assist in building Vega-Lite Expressions."""
20
+
21
+ def __repr__(self) -> str:
22
+ return "datum"
23
+
24
+ def __getattr__(self, attr) -> GetAttrExpression:
25
+ if attr.startswith("__") and attr.endswith("__"):
26
+ raise AttributeError(attr)
27
+ return GetAttrExpression("datum", attr)
28
+
29
+ def __getitem__(self, attr) -> GetItemExpression:
30
+ return GetItemExpression("datum", attr)
31
+
32
+ def __call__(self, datum, **kwargs) -> dict[str, Any]:
33
+ """Specify a datum for use in an encoding."""
34
+ return dict(datum=datum, **kwargs)
35
+
36
+
37
+ datum = DatumType()
38
+
39
+
40
+ def _js_repr(val) -> str:
41
+ """Return a javascript-safe string representation of val."""
42
+ if val is True:
43
+ return "true"
44
+ elif val is False:
45
+ return "false"
46
+ elif val is None:
47
+ return "null"
48
+ elif isinstance(val, OperatorMixin):
49
+ return val._to_expr()
50
+ elif isinstance(val, dt.date):
51
+ return _from_date_datetime(val)
52
+ elif _is_numpy_generic(val):
53
+ return repr(val.item())
54
+ else:
55
+ return repr(val)
56
+
57
+
58
+ def _from_date_datetime(obj: dt.date | dt.datetime, /) -> str:
59
+ """
60
+ Parse native `datetime.(date|datetime)` into a `datetime expression`_ string.
61
+
62
+ **Month is 0-based**
63
+
64
+ .. _datetime expression:
65
+ https://vega.github.io/vega/docs/expressions/#datetime
66
+ """
67
+ fn_name: Literal["datetime", "utc"] = "datetime"
68
+ args: tuple[int, ...] = obj.year, obj.month - 1, obj.day
69
+ if isinstance(obj, dt.datetime):
70
+ if tzinfo := obj.tzinfo:
71
+ if tzinfo is dt.timezone.utc:
72
+ fn_name = "utc"
73
+ else:
74
+ msg = (
75
+ f"Unsupported timezone {tzinfo!r}.\n"
76
+ "Only `'UTC'` or naive (local) datetimes are permitted.\n"
77
+ "See https://altair-viz.github.io/user_guide/generated/core/altair.DateTime.html"
78
+ )
79
+ raise TypeError(msg)
80
+ us = obj.microsecond
81
+ ms = us if us == 0 else us // 1_000
82
+ args = *args, obj.hour, obj.minute, obj.second, ms
83
+ return FunctionExpression(fn_name, args)._to_expr()
84
+
85
+
86
+ def _is_numpy_generic(obj: Any) -> bool:
87
+ """
88
+ Check if an object is a numpy generic (scalar) type.
89
+
90
+ This function can be used without importing numpy when it is not available.
91
+ """
92
+ return (np := sys.modules.get("numpy")) is not None and isinstance(obj, np.generic)
93
+
94
+
95
+ # Designed to work with Expression and VariableParameter
96
+ class OperatorMixin:
97
+ def _to_expr(self) -> str:
98
+ return repr(self)
99
+
100
+ def _from_expr(self, expr) -> Any:
101
+ return expr
102
+
103
+ def __add__(self, other):
104
+ comp_value = BinaryExpression("+", self, other)
105
+ return self._from_expr(comp_value)
106
+
107
+ def __radd__(self, other):
108
+ comp_value = BinaryExpression("+", other, self)
109
+ return self._from_expr(comp_value)
110
+
111
+ def __sub__(self, other):
112
+ comp_value = BinaryExpression("-", self, other)
113
+ return self._from_expr(comp_value)
114
+
115
+ def __rsub__(self, other):
116
+ comp_value = BinaryExpression("-", other, self)
117
+ return self._from_expr(comp_value)
118
+
119
+ def __mul__(self, other):
120
+ comp_value = BinaryExpression("*", self, other)
121
+ return self._from_expr(comp_value)
122
+
123
+ def __rmul__(self, other):
124
+ comp_value = BinaryExpression("*", other, self)
125
+ return self._from_expr(comp_value)
126
+
127
+ def __truediv__(self, other):
128
+ comp_value = BinaryExpression("/", self, other)
129
+ return self._from_expr(comp_value)
130
+
131
+ def __rtruediv__(self, other):
132
+ comp_value = BinaryExpression("/", other, self)
133
+ return self._from_expr(comp_value)
134
+
135
+ __div__ = __truediv__
136
+
137
+ __rdiv__ = __rtruediv__
138
+
139
+ def __mod__(self, other):
140
+ comp_value = BinaryExpression("%", self, other)
141
+ return self._from_expr(comp_value)
142
+
143
+ def __rmod__(self, other):
144
+ comp_value = BinaryExpression("%", other, self)
145
+ return self._from_expr(comp_value)
146
+
147
+ def __pow__(self, other):
148
+ # "**" Javascript operator is not supported in all browsers
149
+ comp_value = FunctionExpression("pow", (self, other))
150
+ return self._from_expr(comp_value)
151
+
152
+ def __rpow__(self, other):
153
+ # "**" Javascript operator is not supported in all browsers
154
+ comp_value = FunctionExpression("pow", (other, self))
155
+ return self._from_expr(comp_value)
156
+
157
+ def __neg__(self):
158
+ comp_value = UnaryExpression("-", self)
159
+ return self._from_expr(comp_value)
160
+
161
+ def __pos__(self):
162
+ comp_value = UnaryExpression("+", self)
163
+ return self._from_expr(comp_value)
164
+
165
+ # comparison operators
166
+
167
+ def __eq__(self, other):
168
+ comp_value = BinaryExpression("===", self, other)
169
+ return self._from_expr(comp_value)
170
+
171
+ def __ne__(self, other):
172
+ comp_value = BinaryExpression("!==", self, other)
173
+ return self._from_expr(comp_value)
174
+
175
+ def __gt__(self, other):
176
+ comp_value = BinaryExpression(">", self, other)
177
+ return self._from_expr(comp_value)
178
+
179
+ def __lt__(self, other):
180
+ comp_value = BinaryExpression("<", self, other)
181
+ return self._from_expr(comp_value)
182
+
183
+ def __ge__(self, other):
184
+ comp_value = BinaryExpression(">=", self, other)
185
+ return self._from_expr(comp_value)
186
+
187
+ def __le__(self, other):
188
+ comp_value = BinaryExpression("<=", self, other)
189
+ return self._from_expr(comp_value)
190
+
191
+ def __abs__(self):
192
+ comp_value = FunctionExpression("abs", (self,))
193
+ return self._from_expr(comp_value)
194
+
195
+ # logical operators
196
+
197
+ def __and__(self, other):
198
+ comp_value = BinaryExpression("&&", self, other)
199
+ return self._from_expr(comp_value)
200
+
201
+ def __rand__(self, other):
202
+ comp_value = BinaryExpression("&&", other, self)
203
+ return self._from_expr(comp_value)
204
+
205
+ def __or__(self, other):
206
+ comp_value = BinaryExpression("||", self, other)
207
+ return self._from_expr(comp_value)
208
+
209
+ def __ror__(self, other):
210
+ comp_value = BinaryExpression("||", other, self)
211
+ return self._from_expr(comp_value)
212
+
213
+ def __invert__(self):
214
+ comp_value = UnaryExpression("!", self)
215
+ return self._from_expr(comp_value)
216
+
217
+
218
+ class Expression(OperatorMixin, SchemaBase):
219
+ """
220
+ Expression.
221
+
222
+ Base object for enabling build-up of Javascript expressions using
223
+ a Python syntax. Calling ``repr(obj)`` will return a Javascript
224
+ representation of the object and the operations it encodes.
225
+ """
226
+
227
+ _schema = {"type": "string"}
228
+
229
+ def to_dict(self, *args, **kwargs):
230
+ return repr(self)
231
+
232
+ def __setattr__(self, attr, val) -> None:
233
+ # We don't need the setattr magic defined in SchemaBase
234
+ return object.__setattr__(self, attr, val)
235
+
236
+ # item access
237
+ def __getitem__(self, val):
238
+ return GetItemExpression(self, val)
239
+
240
+
241
+ class UnaryExpression(Expression):
242
+ def __init__(self, op, val) -> None:
243
+ super().__init__(op=op, val=val)
244
+
245
+ def __repr__(self):
246
+ return f"({self.op}{_js_repr(self.val)})"
247
+
248
+
249
+ class BinaryExpression(Expression):
250
+ def __init__(self, op, lhs, rhs) -> None:
251
+ super().__init__(op=op, lhs=lhs, rhs=rhs)
252
+
253
+ def __repr__(self):
254
+ return f"({_js_repr(self.lhs)} {self.op} {_js_repr(self.rhs)})"
255
+
256
+
257
+ class FunctionExpression(Expression):
258
+ def __init__(self, name, args) -> None:
259
+ super().__init__(name=name, args=args)
260
+
261
+ def __repr__(self):
262
+ args = ",".join(_js_repr(arg) for arg in self.args)
263
+ return f"{self.name}({args})"
264
+
265
+
266
+ class ConstExpression(Expression):
267
+ def __init__(self, name) -> None:
268
+ super().__init__(name=name)
269
+
270
+ def __repr__(self) -> str:
271
+ return str(self.name)
272
+
273
+
274
+ class GetAttrExpression(Expression):
275
+ def __init__(self, group, name) -> None:
276
+ super().__init__(group=group, name=name)
277
+
278
+ def __repr__(self):
279
+ return f"{self.group}.{self.name}"
280
+
281
+
282
+ class GetItemExpression(Expression):
283
+ def __init__(self, group, name) -> None:
284
+ super().__init__(group=group, name=name)
285
+
286
+ def __repr__(self) -> str:
287
+ return f"{self.group}[{self.name!r}]"
288
+
289
+
290
+ IntoExpression: TypeAlias = Union[
291
+ "PrimitiveValue_T", dt.date, dt.datetime, OperatorMixin, "Map"
292
+ ]
.venv/lib/python3.13/site-packages/altair/expr/funcs.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ FUNCTION_LISTING = {
4
+ "isArray": r"Returns true if _value_ is an array, false otherwise.",
5
+ "isBoolean": r"Returns true if _value_ is a boolean (`true` or `false`), false otherwise.",
6
+ "isDate": r"Returns true if _value_ is a Date object, false otherwise. This method will return false for timestamp numbers or date-formatted strings; it recognizes Date objects only.",
7
+ "isDefined": r"Returns true if _value_ is a defined value, false if _value_ equals `undefined`. This method will return true for `null` and `NaN` values.",
8
+ "isNumber": r"Returns true if _value_ is a number, false otherwise. `NaN` and `Infinity` are considered numbers.",
9
+ "isObject": r"Returns true if _value_ is an object (including arrays and Dates), false otherwise.",
10
+ "isRegExp": r"Returns true if _value_ is a RegExp (regular expression) object, false otherwise.",
11
+ "isString": r"Returns true if _value_ is a string, false otherwise.",
12
+ "isValid": r"Returns true if _value_ is not `null`, `undefined`, or `NaN`, false otherwise.",
13
+ "toBoolean": r"Coerces the input _value_ to a string. Null values and empty strings are mapped to `null`.",
14
+ "toDate": r"Coerces the input _value_ to a Date instance. Null values and empty strings are mapped to `null`. If an optional _parser_ function is provided, it is used to perform date parsing, otherwise `Date.parse` is used. Be aware that `Date.parse` has different implementations across browsers!",
15
+ "toNumber": r"Coerces the input _value_ to a number. Null values and empty strings are mapped to `null`.",
16
+ "toString": r"Coerces the input _value_ to a string. Null values and empty strings are mapped to `null`.",
17
+ "if": r"If _test_ is truthy, returns _thenValue_. Otherwise, returns _elseValue_. The _if_ function is equivalent to the ternary operator `a ? b : c`.",
18
+ "isNaN": r"Returns true if _value_ is not a number. Same as JavaScript's `isNaN`.",
19
+ "isFinite": r"Returns true if _value_ is a finite number. Same as JavaScript's `isFinite`.",
20
+ "abs": r"Returns the absolute value of _value_. Same as JavaScript's `Math.abs`.",
21
+ "acos": r"Trigonometric arccosine. Same as JavaScript's `Math.acos`.",
22
+ "asin": r"Trigonometric arcsine. Same as JavaScript's `Math.asin`.",
23
+ "atan": r"Trigonometric arctangent. Same as JavaScript's `Math.atan`.",
24
+ "atan2": r"Returns the arctangent of _dy / dx_. Same as JavaScript's `Math.atan2`.",
25
+ "ceil": r"Rounds _value_ to the nearest integer of equal or greater value. Same as JavaScript's `Math.ceil`.",
26
+ "clamp": r"Restricts _value_ to be between the specified _min_ and _max_.",
27
+ "cos": r"Trigonometric cosine. Same as JavaScript's `Math.cos`.",
28
+ "exp": r"Returns the value of _e_ raised to the provided _exponent_. Same as JavaScript's `Math.exp`.",
29
+ "floor": r"Rounds _value_ to the nearest integer of equal or lower value. Same as JavaScript's `Math.floor`.",
30
+ "hypot": r"Returns the square root of the sum of squares of its arguments. Same as JavaScript's `Math.hypot`.",
31
+ "log": r"Returns the natural logarithm of _value_. Same as JavaScript's `Math.log`.",
32
+ "max": r"Returns the maximum argument value. Same as JavaScript's `Math.max`.",
33
+ "min": r"Returns the minimum argument value. Same as JavaScript's `Math.min`.",
34
+ "pow": r"Returns _value_ raised to the given _exponent_. Same as JavaScript's `Math.pow`.",
35
+ "random": r"Returns a pseudo-random number in the range [0,1). Same as JavaScript's `Math.random`.",
36
+ "round": r"Rounds _value_ to the nearest integer. Same as JavaScript's `Math.round`.",
37
+ "sin": r"Trigonometric sine. Same as JavaScript's `Math.sin`.",
38
+ "sqrt": r"Square root function. Same as JavaScript's `Math.sqrt`.",
39
+ "tan": r"Trigonometric tangent. Same as JavaScript's `Math.tan`.",
40
+ "sampleNormal": r"Returns a sample from a univariate [normal (Gaussian) probability distribution](https://en.wikipedia.org/wiki/Normal_distribution) with specified _mean_ and standard deviation _stdev_. If unspecified, the mean defaults to `0` and the standard deviation defaults to `1`.",
41
+ "cumulativeNormal": r"Returns the value of the [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) at the given input domain _value_ for a normal distribution with specified _mean_ and standard deviation _stdev_. If unspecified, the mean defaults to `0` and the standard deviation defaults to `1`.",
42
+ "densityNormal": r"Returns the value of the [probability density function](https://en.wikipedia.org/wiki/Probability_density_function) at the given input domain _value_, for a normal distribution with specified _mean_ and standard deviation _stdev_. If unspecified, the mean defaults to `0` and the standard deviation defaults to `1`.",
43
+ "quantileNormal": r"Returns the quantile value (the inverse of the [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function)) for the given input _probability_, for a normal distribution with specified _mean_ and standard deviation _stdev_. If unspecified, the mean defaults to `0` and the standard deviation defaults to `1`.",
44
+ "sampleLogNormal": r"Returns a sample from a univariate [log-normal probability distribution](https://en.wikipedia.org/wiki/Log-normal_distribution) with specified log _mean_ and log standard deviation _stdev_. If unspecified, the log mean defaults to `0` and the log standard deviation defaults to `1`.",
45
+ "cumulativeLogNormal": r"Returns the value of the [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) at the given input domain _value_ for a log-normal distribution with specified log _mean_ and log standard deviation _stdev_. If unspecified, the log mean defaults to `0` and the log standard deviation defaults to `1`.",
46
+ "densityLogNormal": r"Returns the value of the [probability density function](https://en.wikipedia.org/wiki/Probability_density_function) at the given input domain _value_, for a log-normal distribution with specified log _mean_ and log standard deviation _stdev_. If unspecified, the log mean defaults to `0` and the log standard deviation defaults to `1`.",
47
+ "quantileLogNormal": r"Returns the quantile value (the inverse of the [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function)) for the given input _probability_, for a log-normal distribution with specified log _mean_ and log standard deviation _stdev_. If unspecified, the log mean defaults to `0` and the log standard deviation defaults to `1`.",
48
+ "sampleUniform": r"Returns a sample from a univariate [continuous uniform probability distribution](https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)) over the interval [_min_, _max_). If unspecified, _min_ defaults to `0` and _max_ defaults to `1`. If only one argument is provided, it is interpreted as the _max_ value.",
49
+ "cumulativeUniform": r"Returns the value of the [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) at the given input domain _value_ for a uniform distribution over the interval [_min_, _max_). If unspecified, _min_ defaults to `0` and _max_ defaults to `1`. If only one argument is provided, it is interpreted as the _max_ value.",
50
+ "densityUniform": r"Returns the value of the [probability density function](https://en.wikipedia.org/wiki/Probability_density_function) at the given input domain _value_, for a uniform distribution over the interval [_min_, _max_). If unspecified, _min_ defaults to `0` and _max_ defaults to `1`. If only one argument is provided, it is interpreted as the _max_ value.",
51
+ "quantileUniform": r"Returns the quantile value (the inverse of the [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function)) for the given input _probability_, for a uniform distribution over the interval [_min_, _max_). If unspecified, _min_ defaults to `0` and _max_ defaults to `1`. If only one argument is provided, it is interpreted as the _max_ value.",
52
+ "now": r"Returns the timestamp for the current time.",
53
+ "datetime": r"Returns a new `Date` instance. The _month_ is 0-based, such that `1` represents February.",
54
+ "date": r"Returns the day of the month for the given _datetime_ value, in local time.",
55
+ "day": r"Returns the day of the week for the given _datetime_ value, in local time.",
56
+ "dayofyear": r"Returns the one-based day of the year for the given _datetime_ value, in local time.",
57
+ "year": r"Returns the year for the given _datetime_ value, in local time.",
58
+ "quarter": r"Returns the quarter of the year (0-3) for the given _datetime_ value, in local time.",
59
+ "month": r"Returns the (zero-based) month for the given _datetime_ value, in local time.",
60
+ "week": r"Returns the week number of the year for the given _datetime_, in local time. This function assumes Sunday-based weeks. Days before the first Sunday of the year are considered to be in week 0, the first Sunday of the year is the start of week 1, the second Sunday week 2, _etc._.",
61
+ "hours": r"Returns the hours component for the given _datetime_ value, in local time.",
62
+ "minutes": r"Returns the minutes component for the given _datetime_ value, in local time.",
63
+ "seconds": r"Returns the seconds component for the given _datetime_ value, in local time.",
64
+ "milliseconds": r"Returns the milliseconds component for the given _datetime_ value, in local time.",
65
+ "time": r"Returns the epoch-based timestamp for the given _datetime_ value.",
66
+ "timezoneoffset": r"Returns the timezone offset from the local timezone to UTC for the given _datetime_ value.",
67
+ "timeOffset": r"Returns a new `Date` instance that offsets the given _date_ by the specified time [_unit_](../api/time/#time-units) in the local timezone. The optional _step_ argument indicates the number of time unit steps to offset by (default 1).",
68
+ "timeSequence": r"Returns an array of `Date` instances from _start_ (inclusive) to _stop_ (exclusive), with each entry separated by the given time [_unit_](../api/time/#time-units) in the local timezone. The optional _step_ argument indicates the number of time unit steps to take between each sequence entry (default 1).",
69
+ "utc": r"Returns a timestamp for the given UTC date. The _month_ is 0-based, such that `1` represents February.",
70
+ "utcdate": r"Returns the day of the month for the given _datetime_ value, in UTC time.",
71
+ "utcday": r"Returns the day of the week for the given _datetime_ value, in UTC time.",
72
+ "utcdayofyear": r"Returns the one-based day of the year for the given _datetime_ value, in UTC time.",
73
+ "utcyear": r"Returns the year for the given _datetime_ value, in UTC time.",
74
+ "utcquarter": r"Returns the quarter of the year (0-3) for the given _datetime_ value, in UTC time.",
75
+ "utcmonth": r"Returns the (zero-based) month for the given _datetime_ value, in UTC time.",
76
+ "utcweek": r"Returns the week number of the year for the given _datetime_, in UTC time. This function assumes Sunday-based weeks. Days before the first Sunday of the year are considered to be in week 0, the first Sunday of the year is the start of week 1, the second Sunday week 2, _etc._.",
77
+ "utchours": r"Returns the hours component for the given _datetime_ value, in UTC time.",
78
+ "utcminutes": r"Returns the minutes component for the given _datetime_ value, in UTC time.",
79
+ "utcseconds": r"Returns the seconds component for the given _datetime_ value, in UTC time.",
80
+ "utcmilliseconds": r"Returns the milliseconds component for the given _datetime_ value, in UTC time.",
81
+ "utcOffset": r"Returns a new `Date` instance that offsets the given _date_ by the specified time [_unit_](../api/time/#time-units) in UTC time. The optional _step_ argument indicates the number of time unit steps to offset by (default 1).",
82
+ "utcSequence": r"Returns an array of `Date` instances from _start_ (inclusive) to _stop_ (exclusive), with each entry separated by the given time [_unit_](../api/time/#time-units) in UTC time. The optional _step_ argument indicates the number of time unit steps to take between each sequence entry (default 1).",
83
+ "extent": r"Returns a new _[min, max]_ array with the minimum and maximum values of the input array, ignoring `null`, `undefined`, and `NaN` values.",
84
+ "clampRange": r"Clamps a two-element _range_ array in a span-preserving manner. If the span of the input _range_ is less than _(max - min)_ and an endpoint exceeds either the _min_ or _max_ value, the range is translated such that the span is preserved and one endpoint touches the boundary of the _[min, max]_ range. If the span exceeds _(max - min)_, the range _[min, max]_ is returned.",
85
+ "indexof": r"Returns the first index of _value_ in the input _array_, or the first index of _substring_ in the input _string_..",
86
+ "inrange": r"Tests whether _value_ lies within (or is equal to either) the first and last values of the _range_ array.",
87
+ "join": r"Returns a new string by concatenating all of the elements of the input _array_, separated by commas or a specified _separator_ string.",
88
+ "lastindexof": r"Returns the last index of _value_ in the input _array_, or the last index of _substring_ in the input _string_..",
89
+ "length": r"Returns the length of the input _array_, or the length of the input _string_.",
90
+ "lerp": r"Returns the linearly interpolated value between the first and last entries in the _array_ for the provided interpolation _fraction_ (typically between 0 and 1). For example, `lerp([0, 50], 0.5)` returns 25.",
91
+ "peek": r"Returns the last element in the input _array_. Similar to the built-in `Array.pop` method, except that it does not remove the last element. This method is a convenient shorthand for `array[array.length - 1]`.",
92
+ "pluck": r"Retrieves the value for the specified *field* from a given *array* of objects. The input *field* string may include nested properties (e.g., `foo.bar.bz`).",
93
+ "reverse": r"Returns a new array with elements in a reverse order of the input _array_. The first array element becomes the last, and the last array element becomes the first.",
94
+ "sequence": r"Returns an array containing an arithmetic sequence of numbers. If _step_ is omitted, it defaults to 1. If _start_ is omitted, it defaults to 0. The _stop_ value is exclusive; it is not included in the result. If _step_ is positive, the last element is the largest _start + i * step_ less than _stop_; if _step_ is negative, the last element is the smallest _start + i * step_ greater than _stop_. If the returned array would contain an infinite number of values, an empty range is returned. The arguments are not required to be integers.",
95
+ "slice": r"Returns a section of _array_ between the _start_ and _end_ indices. If the _end_ argument is negative, it is treated as an offset from the end of the array (_length(array) + end_).",
96
+ "span": r"Returns the span of _array_: the difference between the last and first elements, or _array[array.length-1] - array[0]_. Or if input is a string: a section of _string_ between the _start_ and _end_ indices. If the _end_ argument is negative, it is treated as an offset from the end of the string (_length(string) + end_)..",
97
+ "lower": r"Transforms _string_ to lower-case letters.",
98
+ "pad": r"Pads a _string_ value with repeated instances of a _character_ up to a specified _length_. If _character_ is not specified, a space (' ') is used. By default, padding is added to the end of a string. An optional _align_ parameter specifies if padding should be added to the `'left'` (beginning), `'center'`, or `'right'` (end) of the input string.",
99
+ "parseFloat": r"Parses the input _string_ to a floating-point value. Same as JavaScript's `parseFloat`.",
100
+ "parseInt": r"Parses the input _string_ to an integer value. Same as JavaScript's `parseInt`.",
101
+ "replace": r"Returns a new string with some or all matches of _pattern_ replaced by a _replacement_ string. The _pattern_ can be a string or a regular expression. If _pattern_ is a string, only the first instance will be replaced. Same as [JavaScript's String.replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace).",
102
+ "split": r"Returns an array of tokens created by splitting the input _string_ according to a provided _separator_ pattern. The result can optionally be constrained to return at most _limit_ tokens.",
103
+ "substring": r"Returns a section of _string_ between the _start_ and _end_ indices.",
104
+ "trim": r"Returns a trimmed string with preceding and trailing whitespace removed.",
105
+ "truncate": r"Truncates an input _string_ to a target _length_. The optional _align_ argument indicates what part of the string should be truncated: `'left'` (the beginning), `'center'`, or `'right'` (the end). By default, the `'right'` end of the string is truncated. The optional _ellipsis_ argument indicates the string to use to indicate truncated content; by default the ellipsis character `...` (`\\u2026`) is used.",
106
+ "upper": r"Transforms _string_ to upper-case letters.",
107
+ "merge": r"Merges the input objects _object1_, _object2_, etc into a new output object. Inputs are visited in sequential order, such that key values from later arguments can overwrite those from earlier arguments. Example: `merge({a:1, b:2}, {a:3}) -> {a:3, b:2}`.",
108
+ "dayFormat": r"Formats a (0-6) _weekday_ number as a full week day name, according to the current locale. For example: `dayFormat(0) -> \"Sunday\"`.",
109
+ "dayAbbrevFormat": r"Formats a (0-6) _weekday_ number as an abbreviated week day name, according to the current locale. For example: `dayAbbrevFormat(0) -> \"Sun\"`.",
110
+ "format": r"Formats a numeric _value_ as a string. The _specifier_ must be a valid [d3-format specifier](https://github.com/d3/d3-format/) (e.g., `format(value, ',.2f')`.",
111
+ "monthFormat": r"Formats a (zero-based) _month_ number as a full month name, according to the current locale. For example: `monthFormat(0) -> \"January\"`.",
112
+ "monthAbbrevFormat": r"Formats a (zero-based) _month_ number as an abbreviated month name, according to the current locale. For example: `monthAbbrevFormat(0) -> \"Jan\"`.",
113
+ "timeUnitSpecifier": r"Returns a time format specifier string for the given time [_units_](../api/time/#time-units). The optional _specifiers_ object provides a set of specifier sub-strings for customizing the format; for more, see the [timeUnitSpecifier API documentation](../api/time/#timeUnitSpecifier). The resulting specifier string can then be used as input to the [timeFormat](#timeFormat) or [utcFormat](#utcFormat) functions, or as the _format_ parameter of an axis or legend. For example: `timeFormat(date, timeUnitSpecifier('year'))` or `timeFormat(date, timeUnitSpecifier(['hours', 'minutes']))`.",
114
+ "timeFormat": r"Formats a datetime _value_ (either a `Date` object or timestamp) as a string, according to the local time. The _specifier_ must be a valid [d3-time-format specifier](https://github.com/d3/d3-time-format/). For example: `timeFormat(timestamp, '%A')`.",
115
+ "timeParse": r"Parses a _string_ value to a Date object, according to the local time. The _specifier_ must be a valid [d3-time-format specifier](https://github.com/d3/d3-time-format/). For example: `timeParse('June 30, 2015', '%B %d, %Y')`.",
116
+ "utcFormat": r"Formats a datetime _value_ (either a `Date` object or timestamp) as a string, according to [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) time. The _specifier_ must be a valid [d3-time-format specifier](https://github.com/d3/d3-time-format/). For example: `utcFormat(timestamp, '%A')`.",
117
+ "utcParse": r"Parses a _string_ value to a Date object, according to [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) time. The _specifier_ must be a valid [d3-time-format specifier](https://github.com/d3/d3-time-format/). For example: `utcParse('June 30, 2015', '%B %d, %Y')`.",
118
+ "regexp": r"Creates a regular expression instance from an input _pattern_ string and optional _flags_. Same as [JavaScript's `RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp).",
119
+ "test": r"Evaluates a regular expression _regexp_ against the input _string_, returning `true` if the string matches the pattern, `false` otherwise. For example: `test(/\\d{3}/, \"32-21-9483\") -> true`.",
120
+ "rgb": r"Constructs a new [RGB](https://en.wikipedia.org/wiki/RGB_color_model) color. If _r_, _g_ and _b_ are specified, these represent the channel values of the returned color; an _opacity_ may also be specified. If a CSS Color Module Level 3 _specifier_ string is specified, it is parsed and then converted to the RGB color space. Uses [d3-color's rgb function](https://github.com/d3/d3-color#rgb).",
121
+ "hsl": r"Constructs a new [HSL](https://en.wikipedia.org/wiki/HSL_and_HSV) color. If _h_, _s_ and _l_ are specified, these represent the channel values of the returned color; an _opacity_ may also be specified. If a CSS Color Module Level 3 _specifier_ string is specified, it is parsed and then converted to the HSL color space. Uses [d3-color's hsl function](https://github.com/d3/d3-color#hsl).",
122
+ "lab": r"Constructs a new [CIE LAB](https://en.wikipedia.org/wiki/Lab_color_space#CIELAB) color. If _l_, _a_ and _b_ are specified, these represent the channel values of the returned color; an _opacity_ may also be specified. If a CSS Color Module Level 3 _specifier_ string is specified, it is parsed and then converted to the LAB color space. Uses [d3-color's lab function](https://github.com/d3/d3-color#lab).",
123
+ "hcl": r"Constructs a new [HCL](https://en.wikipedia.org/wiki/Lab_color_space#CIELAB) (hue, chroma, luminance) color. If _h_, _c_ and _l_ are specified, these represent the channel values of the returned color; an _opacity_ may also be specified. If a CSS Color Module Level 3 _specifier_ string is specified, it is parsed and then converted to the HCL color space. Uses [d3-color's hcl function](https://github.com/d3/d3-color#hcl).",
124
+ "luminance": r"Returns the luminance for the given color _specifier_ (compatible with [d3-color's rgb function](https://github.com/d3/d3-color#rgb)). The luminance is calculated according to the [W3C Web Content Accessibility Guidelines](https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef).",
125
+ "contrast": r"Returns the contrast ratio between the input color specifiers as a float between 1 and 21. The contrast is calculated according to the [W3C Web Content Accessibility Guidelines](https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef).",
126
+ "item": r"Returns the current scenegraph item that is the target of the event.",
127
+ "group": r"Returns the scenegraph group mark item in which the current event has occurred. If no arguments are provided, the immediate parent group is returned. If a group name is provided, the matching ancestor group item is returned.",
128
+ "xy": r"Returns the x- and y-coordinates for the current event as a two-element array. If no arguments are provided, the top-level coordinate space of the view is used. If a scenegraph _item_ (or string group name) is provided, the coordinate space of the group item is used.",
129
+ "x": r"Returns the x coordinate for the current event. If no arguments are provided, the top-level coordinate space of the view is used. If a scenegraph _item_ (or string group name) is provided, the coordinate space of the group item is used.",
130
+ "y": r"Returns the y coordinate for the current event. If no arguments are provided, the top-level coordinate space of the view is used. If a scenegraph _item_ (or string group name) is provided, the coordinate space of the group item is used.",
131
+ "pinchDistance": r"Returns the pixel distance between the first two touch points of a multi-touch event.",
132
+ "pinchAngle": r"Returns the angle of the line connecting the first two touch points of a multi-touch event.",
133
+ "inScope": r"Returns true if the given scenegraph _item_ is a descendant of the group mark in which the event handler was defined, false otherwise.",
134
+ "data": r"Returns the array of data objects for the Vega data set with the given _name_. If the data set is not found, returns an empty array.",
135
+ "indata": r"Tests if the data set with a given _name_ contains a datum with a _field_ value that matches the input _value_. For example: `indata('table', 'category', value)`.",
136
+ "scale": r"Applies the named scale transform (or projection) to the specified _value_. The optional _group_ argument takes a scenegraph group mark item to indicate the specific scope in which to look up the scale or projection.",
137
+ "invert": r"Inverts the named scale transform (or projection) for the specified _value_. The optional _group_ argument takes a scenegraph group mark item to indicate the specific scope in which to look up the scale or projection.",
138
+ "copy": r"Returns a copy (a new cloned instance) of the named scale transform of projection, or `undefined` if no scale or projection is found. The optional _group_ argument takes a scenegraph group mark item to indicate the specific scope in which to look up the scale or projection.",
139
+ "domain": r"Returns the scale domain array for the named scale transform, or an empty array if the scale is not found. The optional _group_ argument takes a scenegraph group mark item to indicate the specific scope in which to look up the scale.",
140
+ "range": r"Returns the scale range array for the named scale transform, or an empty array if the scale is not found. The optional _group_ argument takes a scenegraph group mark item to indicate the specific scope in which to look up the scale.",
141
+ "bandwidth": r"Returns the current band width for the named band scale transform, or zero if the scale is not found or is not a band scale. The optional _group_ argument takes a scenegraph group mark item to indicate the specific scope in which to look up the scale.",
142
+ "bandspace": r"Returns the number of steps needed within a band scale, based on the _count_ of domain elements and the inner and outer padding values. While normally calculated within the scale itself, this function can be helpful for determining the size of a chart's layout.",
143
+ "gradient": r"Returns a linear color gradient for the _scale_ (whose range must be a [continuous color scheme](../schemes)) and starting and ending points _p0_ and _p1_, each an _[x, y]_ array. The points _p0_ and _p1_ should be expressed in normalized coordinates in the domain [0, 1], relative to the bounds of the item being colored. If unspecified, _p0_ defaults to `[0, 0]` and _p1_ defaults to `[1, 0]`, for a horizontal gradient that spans the full bounds of an item. The optional _count_ argument indicates a desired target number of sample points to take from the color scale.",
144
+ "panLinear": r"Given a linear scale _domain_ array with numeric or datetime values, returns a new two-element domain array that is the result of panning the domain by a fractional _delta_. The _delta_ value represents fractional units of the scale range; for example, `0.5` indicates panning the scale domain to the right by half the scale range.",
145
+ "panLog": r"Given a log scale _domain_ array with numeric or datetime values, returns a new two-element domain array that is the result of panning the domain by a fractional _delta_. The _delta_ value represents fractional units of the scale range; for example, `0.5` indicates panning the scale domain to the right by half the scale range.",
146
+ "panPow": r"Given a power scale _domain_ array with numeric or datetime values and the given _exponent_, returns a new two-element domain array that is the result of panning the domain by a fractional _delta_. The _delta_ value represents fractional units of the scale range; for example, `0.5` indicates panning the scale domain to the right by half the scale range.",
147
+ "panSymlog": r"Given a symmetric log scale _domain_ array with numeric or datetime values parameterized by the given _constant_, returns a new two-element domain array that is the result of panning the domain by a fractional _delta_. The _delta_ value represents fractional units of the scale range; for example, `0.5` indicates panning the scale domain to the right by half the scale range.",
148
+ "zoomLinear": r"Given a linear scale _domain_ array with numeric or datetime values, returns a new two-element domain array that is the result of zooming the domain by a _scaleFactor_, centered at the provided fractional _anchor_. The _anchor_ value represents the zoom position in terms of fractional units of the scale range; for example, `0.5` indicates a zoom centered on the mid-point of the scale range.",
149
+ "zoomLog": r"Given a log scale _domain_ array with numeric or datetime values, returns a new two-element domain array that is the result of zooming the domain by a _scaleFactor_, centered at the provided fractional _anchor_. The _anchor_ value represents the zoom position in terms of fractional units of the scale range; for example, `0.5` indicates a zoom centered on the mid-point of the scale range.",
150
+ "zoomPow": r"Given a power scale _domain_ array with numeric or datetime values and the given _exponent_, returns a new two-element domain array that is the result of zooming the domain by a _scaleFactor_, centered at the provided fractional _anchor_. The _anchor_ value represents the zoom position in terms of fractional units of the scale range; for example, `0.5` indicates a zoom centered on the mid-point of the scale range.",
151
+ "zoomSymlog": r"Given a symmetric log scale _domain_ array with numeric or datetime values parameterized by the given _constant_, returns a new two-element domain array that is the result of zooming the domain by a _scaleFactor_, centered at the provided fractional _anchor_. The _anchor_ value represents the zoom position in terms of fractional units of the scale range; for example, `0.5` indicates a zoom centered on the mid-point of the scale range.",
152
+ "geoArea": r"Returns the projected planar area (typically in square pixels) of a GeoJSON _feature_ according to the named _projection_. If the _projection_ argument is `null`, computes the spherical area in steradians using unprojected longitude, latitude coordinates. The optional _group_ argument takes a scenegraph group mark item to indicate the specific scope in which to look up the projection. Uses d3-geo's [geoArea](https://github.com/d3/d3-geo#geoArea) and [path.area](https://github.com/d3/d3-geo#path_area) methods.",
153
+ "geoBounds": r"Returns the projected planar bounding box (typically in pixels) for the specified GeoJSON _feature_, according to the named _projection_. The bounding box is represented by a two-dimensional array: [[_x0_, _y0_], [_x1_, _y1_]], where _x0_ is the minimum x-coordinate, _y0_ is the minimum y-coordinate, _x1_ is the maximum x-coordinate, and _y1_ is the maximum y-coordinate. If the _projection_ argument is `null`, computes the spherical bounding box using unprojected longitude, latitude coordinates. The optional _group_ argument takes a scenegraph group mark item to indicate the specific scope in which to look up the projection. Uses d3-geo's [geoBounds](https://github.com/d3/d3-geo#geoBounds) and [path.bounds](https://github.com/d3/d3-geo#path_bounds) methods.",
154
+ "geoCentroid": r"Returns the projected planar centroid (typically in pixels) for the specified GeoJSON _feature_, according to the named _projection_. If the _projection_ argument is `null`, computes the spherical centroid using unprojected longitude, latitude coordinates. The optional _group_ argument takes a scenegraph group mark item to indicate the specific scope in which to look up the projection. Uses d3-geo's [geoCentroid](https://github.com/d3/d3-geo#geoCentroid) and [path.centroid](https://github.com/d3/d3-geo#path_centroid) methods.",
155
+ "treePath": r"For the hierarchy data set with the given _name_, returns the shortest path through from the _source_ node id to the _target_ node id. The path starts at the _source_ node, ascends to the least common ancestor of the _source_ node and the _target_ node, and then descends to the _target_ node.",
156
+ "treeAncestors": r"For the hierarchy data set with the given _name_, returns the array of ancestors nodes, starting with the input _node_, then followed by each parent up to the root.",
157
+ "containerSize": r"Returns the current CSS box size (`[el.clientWidth, el.clientHeight]`) of the parent DOM element that contains the Vega view. If there is no container element, returns `[undefined, undefined]`.",
158
+ "screen": r"Returns the [`window.screen`](https://developer.mozilla.org/en-US/docs/Web/API/Window/screen) object, or `{}` if Vega is not running in a browser environment.",
159
+ "windowSize": r"Returns the current window size (`[window.innerWidth, window.innerHeight]`) or `[undefined, undefined]` if Vega is not running in a browser environment.",
160
+ "warn": r"Logs a warning message and returns the last argument. For the message to appear in the console, the visualization view must have the appropriate logging level set.",
161
+ "info": r"Logs an informative message and returns the last argument. For the message to appear in the console, the visualization view must have the appropriate logging level set.",
162
+ "debug": r"Logs a debugging message and returns the last argument. For the message to appear in the console, the visualization view must have the appropriate logging level set.",
163
+ }
164
+
165
+
166
+ # This maps vega expression function names to the Python name
167
+ NAME_MAP = {"if": "if_"}
.venv/lib/python3.13/site-packages/altair/jupyter/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ try:
2
+ import anywidget # noqa: F401
3
+ except ImportError:
4
+ # When anywidget isn't available, create stand-in JupyterChart class
5
+ # that raises an informative import error on construction. This
6
+ # way we can make JupyterChart available in the altair namespace
7
+ # when anywidget is not installed
8
+ class JupyterChart:
9
+ def __init__(self, *args, **kwargs):
10
+ msg = (
11
+ "The Altair JupyterChart requires the anywidget \n"
12
+ "Python package which may be installed using pip with\n"
13
+ " pip install anywidget\n"
14
+ "or using conda with\n"
15
+ " conda install -c conda-forge anywidget\n"
16
+ "Afterwards, you will need to restart your Python kernel."
17
+ )
18
+ raise ImportError(msg)
19
+
20
+ else:
21
+ from .jupyter_chart import JupyterChart # noqa: F401
.venv/lib/python3.13/site-packages/altair/jupyter/js/README.md ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # JupyterChart
2
+ This directory contains the JavaScript portion of the Altair `JupyterChart`. The `JupyterChart` is based on the [AnyWidget](https://anywidget.dev/) project.
.venv/lib/python3.13/site-packages/altair/jupyter/js/index.js ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import vegaEmbed from "https://esm.sh/vega-embed@v7?deps=vega@6&deps=vega-lite@6.1.0";
2
+ import lodashDebounce from "https://esm.sh/lodash-es@4.17.21/debounce";
3
+
4
+ // Note: For offline support, the import lines above are removed and the remaining script
5
+ // is bundled using vl-convert's javascript_bundle function. See the documentation of
6
+ // the javascript_bundle function for details on the available imports and their names.
7
+ // If an additional import is required in the future, it will need to be added to vl-convert
8
+ // in order to preserve offline support.
9
+ async function render({ model, el }) {
10
+ let finalize;
11
+
12
+ function showError(error){
13
+ el.innerHTML = (
14
+ '<div style="color:red;">'
15
+ + '<p>JavaScript Error: ' + error.message + '</p>'
16
+ + "<p>This usually means there's a typo in your chart specification. "
17
+ + "See the javascript console for the full traceback.</p>"
18
+ + '</div>'
19
+ );
20
+ }
21
+
22
+ const reembed = async () => {
23
+ if (finalize != null) {
24
+ finalize();
25
+ }
26
+
27
+ model.set("local_tz", Intl.DateTimeFormat().resolvedOptions().timeZone);
28
+
29
+ let spec = structuredClone(model.get("spec"));
30
+ if (spec == null) {
31
+ // Remove any existing chart and return
32
+ while (el.firstChild) {
33
+ el.removeChild(el.lastChild);
34
+ }
35
+ model.save_changes();
36
+ return;
37
+ }
38
+ let embedOptions = structuredClone(model.get("embed_options")) ?? undefined;
39
+
40
+ let api;
41
+ try {
42
+ api = await vegaEmbed(el, spec, embedOptions);
43
+ } catch (error) {
44
+ showError(error)
45
+ return;
46
+ }
47
+
48
+ finalize = api.finalize;
49
+
50
+ // Debounce config
51
+ const wait = model.get("debounce_wait") ?? 10;
52
+ const debounceOpts = {leading: false, trailing: true};
53
+ if (model.get("max_wait") ?? true) {
54
+ debounceOpts["maxWait"] = wait;
55
+ }
56
+
57
+ const initialSelections = {};
58
+ for (const selectionName of Object.keys(model.get("_vl_selections"))) {
59
+ const storeName = `${selectionName}_store`;
60
+ const selectionHandler = (_, value) => {
61
+ const newSelections = cleanJson(model.get("_vl_selections") ?? {});
62
+ const store = cleanJson(api.view.data(storeName) ?? []);
63
+
64
+ newSelections[selectionName] = {value, store};
65
+ model.set("_vl_selections", newSelections);
66
+ model.save_changes();
67
+ };
68
+ api.view.addSignalListener(selectionName, lodashDebounce(selectionHandler, wait, debounceOpts));
69
+
70
+ initialSelections[selectionName] = {
71
+ value: cleanJson(api.view.signal(selectionName) ?? {}),
72
+ store: cleanJson(api.view.data(storeName) ?? [])
73
+ }
74
+ }
75
+ model.set("_vl_selections", initialSelections);
76
+
77
+ const initialParams = {};
78
+ for (const paramName of Object.keys(model.get("_params"))) {
79
+ const paramHandler = (_, value) => {
80
+ const newParams = JSON.parse(JSON.stringify(model.get("_params"))) || {};
81
+ newParams[paramName] = value;
82
+ model.set("_params", newParams);
83
+ model.save_changes();
84
+ };
85
+ api.view.addSignalListener(paramName, lodashDebounce(paramHandler, wait, debounceOpts));
86
+
87
+ initialParams[paramName] = api.view.signal(paramName) ?? null
88
+ }
89
+ model.set("_params", initialParams);
90
+ model.save_changes();
91
+
92
+ // Param change callback
93
+ model.on('change:_params', async (new_params) => {
94
+ for (const [param, value] of Object.entries(new_params.changed ? new_params.changed._params : new_params)) {
95
+ api.view.signal(param, value);
96
+ }
97
+ await api.view.runAsync();
98
+ });
99
+
100
+ // Add signal/data listeners
101
+ for (const watch of model.get("_js_watch_plan") ?? []) {
102
+ if (watch.namespace === "data") {
103
+ const dataHandler = (_, value) => {
104
+ model.set("_js_to_py_updates", [{
105
+ namespace: "data",
106
+ name: watch.name,
107
+ scope: watch.scope,
108
+ value: cleanJson(value)
109
+ }]);
110
+ model.save_changes();
111
+ };
112
+ addDataListener(api.view, watch.name, watch.scope, lodashDebounce(dataHandler, wait, debounceOpts))
113
+
114
+ } else if (watch.namespace === "signal") {
115
+ const signalHandler = (_, value) => {
116
+ model.set("_js_to_py_updates", [{
117
+ namespace: "signal",
118
+ name: watch.name,
119
+ scope: watch.scope,
120
+ value: cleanJson(value)
121
+ }]);
122
+ model.save_changes();
123
+ };
124
+
125
+ addSignalListener(api.view, watch.name, watch.scope, lodashDebounce(signalHandler, wait, debounceOpts))
126
+ }
127
+ }
128
+
129
+ // Add signal/data updaters
130
+ model.on('change:_py_to_js_updates', async (updates) => {
131
+ const py_to_js_updates = updates.changed ? updates.changed._py_to_js_updates : updates;
132
+ for (const update of py_to_js_updates ?? []) {
133
+ if (update.namespace === "signal") {
134
+ setSignalValue(api.view, update.name, update.scope, update.value);
135
+ } else if (update.namespace === "data") {
136
+ setDataValue(api.view, update.name, update.scope, update.value);
137
+ }
138
+ }
139
+ await api.view.runAsync();
140
+ });
141
+ }
142
+
143
+ model.on('change:spec', reembed);
144
+ model.on('change:embed_options', reembed);
145
+ model.on('change:debounce_wait', reembed);
146
+ model.on('change:max_wait', reembed);
147
+ await reembed();
148
+ }
149
+
150
+ function cleanJson(data) {
151
+ return JSON.parse(JSON.stringify(data))
152
+ }
153
+
154
+ function getNestedRuntime(view, scope) {
155
+ var runtime = view._runtime;
156
+ for (const index of scope) {
157
+ runtime = runtime.subcontext[index];
158
+ }
159
+ return runtime
160
+ }
161
+
162
+ function lookupSignalOp(view, name, scope) {
163
+ let parent_runtime = getNestedRuntime(view, scope);
164
+ return parent_runtime.signals[name] ?? null;
165
+ }
166
+
167
+ function dataRef(view, name, scope) {
168
+ let parent_runtime = getNestedRuntime(view, scope);
169
+ return parent_runtime.data[name];
170
+ }
171
+
172
+ export function setSignalValue(view, name, scope, value) {
173
+ let signal_op = lookupSignalOp(view, name, scope);
174
+ view.update(signal_op, value);
175
+ }
176
+
177
+ export function setDataValue(view, name, scope, value) {
178
+ let dataset = dataRef(view, name, scope);
179
+ let changeset = view.changeset().remove(() => true).insert(value)
180
+ dataset.modified = true;
181
+ view.pulse(dataset.input, changeset);
182
+ }
183
+
184
+ export function addSignalListener(view, name, scope, handler) {
185
+ let signal_op = lookupSignalOp(view, name, scope);
186
+ return addOperatorListener(
187
+ view,
188
+ name,
189
+ signal_op,
190
+ handler,
191
+ );
192
+ }
193
+
194
+ export function addDataListener(view, name, scope, handler) {
195
+ let dataset = dataRef(view, name, scope).values;
196
+ return addOperatorListener(
197
+ view,
198
+ name,
199
+ dataset,
200
+ handler,
201
+ );
202
+ }
203
+
204
+ // Private helpers from Vega for dealing with nested signals/data
205
+ function findOperatorHandler(op, handler) {
206
+ const h = (op._targets || [])
207
+ .filter(op => op._update && op._update.handler === handler);
208
+ return h.length ? h[0] : null;
209
+ }
210
+
211
+ function addOperatorListener(view, name, op, handler) {
212
+ let h = findOperatorHandler(op, handler);
213
+ if (!h) {
214
+ h = trap(view, () => handler(name, op.value));
215
+ h.handler = handler;
216
+ view.on(op, null, h);
217
+ }
218
+ return view;
219
+ }
220
+
221
+ function trap(view, fn) {
222
+ return !fn ? null : function() {
223
+ try {
224
+ fn.apply(this, arguments);
225
+ } catch (error) {
226
+ view.error(error);
227
+ }
228
+ };
229
+ }
230
+
231
+ export default { render }
.venv/lib/python3.13/site-packages/altair/jupyter/jupyter_chart.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import pathlib
5
+ from typing import Any
6
+
7
+ import anywidget
8
+ import traitlets
9
+
10
+ import altair as alt
11
+ from altair import TopLevelSpec
12
+ from altair.utils._vegafusion_data import (
13
+ compile_to_vegafusion_chart_state,
14
+ using_vegafusion,
15
+ )
16
+ from altair.utils.selection import IndexSelection, IntervalSelection, PointSelection
17
+
18
+ _here = pathlib.Path(__file__).parent
19
+
20
+
21
+ class Params(traitlets.HasTraits):
22
+ """Traitlet class storing a JupyterChart's params."""
23
+
24
+ def __init__(self, trait_values):
25
+ super().__init__()
26
+
27
+ for key, value in trait_values.items():
28
+ if isinstance(value, (int, float)):
29
+ traitlet_type = traitlets.Float()
30
+ elif isinstance(value, str):
31
+ traitlet_type = traitlets.Unicode()
32
+ elif isinstance(value, list):
33
+ traitlet_type = traitlets.List()
34
+ elif isinstance(value, dict):
35
+ traitlet_type = traitlets.Dict()
36
+ else:
37
+ traitlet_type = traitlets.Any()
38
+
39
+ # Add the new trait.
40
+ self.add_traits(**{key: traitlet_type})
41
+
42
+ # Set the trait's value.
43
+ setattr(self, key, value)
44
+
45
+ def __repr__(self):
46
+ return f"Params({self.trait_values()})"
47
+
48
+
49
+ class Selections(traitlets.HasTraits):
50
+ """Traitlet class storing a JupyterChart's selections."""
51
+
52
+ def __init__(self, trait_values):
53
+ super().__init__()
54
+
55
+ for key, value in trait_values.items():
56
+ if isinstance(value, IndexSelection):
57
+ traitlet_type = traitlets.Instance(IndexSelection)
58
+ elif isinstance(value, PointSelection):
59
+ traitlet_type = traitlets.Instance(PointSelection)
60
+ elif isinstance(value, IntervalSelection):
61
+ traitlet_type = traitlets.Instance(IntervalSelection)
62
+ else:
63
+ msg = f"Unexpected selection type: {type(value)}"
64
+ raise ValueError(msg)
65
+
66
+ # Add the new trait.
67
+ self.add_traits(**{key: traitlet_type})
68
+
69
+ # Set the trait's value.
70
+ setattr(self, key, value)
71
+
72
+ # Make read-only
73
+ self.observe(self._make_read_only, names=key)
74
+
75
+ def __repr__(self):
76
+ return f"Selections({self.trait_values()})"
77
+
78
+ def _make_read_only(self, change):
79
+ """Work around to make traits read-only, but still allow us to change them internally."""
80
+ if change["name"] in self.traits() and change["old"] != change["new"]:
81
+ self._set_value(change["name"], change["old"])
82
+ msg = (
83
+ "Selections may not be set from Python.\n"
84
+ f"Attempted to set select: {change['name']}"
85
+ )
86
+ raise ValueError(msg)
87
+
88
+ def _set_value(self, key, value):
89
+ self.unobserve(self._make_read_only, names=key)
90
+ setattr(self, key, value)
91
+ self.observe(self._make_read_only, names=key)
92
+
93
+
94
+ def load_js_src() -> str:
95
+ return (_here / "js" / "index.js").read_text()
96
+
97
+
98
+ class JupyterChart(anywidget.AnyWidget):
99
+ _esm = load_js_src()
100
+ _css = r"""
101
+ .vega-embed {
102
+ /* Make sure action menu isn't cut off */
103
+ overflow: visible;
104
+ }
105
+ """
106
+
107
+ # Public traitlets
108
+ chart = traitlets.Instance(TopLevelSpec, allow_none=True)
109
+ spec = traitlets.Dict(allow_none=True).tag(sync=True)
110
+ debounce_wait = traitlets.Float(default_value=10).tag(sync=True)
111
+ max_wait = traitlets.Bool(default_value=True).tag(sync=True)
112
+ local_tz = traitlets.Unicode(default_value=None, allow_none=True).tag(sync=True)
113
+ debug = traitlets.Bool(default_value=False)
114
+ embed_options = traitlets.Dict(default_value=None, allow_none=True).tag(sync=True)
115
+
116
+ # Internal selection traitlets
117
+ _selection_types = traitlets.Dict()
118
+ _vl_selections = traitlets.Dict().tag(sync=True)
119
+
120
+ # Internal param traitlets
121
+ _params = traitlets.Dict().tag(sync=True)
122
+
123
+ # Internal comm traitlets for VegaFusion support
124
+ _chart_state = traitlets.Any(allow_none=True)
125
+ _js_watch_plan = traitlets.Any(allow_none=True).tag(sync=True)
126
+ _js_to_py_updates = traitlets.Any(allow_none=True).tag(sync=True)
127
+ _py_to_js_updates = traitlets.Any(allow_none=True).tag(sync=True)
128
+
129
+ # Track whether charts are configured for offline use
130
+ _is_offline = False
131
+
132
+ @classmethod
133
+ def enable_offline(cls, offline: bool = True):
134
+ """
135
+ Configure JupyterChart's offline behavior.
136
+
137
+ Parameters
138
+ ----------
139
+ offline: bool
140
+ If True, configure JupyterChart to operate in offline mode where JavaScript
141
+ dependencies are loaded from vl-convert.
142
+ If False, configure it to operate in online mode where JavaScript dependencies
143
+ are loaded from CDN dynamically. This is the default behavior.
144
+ """
145
+ from altair.utils._importers import import_vl_convert, vl_version_for_vl_convert
146
+
147
+ if offline:
148
+ if cls._is_offline:
149
+ # Already offline
150
+ return
151
+
152
+ vlc = import_vl_convert()
153
+
154
+ src_lines = load_js_src().split("\n")
155
+
156
+ # Remove leading lines with only whitespace, comments, or imports
157
+ while src_lines and (
158
+ len(src_lines[0].strip()) == 0
159
+ or src_lines[0].startswith("import")
160
+ or src_lines[0].startswith("//")
161
+ ):
162
+ src_lines.pop(0)
163
+
164
+ src = "\n".join(src_lines)
165
+
166
+ # vl-convert's javascript_bundle function creates a self-contained JavaScript bundle
167
+ # for JavaScript snippets that import from a small set of dependencies that
168
+ # vl-convert includes. To see the available imports and their imported names, run
169
+ # import vl_convert as vlc
170
+ # help(vlc.javascript_bundle)
171
+ bundled_src = vlc.javascript_bundle(
172
+ src, vl_version=vl_version_for_vl_convert()
173
+ )
174
+ cls._esm = bundled_src
175
+ cls._is_offline = True
176
+ else:
177
+ cls._esm = load_js_src()
178
+ cls._is_offline = False
179
+
180
+ def __init__(
181
+ self,
182
+ chart: TopLevelSpec,
183
+ debounce_wait: int = 10,
184
+ max_wait: bool = True,
185
+ debug: bool = False,
186
+ embed_options: dict | None = None,
187
+ **kwargs: Any,
188
+ ):
189
+ """
190
+ Jupyter Widget for displaying and updating Altair Charts, and retrieving selection and parameter values.
191
+
192
+ Parameters
193
+ ----------
194
+ chart: Chart
195
+ Altair Chart instance
196
+ debounce_wait: int
197
+ Debouncing wait time in milliseconds. Updates will be sent from the client to the kernel
198
+ after debounce_wait milliseconds of no chart interactions.
199
+ max_wait: bool
200
+ If True (default), updates will be sent from the client to the kernel every debounce_wait
201
+ milliseconds even if there are ongoing chart interactions. If False, updates will not be
202
+ sent until chart interactions have completed.
203
+ debug: bool
204
+ If True, debug messages will be printed
205
+ embed_options: dict
206
+ Options to pass to vega-embed.
207
+ See https://github.com/vega/vega-embed?tab=readme-ov-file#options
208
+ """
209
+ self.params = Params({})
210
+ self.selections = Selections({})
211
+ super().__init__(
212
+ chart=chart,
213
+ debounce_wait=debounce_wait,
214
+ max_wait=max_wait,
215
+ debug=debug,
216
+ embed_options=embed_options,
217
+ **kwargs,
218
+ )
219
+
220
+ @traitlets.observe("chart")
221
+ def _on_change_chart(self, change): # noqa: C901
222
+ """Updates the JupyterChart's internal state when the wrapped Chart instance changes."""
223
+ new_chart = change.new
224
+ selection_watches = []
225
+ selection_types = {}
226
+ initial_params = {}
227
+ initial_vl_selections = {}
228
+ empty_selections = {}
229
+
230
+ if new_chart is None:
231
+ with self.hold_sync():
232
+ self.spec = None
233
+ self._selection_types = selection_types
234
+ self._vl_selections = initial_vl_selections
235
+ self._params = initial_params
236
+ return
237
+
238
+ params = getattr(new_chart, "params", [])
239
+
240
+ if params is not alt.Undefined:
241
+ for param in new_chart.params:
242
+ if isinstance(param.name, alt.ParameterName):
243
+ clean_name = param.name.to_json().strip('"')
244
+ else:
245
+ clean_name = param.name
246
+
247
+ select = getattr(param, "select", alt.Undefined)
248
+
249
+ if select != alt.Undefined:
250
+ if not isinstance(select, dict):
251
+ select = select.to_dict()
252
+
253
+ select_type = select["type"]
254
+ if select_type == "point":
255
+ if not (
256
+ select.get("fields", None) or select.get("encodings", None)
257
+ ):
258
+ # Point selection with no associated fields or encodings specified.
259
+ # This is an index-based selection
260
+ selection_types[clean_name] = "index"
261
+ empty_selections[clean_name] = IndexSelection(
262
+ name=clean_name, value=[], store=[]
263
+ )
264
+ else:
265
+ selection_types[clean_name] = "point"
266
+ empty_selections[clean_name] = PointSelection(
267
+ name=clean_name, value=[], store=[]
268
+ )
269
+ elif select_type == "interval":
270
+ selection_types[clean_name] = "interval"
271
+ empty_selections[clean_name] = IntervalSelection(
272
+ name=clean_name, value={}, store=[]
273
+ )
274
+ else:
275
+ msg = f"Unexpected selection type {select.type}"
276
+ raise ValueError(msg)
277
+ selection_watches.append(clean_name)
278
+ initial_vl_selections[clean_name] = {"value": None, "store": []}
279
+ else:
280
+ clean_value = param.value if param.value != alt.Undefined else None
281
+ initial_params[clean_name] = clean_value
282
+
283
+ # Handle the params generated by transforms
284
+ for param_name in collect_transform_params(new_chart):
285
+ initial_params[param_name] = None
286
+
287
+ # Setup params
288
+ self.params = Params(initial_params)
289
+
290
+ def on_param_traitlet_changed(param_change):
291
+ new_params = dict(self._params)
292
+ new_params[param_change["name"]] = param_change["new"]
293
+ self._params = new_params
294
+
295
+ self.params.observe(on_param_traitlet_changed)
296
+
297
+ # Setup selections
298
+ self.selections = Selections(empty_selections)
299
+
300
+ # Update properties all together
301
+ with self.hold_sync():
302
+ if using_vegafusion():
303
+ if self.local_tz is None:
304
+ self.spec = None
305
+
306
+ def on_local_tz_change(change):
307
+ self._init_with_vegafusion(change["new"])
308
+
309
+ self.observe(on_local_tz_change, ["local_tz"])
310
+ else:
311
+ self._init_with_vegafusion(self.local_tz)
312
+ else:
313
+ self.spec = new_chart.to_dict()
314
+ self._selection_types = selection_types
315
+ self._vl_selections = initial_vl_selections
316
+ self._params = initial_params
317
+
318
+ def _init_with_vegafusion(self, local_tz: str):
319
+ if self.chart is not None:
320
+ vegalite_spec = self.chart.to_dict(context={"pre_transform": False})
321
+ with self.hold_sync():
322
+ self._chart_state = compile_to_vegafusion_chart_state(
323
+ vegalite_spec, local_tz
324
+ )
325
+ self._js_watch_plan = self._chart_state.get_watch_plan()[
326
+ "client_to_server"
327
+ ]
328
+ self.spec = self._chart_state.get_transformed_spec()
329
+
330
+ # Callback to update chart state and send updates back to client
331
+ def on_js_to_py_updates(change):
332
+ if self.debug:
333
+ updates_str = json.dumps(change["new"], indent=2)
334
+ print(
335
+ f"JavaScript to Python VegaFusion updates:\n {updates_str}"
336
+ )
337
+ updates = self._chart_state.update(change["new"])
338
+ if self.debug:
339
+ updates_str = json.dumps(updates, indent=2)
340
+ print(
341
+ f"Python to JavaScript VegaFusion updates:\n {updates_str}"
342
+ )
343
+ self._py_to_js_updates = updates
344
+
345
+ self.observe(on_js_to_py_updates, ["_js_to_py_updates"])
346
+
347
+ @traitlets.observe("_params")
348
+ def _on_change_params(self, change):
349
+ for param_name, value in change.new.items():
350
+ setattr(self.params, param_name, value)
351
+
352
+ @traitlets.observe("_vl_selections")
353
+ def _on_change_selections(self, change):
354
+ """Updates the JupyterChart's public selections traitlet in response to changes that the JavaScript logic makes to the internal _selections traitlet."""
355
+ for selection_name, selection_dict in change.new.items():
356
+ value = selection_dict["value"]
357
+ store = selection_dict["store"]
358
+ selection_type = self._selection_types[selection_name]
359
+ if selection_type == "index":
360
+ self.selections._set_value(
361
+ selection_name,
362
+ IndexSelection.from_vega(selection_name, signal=value, store=store),
363
+ )
364
+ elif selection_type == "point":
365
+ self.selections._set_value(
366
+ selection_name,
367
+ PointSelection.from_vega(selection_name, signal=value, store=store),
368
+ )
369
+ elif selection_type == "interval":
370
+ self.selections._set_value(
371
+ selection_name,
372
+ IntervalSelection.from_vega(
373
+ selection_name, signal=value, store=store
374
+ ),
375
+ )
376
+
377
+
378
+ def collect_transform_params(chart: TopLevelSpec) -> set[str]:
379
+ """
380
+ Collect the names of params that are defined by transforms.
381
+
382
+ Parameters
383
+ ----------
384
+ chart: Chart from which to extract transform params
385
+
386
+ Returns
387
+ -------
388
+ set of param names
389
+ """
390
+ transform_params = set()
391
+
392
+ # Handle recursive case
393
+ for prop in ("layer", "concat", "hconcat", "vconcat"):
394
+ for child in getattr(chart, prop, []):
395
+ transform_params.update(collect_transform_params(child))
396
+
397
+ # Handle chart's own transforms
398
+ transforms = getattr(chart, "transform", [])
399
+ transforms = transforms if transforms != alt.Undefined else []
400
+ for tx in transforms:
401
+ if hasattr(tx, "param"):
402
+ transform_params.add(tx.param)
403
+
404
+ return transform_params
.venv/lib/python3.13/site-packages/altair/typing/__init__.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Public types to ease integrating with `altair`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "ChannelAngle",
7
+ "ChannelColor",
8
+ "ChannelColumn",
9
+ "ChannelDescription",
10
+ "ChannelDetail",
11
+ "ChannelFacet",
12
+ "ChannelFill",
13
+ "ChannelFillOpacity",
14
+ "ChannelHref",
15
+ "ChannelKey",
16
+ "ChannelLatitude",
17
+ "ChannelLatitude2",
18
+ "ChannelLongitude",
19
+ "ChannelLongitude2",
20
+ "ChannelOpacity",
21
+ "ChannelOrder",
22
+ "ChannelRadius",
23
+ "ChannelRadius2",
24
+ "ChannelRow",
25
+ "ChannelShape",
26
+ "ChannelSize",
27
+ "ChannelStroke",
28
+ "ChannelStrokeDash",
29
+ "ChannelStrokeOpacity",
30
+ "ChannelStrokeWidth",
31
+ "ChannelText",
32
+ "ChannelTheta",
33
+ "ChannelTheta2",
34
+ "ChannelTooltip",
35
+ "ChannelUrl",
36
+ "ChannelX",
37
+ "ChannelX2",
38
+ "ChannelXError",
39
+ "ChannelXError2",
40
+ "ChannelXOffset",
41
+ "ChannelY",
42
+ "ChannelY2",
43
+ "ChannelYError",
44
+ "ChannelYError2",
45
+ "ChannelYOffset",
46
+ "ChartType",
47
+ "EncodeKwds",
48
+ "Optional",
49
+ "is_chart_type",
50
+ ]
51
+
52
+ from altair.utils.schemapi import Optional
53
+ from altair.vegalite.v6.api import ChartType, is_chart_type
54
+ from altair.vegalite.v6.schema.channels import (
55
+ ChannelAngle,
56
+ ChannelColor,
57
+ ChannelColumn,
58
+ ChannelDescription,
59
+ ChannelDetail,
60
+ ChannelFacet,
61
+ ChannelFill,
62
+ ChannelFillOpacity,
63
+ ChannelHref,
64
+ ChannelKey,
65
+ ChannelLatitude,
66
+ ChannelLatitude2,
67
+ ChannelLongitude,
68
+ ChannelLongitude2,
69
+ ChannelOpacity,
70
+ ChannelOrder,
71
+ ChannelRadius,
72
+ ChannelRadius2,
73
+ ChannelRow,
74
+ ChannelShape,
75
+ ChannelSize,
76
+ ChannelStroke,
77
+ ChannelStrokeDash,
78
+ ChannelStrokeOpacity,
79
+ ChannelStrokeWidth,
80
+ ChannelText,
81
+ ChannelTheta,
82
+ ChannelTheta2,
83
+ ChannelTooltip,
84
+ ChannelUrl,
85
+ ChannelX,
86
+ ChannelX2,
87
+ ChannelXError,
88
+ ChannelXError2,
89
+ ChannelXOffset,
90
+ ChannelY,
91
+ ChannelY2,
92
+ ChannelYError,
93
+ ChannelYError2,
94
+ ChannelYOffset,
95
+ EncodeKwds,
96
+ )
.venv/lib/python3.13/site-packages/altair/utils/__init__.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .core import (
2
+ SHORTHAND_KEYS,
3
+ display_traceback,
4
+ infer_encoding_types,
5
+ infer_vegalite_type_for_pandas,
6
+ parse_shorthand,
7
+ sanitize_narwhals_dataframe,
8
+ sanitize_pandas_dataframe,
9
+ update_nested,
10
+ use_signature,
11
+ )
12
+ from .deprecation import AltairDeprecationWarning, deprecated, deprecated_warn
13
+ from .html import spec_to_html
14
+ from .plugin_registry import PluginRegistry
15
+ from .schemapi import (
16
+ VERSIONS,
17
+ Optional,
18
+ SchemaBase,
19
+ SchemaLike,
20
+ Undefined,
21
+ is_undefined,
22
+ )
23
+
24
+ __all__ = (
25
+ "SHORTHAND_KEYS",
26
+ "VERSIONS",
27
+ "AltairDeprecationWarning",
28
+ "Optional",
29
+ "PluginRegistry",
30
+ "SchemaBase",
31
+ "SchemaLike",
32
+ "Undefined",
33
+ "deprecated",
34
+ "deprecated_warn",
35
+ "display_traceback",
36
+ "infer_encoding_types",
37
+ "infer_vegalite_type_for_pandas",
38
+ "is_undefined",
39
+ "parse_shorthand",
40
+ "sanitize_narwhals_dataframe",
41
+ "sanitize_pandas_dataframe",
42
+ "spec_to_html",
43
+ "update_nested",
44
+ "use_signature",
45
+ )
.venv/lib/python3.13/site-packages/altair/utils/_dfi_types.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DataFrame Interchange Protocol Types
2
+ # Copied from https://data-apis.org/dataframe-protocol/latest/API.html,
3
+ # changed ABCs to Protocols, and subset the type hints to only those that are
4
+ # relevant for Altair.
5
+ #
6
+ # These classes are only for use in type signatures
7
+ from __future__ import annotations
8
+
9
+ import enum
10
+ from typing import TYPE_CHECKING, Any, Protocol
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Iterable
14
+
15
+
16
+ class DtypeKind(enum.IntEnum):
17
+ """
18
+ Integer enum for data types.
19
+
20
+ Attributes
21
+ ----------
22
+ INT : int
23
+ Matches to signed integer data type.
24
+ UINT : int
25
+ Matches to unsigned integer data type.
26
+ FLOAT : int
27
+ Matches to floating point data type.
28
+ BOOL : int
29
+ Matches to boolean data type.
30
+ STRING : int
31
+ Matches to string data type (UTF-8 encoded).
32
+ DATETIME : int
33
+ Matches to datetime data type.
34
+ CATEGORICAL : int
35
+ Matches to categorical data type.
36
+ """
37
+
38
+ INT = 0
39
+ UINT = 1
40
+ FLOAT = 2
41
+ BOOL = 20
42
+ STRING = 21 # UTF-8
43
+ DATETIME = 22
44
+ CATEGORICAL = 23
45
+
46
+
47
+ # Type hint of first element would actually be DtypeKind but can't use that
48
+ # as other libraries won't use an instance of our own Enum in this module but have
49
+ # their own. Type checkers will raise an error on that even though the enums
50
+ # are identical.
51
+ class Column(Protocol):
52
+ @property
53
+ def dtype(self) -> tuple[Any, int, str, str]:
54
+ """
55
+ Dtype description as a tuple ``(kind, bit-width, format string, endianness)``.
56
+
57
+ Bit-width : the number of bits as an integer
58
+ Format string : data type description format string in Apache Arrow C
59
+ Data Interface format.
60
+ Endianness : current only native endianness (``=``) is supported
61
+
62
+ Notes
63
+ -----
64
+ - Kind specifiers are aligned with DLPack where possible (hence the
65
+ jump to 20, leave enough room for future extension)
66
+ - Masks must be specified as boolean with either bit width 1 (for bit
67
+ masks) or 8 (for byte masks).
68
+ - Dtype width in bits was preferred over bytes
69
+ - Endianness isn't too useful, but included now in case in the future
70
+ we need to support non-native endianness
71
+ - Went with Apache Arrow format strings over NumPy format strings
72
+ because they're more complete from a dataframe perspective
73
+ - Format strings are mostly useful for datetime specification, and
74
+ for categoricals.
75
+ - For categoricals, the format string describes the type of the
76
+ categorical in the data buffer. In case of a separate encoding of
77
+ the categorical (e.g. an integer to string mapping), this can
78
+ be derived from ``self.describe_categorical``.
79
+ - Data types not included: complex, Arrow-style null, binary, decimal,
80
+ and nested (list, struct, map, union) dtypes.
81
+ """
82
+ ...
83
+
84
+ # Have to use a generic Any return type as not all libraries who implement
85
+ # the dataframe interchange protocol implement the TypedDict that is usually
86
+ # returned here in the same way. As TypedDicts are invariant, even a slight change
87
+ # will lead to an error by a type checker. See PR in which this code was added
88
+ # for details.
89
+ @property
90
+ def describe_categorical(self) -> Any:
91
+ """
92
+ If the dtype is categorical, there are two options.
93
+
94
+ - There are only values in the data buffer.
95
+ - There is a separate non-categorical Column encoding categorical values.
96
+
97
+ Raises TypeError if the dtype is not categorical
98
+
99
+ Returns the dictionary with description on how to interpret the data buffer:
100
+ - "is_ordered" : bool, whether the ordering of dictionary indices is
101
+ semantically meaningful.
102
+ - "is_dictionary" : bool, whether a mapping of
103
+ categorical values to other objects exists
104
+ - "categories" : Column representing the (implicit) mapping of indices to
105
+ category values (e.g. an array of cat1, cat2, ...).
106
+ None if not a dictionary-style categorical.
107
+
108
+ TBD: are there any other in-memory representations that are needed?
109
+ """
110
+ ...
111
+
112
+
113
+ class DataFrame(Protocol):
114
+ """
115
+ A data frame class, with only the methods required by the interchange protocol defined.
116
+
117
+ A "data frame" represents an ordered collection of named columns.
118
+ A column's "name" must be a unique string.
119
+ Columns may be accessed by name or by position.
120
+
121
+ This could be a public data frame class, or an object with the methods and
122
+ attributes defined on this DataFrame class could be returned from the
123
+ ``__dataframe__`` method of a public data frame class in a library adhering
124
+ to the dataframe interchange protocol specification.
125
+ """
126
+
127
+ def __dataframe__(
128
+ self, nan_as_null: bool = False, allow_copy: bool = True
129
+ ) -> DataFrame:
130
+ """
131
+ Construct a new exchange object, potentially changing the parameters.
132
+
133
+ ``nan_as_null`` is a keyword intended for the consumer to tell the
134
+ producer to overwrite null values in the data with ``NaN``.
135
+ It is intended for cases where the consumer does not support the bit
136
+ mask or byte mask that is the producer's native representation.
137
+ ``allow_copy`` is a keyword that defines whether or not the library is
138
+ allowed to make a copy of the data. For example, copying data would be
139
+ necessary if a library supports strided buffers, given that this protocol
140
+ specifies contiguous buffers.
141
+ """
142
+ ...
143
+
144
+ def column_names(self) -> Iterable[str]:
145
+ """Return an iterator yielding the column names."""
146
+ ...
147
+
148
+ def get_column_by_name(self, name: str) -> Column:
149
+ """Return the column whose name is the indicated name."""
150
+ ...
151
+
152
+ def get_chunks(self, n_chunks: int | None = None) -> Iterable[DataFrame]:
153
+ """
154
+ Return an iterator yielding the chunks.
155
+
156
+ By default (None), yields the chunks that the data is stored as by the
157
+ producer. If given, ``n_chunks`` must be a multiple of
158
+ ``self.num_chunks()``, meaning the producer must subdivide each chunk
159
+ before yielding it.
160
+
161
+ Note that the producer must ensure that all columns are chunked the
162
+ same way.
163
+ """
164
+ ...
.venv/lib/python3.13/site-packages/altair/utils/_importers.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from importlib.metadata import version as importlib_version
4
+ from typing import TYPE_CHECKING
5
+
6
+ from packaging.version import Version
7
+
8
+ from altair.utils.schemapi import VERSIONS
9
+
10
+ if TYPE_CHECKING:
11
+ from types import ModuleType
12
+
13
+
14
+ def import_vegafusion() -> ModuleType:
15
+ min_version = VERSIONS["vegafusion"]
16
+ try:
17
+ version = importlib_version("vegafusion")
18
+ if Version(version) < Version(min_version):
19
+ msg = (
20
+ f"The vegafusion package must be version {min_version} or greater. "
21
+ f"Found version {version}"
22
+ )
23
+ raise RuntimeError(msg)
24
+ import vegafusion as vf
25
+
26
+ return vf
27
+ except ImportError as err:
28
+ msg = (
29
+ 'The "vegafusion" data transformer and chart.transformed_data feature requires\n'
30
+ f"version {min_version} or greater of the 'vegafusion' package.\n"
31
+ "This can be installed with pip using:\n"
32
+ f' pip install "vegafusion>={min_version}"\n'
33
+ "or conda:\n"
34
+ f' conda install -c conda-forge "vegafusion>={min_version}"\n\n'
35
+ f"ImportError: {err.args[0]}"
36
+ )
37
+ raise ImportError(msg) from err
38
+
39
+
40
+ def import_vl_convert() -> ModuleType:
41
+ min_version = VERSIONS["vl-convert-python"]
42
+ try:
43
+ version = importlib_version("vl-convert-python")
44
+ if Version(version) < Version(min_version):
45
+ msg = (
46
+ f"The vl-convert-python package must be version {min_version} or greater. "
47
+ f"Found version {version}"
48
+ )
49
+ raise RuntimeError(msg)
50
+ import vl_convert as vlc
51
+
52
+ return vlc
53
+ except ImportError as err:
54
+ msg = (
55
+ f"The vl-convert Vega-Lite compiler and file export feature requires\n"
56
+ f"version {min_version} or greater of the 'vl-convert-python' package. \n"
57
+ f"This can be installed with pip using:\n"
58
+ f' pip install "vl-convert-python>={min_version}"\n'
59
+ "or conda:\n"
60
+ f' conda install -c conda-forge "vl-convert-python>={min_version}"\n\n'
61
+ f"ImportError: {err.args[0]}"
62
+ )
63
+ raise ImportError(msg) from err
64
+
65
+
66
+ def vl_version_for_vl_convert() -> str:
67
+ from altair.vegalite import SCHEMA_VERSION
68
+
69
+ # Compute VlConvert's vl_version string (of the form 'v5_2')
70
+ # from SCHEMA_VERSION (of the form 'v5.2.0')
71
+ return "_".join(SCHEMA_VERSION.split(".")[:2])
72
+
73
+
74
+ def import_pyarrow_interchange() -> ModuleType:
75
+ min_version = "11.0.0"
76
+ try:
77
+ version = importlib_version("pyarrow")
78
+
79
+ if Version(version) < Version(min_version):
80
+ msg = (
81
+ f"The pyarrow package must be version {min_version} or greater. "
82
+ f"Found version {version}"
83
+ )
84
+ raise RuntimeError(msg)
85
+ import pyarrow.interchange as pi
86
+
87
+ return pi
88
+ except ImportError as err:
89
+ msg = (
90
+ f"Usage of the DataFrame Interchange Protocol requires\n"
91
+ f"version {min_version} or greater of the pyarrow package. \n"
92
+ f"This can be installed with pip using:\n"
93
+ f' pip install "pyarrow>={min_version}"\n'
94
+ "or conda:\n"
95
+ f' conda install -c conda-forge "pyarrow>={min_version}"\n\n'
96
+ f"ImportError: {err.args[0]}"
97
+ )
98
+ raise ImportError(msg) from err
99
+
100
+
101
+ def pyarrow_available() -> bool:
102
+ try:
103
+ import_pyarrow_interchange()
104
+ return True
105
+ except (ImportError, RuntimeError):
106
+ return False
.venv/lib/python3.13/site-packages/altair/utils/_show.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import webbrowser
4
+ from http.server import BaseHTTPRequestHandler, HTTPServer
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from collections.abc import Iterable
9
+
10
+
11
+ def open_html_in_browser(
12
+ html: str | bytes,
13
+ using: str | Iterable[str] | None = None,
14
+ port: int | None = None,
15
+ ) -> None:
16
+ """
17
+ Display an html document in a web browser without creating a temp file.
18
+
19
+ Instantiates a simple http server and uses the webbrowser module to
20
+ open the server's URL
21
+
22
+ Parameters
23
+ ----------
24
+ html: str
25
+ HTML string to display
26
+ using: str or iterable of str
27
+ Name of the web browser to open (e.g. "chrome", "firefox", etc.).
28
+ If an iterable, choose the first browser available on the system.
29
+ If none, choose the system default browser.
30
+ port: int
31
+ Port to use. Defaults to a random port
32
+ """
33
+ # Encode html to bytes
34
+ html_bytes = html.encode("utf8") if isinstance(html, str) else html
35
+
36
+ browser = None
37
+
38
+ if using is None:
39
+ browser = webbrowser.get(None)
40
+ else:
41
+ # normalize using to an iterable
42
+ if isinstance(using, str):
43
+ using = [using]
44
+
45
+ for browser_key in using:
46
+ try:
47
+ browser = webbrowser.get(browser_key)
48
+ if browser is not None:
49
+ break
50
+ except webbrowser.Error:
51
+ pass
52
+
53
+ if browser is None:
54
+ raise ValueError("Failed to locate a browser with name in " + str(using))
55
+
56
+ class OneShotRequestHandler(BaseHTTPRequestHandler):
57
+ def do_GET(self) -> None:
58
+ self.send_response(200)
59
+ self.send_header("Content-type", "text/html")
60
+ self.end_headers()
61
+
62
+ bufferSize = 1024 * 1024
63
+ for i in range(0, len(html_bytes), bufferSize):
64
+ self.wfile.write(html_bytes[i : i + bufferSize])
65
+
66
+ def log_message(self, format, *args):
67
+ # Silence stderr logging
68
+ pass
69
+
70
+ # Use specified port if provided, otherwise choose a random port (port value of 0)
71
+ server = HTTPServer(
72
+ ("127.0.0.1", port if port is not None else 0), OneShotRequestHandler
73
+ )
74
+ browser.open(f"http://127.0.0.1:{server.server_port}")
75
+ server.handle_request()
.venv/lib/python3.13/site-packages/altair/utils/_transformed_data.py ADDED
@@ -0,0 +1,591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any, overload
4
+
5
+ from altair import (
6
+ Chart,
7
+ ConcatChart,
8
+ ConcatSpecGenericSpec,
9
+ FacetChart,
10
+ FacetedUnitSpec,
11
+ FacetSpec,
12
+ HConcatChart,
13
+ HConcatSpecGenericSpec,
14
+ LayerChart,
15
+ LayerSpec,
16
+ NonNormalizedSpec,
17
+ TopLevelConcatSpec,
18
+ TopLevelFacetSpec,
19
+ TopLevelHConcatSpec,
20
+ TopLevelLayerSpec,
21
+ TopLevelUnitSpec,
22
+ TopLevelVConcatSpec,
23
+ UnitSpec,
24
+ UnitSpecWithFrame,
25
+ VConcatChart,
26
+ VConcatSpecGenericSpec,
27
+ data_transformers,
28
+ )
29
+ from altair.utils._vegafusion_data import get_inline_tables, import_vegafusion
30
+ from altair.utils.schemapi import Undefined
31
+
32
+ if TYPE_CHECKING:
33
+ import sys
34
+ from collections.abc import Iterable
35
+
36
+ if sys.version_info >= (3, 10):
37
+ from typing import TypeAlias
38
+ else:
39
+ from typing_extensions import TypeAlias
40
+
41
+ from altair.typing import ChartType
42
+ from altair.utils.core import DataFrameLike
43
+
44
+ Scope: TypeAlias = tuple[int, ...]
45
+ FacetMapping: TypeAlias = dict[tuple[str, Scope], tuple[str, Scope]]
46
+
47
+
48
+ # For the transformed_data functionality, the chart classes in the values
49
+ # can be considered equivalent to the chart class in the key.
50
+ _chart_class_mapping = {
51
+ Chart: (
52
+ Chart,
53
+ TopLevelUnitSpec,
54
+ FacetedUnitSpec,
55
+ UnitSpec,
56
+ UnitSpecWithFrame,
57
+ NonNormalizedSpec,
58
+ ),
59
+ LayerChart: (LayerChart, TopLevelLayerSpec, LayerSpec),
60
+ ConcatChart: (ConcatChart, TopLevelConcatSpec, ConcatSpecGenericSpec),
61
+ HConcatChart: (HConcatChart, TopLevelHConcatSpec, HConcatSpecGenericSpec),
62
+ VConcatChart: (VConcatChart, TopLevelVConcatSpec, VConcatSpecGenericSpec),
63
+ FacetChart: (FacetChart, TopLevelFacetSpec, FacetSpec),
64
+ }
65
+
66
+
67
+ @overload
68
+ def transformed_data(
69
+ chart: Chart | FacetChart,
70
+ row_limit: int | None = None,
71
+ exclude: Iterable[str] | None = None,
72
+ ) -> DataFrameLike | None: ...
73
+
74
+
75
+ @overload
76
+ def transformed_data(
77
+ chart: LayerChart | HConcatChart | VConcatChart | ConcatChart,
78
+ row_limit: int | None = None,
79
+ exclude: Iterable[str] | None = None,
80
+ ) -> list[DataFrameLike]: ...
81
+
82
+
83
+ def transformed_data(chart, row_limit=None, exclude=None):
84
+ """
85
+ Evaluate a Chart's transforms.
86
+
87
+ Evaluate the data transforms associated with a Chart and return the
88
+ transformed data as one or more DataFrames
89
+
90
+ Parameters
91
+ ----------
92
+ chart : Chart, FacetChart, LayerChart, HConcatChart, VConcatChart, or ConcatChart
93
+ Altair chart to evaluate transforms on
94
+ row_limit : int (optional)
95
+ Maximum number of rows to return for each DataFrame. None (default) for unlimited
96
+ exclude : iterable of str
97
+ Set of the names of charts to exclude
98
+
99
+ Returns
100
+ -------
101
+ DataFrame or list of DataFrames or None
102
+ If input chart is a Chart or Facet Chart, returns a DataFrame of the
103
+ transformed data. Otherwise, returns a list of DataFrames of the
104
+ transformed data
105
+ """
106
+ vf = import_vegafusion()
107
+ # Add mark if none is specified to satisfy Vega-Lite
108
+ if isinstance(chart, Chart) and chart.mark == Undefined:
109
+ chart = chart.mark_point()
110
+
111
+ # Deep copy chart so that we can rename marks without affecting caller
112
+ chart = chart.copy(deep=True)
113
+
114
+ # Ensure that all views are named so that we can look them up in the
115
+ # resulting Vega specification
116
+ chart_names = name_views(chart, 0, exclude=exclude)
117
+
118
+ # Compile to Vega and extract inline DataFrames
119
+ with data_transformers.enable("vegafusion"):
120
+ vega_spec = chart.to_dict(format="vega", context={"pre_transform": False})
121
+ inline_datasets = get_inline_tables(vega_spec)
122
+
123
+ # Build mapping from mark names to vega datasets
124
+ facet_mapping = get_facet_mapping(vega_spec)
125
+ dataset_mapping = get_datasets_for_view_names(vega_spec, chart_names, facet_mapping)
126
+
127
+ # Build a list of vega dataset names that corresponds to the order
128
+ # of the chart components
129
+ dataset_names = []
130
+ for chart_name in chart_names:
131
+ if chart_name in dataset_mapping:
132
+ dataset_names.append(dataset_mapping[chart_name])
133
+ else:
134
+ msg = "Failed to locate all datasets"
135
+ raise ValueError(msg)
136
+
137
+ # Extract transformed datasets with VegaFusion
138
+ datasets, _ = vf.runtime.pre_transform_datasets(
139
+ vega_spec,
140
+ dataset_names,
141
+ row_limit=row_limit,
142
+ inline_datasets=inline_datasets,
143
+ )
144
+
145
+ if isinstance(chart, (Chart, FacetChart)):
146
+ # Return DataFrame (or None if it was excluded) if input was a simple Chart
147
+ if not datasets:
148
+ return None
149
+ else:
150
+ return datasets[0]
151
+ else:
152
+ # Otherwise return the list of DataFrames
153
+ return datasets
154
+
155
+
156
+ # The equivalent classes from _chart_class_mapping should also be added
157
+ # to the type hints below for `chart` as the function would also work for them.
158
+ # However, this was not possible so far as mypy then complains about
159
+ # "Overloaded function signatures 1 and 2 overlap with incompatible return types [misc]"
160
+ # This might be due to the complex type hierarchy of the chart classes.
161
+ # See also https://github.com/python/mypy/issues/5119
162
+ # and https://github.com/python/mypy/issues/4020 which show that mypy might not have
163
+ # a very consistent behavior for overloaded functions.
164
+ # The same error appeared when trying it with Protocols for the concat and layer charts.
165
+ # This function is only used internally and so we accept this inconsistency for now.
166
+ def _assign_chart_name(chart: ChartType) -> None:
167
+ """Assign a name to a chart if it doesn't have one."""
168
+ if chart.name in {None, Undefined}:
169
+ # Use hash-based naming for Altair Chart objects
170
+ if hasattr(chart, "_get_view_hash_name"):
171
+ chart.name = chart._get_view_hash_name()
172
+ else:
173
+ # For Vega-Lite schema objects (UnitSpec, FacetedUnitSpec, etc.),
174
+ # use simple naming since these are already unique by design
175
+ chart_type = chart.__class__.__name__.lower()
176
+ # Clean up the type name for readability
177
+ chart_type = (
178
+ chart_type.replace("spec", "")
179
+ .replace("generic", "")
180
+ .replace("concat", "")
181
+ )
182
+ chart_type = chart_type.removesuffix("_")
183
+ # Use object ID for uniqueness - these objects are already unique
184
+ chart.name = f"view_{chart_type}_{id(chart):x}"
185
+
186
+
187
+ def _get_subcharts(chart: ChartType) -> list[Any]:
188
+ """Get the subcharts for a composite chart."""
189
+ if isinstance(chart, _chart_class_mapping[LayerChart]):
190
+ return chart.layer
191
+ elif isinstance(chart, _chart_class_mapping[HConcatChart]):
192
+ return chart.hconcat
193
+ elif isinstance(chart, _chart_class_mapping[VConcatChart]):
194
+ return chart.vconcat
195
+ elif isinstance(chart, _chart_class_mapping[ConcatChart]):
196
+ return chart.concat
197
+ else:
198
+ msg = (
199
+ "transformed_data accepts an instance of "
200
+ "Chart, FacetChart, LayerChart, HConcatChart, VConcatChart, or ConcatChart\n"
201
+ f"Received value of type: {type(chart)}"
202
+ )
203
+ raise ValueError(msg)
204
+
205
+
206
+ def name_views(
207
+ chart: ChartType, i: int = 0, exclude: Iterable[str] | None = None
208
+ ) -> list[str]:
209
+ """
210
+ Name unnamed chart views.
211
+
212
+ Name unnamed charts views so that we can look them up later in
213
+ the compiled Vega spec.
214
+
215
+ Note: This function mutates the input chart by applying names to
216
+ unnamed views.
217
+
218
+ Parameters
219
+ ----------
220
+ chart : Chart, FacetChart, LayerChart, HConcatChart, VConcatChart, or ConcatChart
221
+ Altair chart to apply names to
222
+ i : int (default 0)
223
+ Starting chart index
224
+ exclude : iterable of str
225
+ Names of charts to exclude
226
+
227
+ Returns
228
+ -------
229
+ list of str
230
+ List of the names of the charts and subcharts
231
+ """
232
+ exclude = set(exclude) if exclude is not None else set()
233
+
234
+ # Handle simple charts (Chart and FacetChart)
235
+ if isinstance(
236
+ chart, (_chart_class_mapping[Chart], _chart_class_mapping[FacetChart])
237
+ ):
238
+ if chart.name not in exclude:
239
+ _assign_chart_name(chart)
240
+ return [chart.name]
241
+ return []
242
+
243
+ # Handle composite charts
244
+ subcharts = _get_subcharts(chart)
245
+ chart_names: list[str] = []
246
+ for subchart in subcharts:
247
+ for name in name_views(subchart, i=i + len(chart_names), exclude=exclude):
248
+ chart_names.append(name)
249
+ return chart_names
250
+
251
+
252
+ def get_group_mark_for_scope(
253
+ vega_spec: dict[str, Any], scope: Scope
254
+ ) -> dict[str, Any] | None:
255
+ """
256
+ Get the group mark at a particular scope.
257
+
258
+ Parameters
259
+ ----------
260
+ vega_spec : dict
261
+ Top-level Vega specification dictionary
262
+ scope : tuple of int
263
+ Scope tuple. If empty, the original Vega specification is returned.
264
+ Otherwise, the nested group mark at the scope specified is returned.
265
+
266
+ Returns
267
+ -------
268
+ dict or None
269
+ Top-level Vega spec (if scope is empty)
270
+ or group mark (if scope is non-empty)
271
+ or None (if group mark at scope does not exist)
272
+
273
+ Examples
274
+ --------
275
+ >>> spec = {
276
+ ... "marks": [
277
+ ... {"type": "group", "marks": [{"type": "symbol"}]},
278
+ ... {"type": "group", "marks": [{"type": "rect"}]},
279
+ ... ]
280
+ ... }
281
+ >>> get_group_mark_for_scope(spec, (1,))
282
+ {'type': 'group', 'marks': [{'type': 'rect'}]}
283
+ """
284
+ group = vega_spec
285
+
286
+ # Find group at scope
287
+ for scope_value in scope:
288
+ group_index = 0
289
+ child_group = None
290
+ for mark in group.get("marks", []):
291
+ if mark.get("type") == "group":
292
+ if group_index == scope_value:
293
+ child_group = mark
294
+ break
295
+ group_index += 1
296
+ if child_group is None:
297
+ return None
298
+ group = child_group
299
+
300
+ return group
301
+
302
+
303
+ def get_datasets_for_scope(vega_spec: dict[str, Any], scope: Scope) -> list[str]:
304
+ """
305
+ Get the names of the datasets that are defined at a given scope.
306
+
307
+ Parameters
308
+ ----------
309
+ vega_spec : dict
310
+ Top-level Vega specification
311
+ scope : tuple of int
312
+ Scope tuple. If empty, the names of top-level datasets are returned
313
+ Otherwise, the names of the datasets defined in the nested group mark
314
+ at the specified scope are returned.
315
+
316
+ Returns
317
+ -------
318
+ list of str
319
+ List of the names of the datasets defined at the specified scope
320
+
321
+ Examples
322
+ --------
323
+ >>> spec = {
324
+ ... "data": [{"name": "data1"}],
325
+ ... "marks": [
326
+ ... {
327
+ ... "type": "group",
328
+ ... "data": [{"name": "data2"}],
329
+ ... "marks": [{"type": "symbol"}],
330
+ ... },
331
+ ... {
332
+ ... "type": "group",
333
+ ... "data": [
334
+ ... {"name": "data3"},
335
+ ... {"name": "data4"},
336
+ ... ],
337
+ ... "marks": [{"type": "rect"}],
338
+ ... },
339
+ ... ],
340
+ ... }
341
+
342
+ >>> get_datasets_for_scope(spec, ())
343
+ ['data1']
344
+
345
+ >>> get_datasets_for_scope(spec, (0,))
346
+ ['data2']
347
+
348
+ >>> get_datasets_for_scope(spec, (1,))
349
+ ['data3', 'data4']
350
+
351
+ Returns empty when no group mark exists at scope
352
+ >>> get_datasets_for_scope(spec, (1, 3))
353
+ []
354
+ """
355
+ group = get_group_mark_for_scope(vega_spec, scope) or {}
356
+
357
+ # get datasets from group
358
+ datasets = []
359
+ for dataset in group.get("data", []):
360
+ datasets.append(dataset["name"])
361
+
362
+ # Add facet dataset
363
+ facet_dataset = group.get("from", {}).get("facet", {}).get("name", None)
364
+ if facet_dataset:
365
+ datasets.append(facet_dataset)
366
+ return datasets
367
+
368
+
369
+ def get_definition_scope_for_data_reference(
370
+ vega_spec: dict[str, Any], data_name: str, usage_scope: Scope
371
+ ) -> Scope | None:
372
+ """
373
+ Return the scope that a dataset is defined at, for a given usage scope.
374
+
375
+ Parameters
376
+ ----------
377
+ vega_spec: dict
378
+ Top-level Vega specification
379
+ data_name: str
380
+ The name of a dataset reference
381
+ usage_scope: tuple of int
382
+ The scope that the dataset is referenced in
383
+
384
+ Returns
385
+ -------
386
+ tuple of int
387
+ The scope where the referenced dataset is defined,
388
+ or None if no such dataset is found
389
+
390
+ Examples
391
+ --------
392
+ >>> spec = {
393
+ ... "data": [{"name": "data1"}],
394
+ ... "marks": [
395
+ ... {
396
+ ... "type": "group",
397
+ ... "data": [{"name": "data2"}],
398
+ ... "marks": [
399
+ ... {
400
+ ... "type": "symbol",
401
+ ... "encode": {
402
+ ... "update": {
403
+ ... "x": {"field": "x", "data": "data1"},
404
+ ... "y": {"field": "y", "data": "data2"},
405
+ ... }
406
+ ... },
407
+ ... }
408
+ ... ],
409
+ ... }
410
+ ... ],
411
+ ... }
412
+
413
+ data1 is referenced at scope [0] and defined at scope []
414
+ >>> get_definition_scope_for_data_reference(spec, "data1", (0,))
415
+ ()
416
+
417
+ data2 is referenced at scope [0] and defined at scope [0]
418
+ >>> get_definition_scope_for_data_reference(spec, "data2", (0,))
419
+ (0,)
420
+
421
+ If data2 is not visible at scope [] (the top level),
422
+ because it's defined in scope [0]
423
+ >>> repr(get_definition_scope_for_data_reference(spec, "data2", ()))
424
+ 'None'
425
+ """
426
+ for i in reversed(range(len(usage_scope) + 1)):
427
+ scope = usage_scope[:i]
428
+ datasets = get_datasets_for_scope(vega_spec, scope)
429
+ if data_name in datasets:
430
+ return scope
431
+ return None
432
+
433
+
434
+ def get_facet_mapping(group: dict[str, Any], scope: Scope = ()) -> FacetMapping:
435
+ """
436
+ Create mapping from facet definitions to source datasets.
437
+
438
+ Parameters
439
+ ----------
440
+ group : dict
441
+ Top-level Vega spec or nested group mark
442
+ scope : tuple of int
443
+ Scope of the group dictionary within a top-level Vega spec
444
+
445
+ Returns
446
+ -------
447
+ dict
448
+ Dictionary from (facet_name, facet_scope) to (dataset_name, dataset_scope)
449
+
450
+ Examples
451
+ --------
452
+ >>> spec = {
453
+ ... "data": [{"name": "data1"}],
454
+ ... "marks": [
455
+ ... {
456
+ ... "type": "group",
457
+ ... "from": {
458
+ ... "facet": {
459
+ ... "name": "facet1",
460
+ ... "data": "data1",
461
+ ... "groupby": ["colA"],
462
+ ... }
463
+ ... },
464
+ ... }
465
+ ... ],
466
+ ... }
467
+ >>> get_facet_mapping(spec)
468
+ {('facet1', (0,)): ('data1', ())}
469
+ """
470
+ facet_mapping = {}
471
+ group_index = 0
472
+ mark_group = get_group_mark_for_scope(group, scope) or {}
473
+ for mark in mark_group.get("marks", []):
474
+ if mark.get("type", None) == "group":
475
+ # Get facet for this group
476
+ group_scope = (*scope, group_index)
477
+ facet = mark.get("from", {}).get("facet", None)
478
+ if facet is not None:
479
+ facet_name = facet.get("name", None)
480
+ facet_data = facet.get("data", None)
481
+ if facet_name is not None and facet_data is not None:
482
+ definition_scope = get_definition_scope_for_data_reference(
483
+ group, facet_data, scope
484
+ )
485
+ if definition_scope is not None:
486
+ facet_mapping[facet_name, group_scope] = (
487
+ facet_data,
488
+ definition_scope,
489
+ )
490
+
491
+ # Handle children recursively
492
+ child_mapping = get_facet_mapping(group, scope=group_scope)
493
+ facet_mapping.update(child_mapping)
494
+ group_index += 1
495
+
496
+ return facet_mapping
497
+
498
+
499
+ def get_from_facet_mapping(
500
+ scoped_dataset: tuple[str, Scope], facet_mapping: FacetMapping
501
+ ) -> tuple[str, Scope]:
502
+ """
503
+ Apply facet mapping to a scoped dataset.
504
+
505
+ Parameters
506
+ ----------
507
+ scoped_dataset : (str, tuple of int)
508
+ A dataset name and scope tuple
509
+ facet_mapping : dict from (str, tuple of int) to (str, tuple of int)
510
+ The facet mapping produced by get_facet_mapping
511
+
512
+ Returns
513
+ -------
514
+ (str, tuple of int)
515
+ Dataset name and scope tuple that has been mapped as many times as possible
516
+
517
+ Examples
518
+ --------
519
+ Facet mapping as produced by get_facet_mapping
520
+ >>> facet_mapping = {
521
+ ... ("facet1", (0,)): ("data1", ()),
522
+ ... ("facet2", (0, 1)): ("facet1", (0,)),
523
+ ... }
524
+ >>> get_from_facet_mapping(("facet2", (0, 1)), facet_mapping)
525
+ ('data1', ())
526
+ """
527
+ while scoped_dataset in facet_mapping:
528
+ scoped_dataset = facet_mapping[scoped_dataset]
529
+ return scoped_dataset
530
+
531
+
532
+ def get_datasets_for_view_names(
533
+ group: dict[str, Any],
534
+ vl_chart_names: list[str],
535
+ facet_mapping: FacetMapping,
536
+ scope: Scope = (),
537
+ ) -> dict[str, tuple[str, Scope]]:
538
+ """
539
+ Get the Vega datasets that correspond to the provided Altair view names.
540
+
541
+ Parameters
542
+ ----------
543
+ group : dict
544
+ Top-level Vega spec or nested group mark
545
+ vl_chart_names : list of str
546
+ List of the Vega-Lite
547
+ facet_mapping : dict from (str, tuple of int) to (str, tuple of int)
548
+ The facet mapping produced by get_facet_mapping
549
+ scope : tuple of int
550
+ Scope of the group dictionary within a top-level Vega spec
551
+
552
+ Returns
553
+ -------
554
+ dict from str to (str, tuple of int)
555
+ Dict from Altair view names to scoped datasets
556
+ """
557
+ datasets = {}
558
+ group_index = 0
559
+ mark_group = get_group_mark_for_scope(group, scope) or {}
560
+ for mark in mark_group.get("marks", []):
561
+ for vl_chart_name in vl_chart_names:
562
+ if mark.get("name", "") == f"{vl_chart_name}_cell":
563
+ data_name = mark.get("from", {}).get("facet", None).get("data", None)
564
+ scoped_data_name = (data_name, scope)
565
+ datasets[vl_chart_name] = get_from_facet_mapping(
566
+ scoped_data_name, facet_mapping
567
+ )
568
+ break
569
+
570
+ name = mark.get("name", "")
571
+ if mark.get("type", "") == "group":
572
+ group_data_names = get_datasets_for_view_names(
573
+ group, vl_chart_names, facet_mapping, scope=(*scope, group_index)
574
+ )
575
+ for k, v in group_data_names.items():
576
+ datasets.setdefault(k, v)
577
+ group_index += 1
578
+ else:
579
+ for vl_chart_name in vl_chart_names:
580
+ if name.startswith(vl_chart_name) and name.endswith("_marks"):
581
+ data_name = mark.get("from", {}).get("data", None)
582
+ scoped_data = get_definition_scope_for_data_reference(
583
+ group, data_name, scope
584
+ )
585
+ if scoped_data is not None:
586
+ datasets[vl_chart_name] = get_from_facet_mapping(
587
+ (data_name, scoped_data), facet_mapping
588
+ )
589
+ break
590
+
591
+ return datasets
.venv/lib/python3.13/site-packages/altair/utils/_vegafusion_data.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import uuid
4
+ from importlib.metadata import version as importlib_version
5
+ from typing import TYPE_CHECKING, Any, Final, TypedDict, Union, overload
6
+ from weakref import WeakValueDictionary
7
+
8
+ from narwhals.stable.v1.dependencies import is_into_dataframe
9
+ from packaging.version import Version
10
+
11
+ from altair.utils._importers import import_vegafusion
12
+ from altair.utils.core import DataFrameLike
13
+ from altair.utils.data import (
14
+ DataType,
15
+ MaxRowsError,
16
+ SupportsGeoInterface,
17
+ ToValuesReturnType,
18
+ )
19
+ from altair.vegalite.data import default_data_transformer
20
+
21
+ if TYPE_CHECKING:
22
+ import sys
23
+ from collections.abc import Callable, MutableMapping
24
+
25
+ from narwhals.stable.v1.typing import IntoDataFrame
26
+
27
+ from vegafusion.runtime import ChartState
28
+
29
+ if sys.version_info >= (3, 13):
30
+ from typing import TypeIs
31
+ else:
32
+ from typing_extensions import TypeIs
33
+
34
+ # Temporary storage for dataframes that have been extracted
35
+ # from charts by the vegafusion data transformer. Use a WeakValueDictionary
36
+ # rather than a dict so that the Python interpreter is free to garbage
37
+ # collect the stored DataFrames.
38
+ extracted_inline_tables: MutableMapping[str, DataFrameLike] = WeakValueDictionary()
39
+
40
+ # Special URL prefix that VegaFusion uses to denote that a
41
+ # dataset in a Vega spec corresponds to an entry in the `inline_datasets`
42
+ # kwarg of vf.runtime.pre_transform_spec().
43
+ VEGAFUSION_PREFIX: Final = "vegafusion+dataset://"
44
+
45
+
46
+ try:
47
+ VEGAFUSION_VERSION: Version | None = Version(importlib_version("vegafusion"))
48
+ except ImportError:
49
+ VEGAFUSION_VERSION = None
50
+
51
+
52
+ if VEGAFUSION_VERSION and Version("2.0.0a0") <= VEGAFUSION_VERSION:
53
+
54
+ def is_supported_by_vf(data: Any) -> TypeIs[DataFrameLike]:
55
+ # Test whether VegaFusion supports the data type
56
+ # VegaFusion v2 support narwhals-compatible DataFrames
57
+ return isinstance(data, DataFrameLike) or is_into_dataframe(data)
58
+
59
+ else:
60
+
61
+ def is_supported_by_vf(data: Any) -> TypeIs[DataFrameLike]:
62
+ return isinstance(data, DataFrameLike)
63
+
64
+
65
+ class _ToVegaFusionReturnUrlDict(TypedDict):
66
+ url: str
67
+
68
+
69
+ _VegaFusionReturnType = Union[_ToVegaFusionReturnUrlDict, ToValuesReturnType]
70
+
71
+
72
+ @overload
73
+ def vegafusion_data_transformer(
74
+ data: None = ..., max_rows: int = ...
75
+ ) -> Callable[..., Any]: ...
76
+
77
+
78
+ @overload
79
+ def vegafusion_data_transformer(
80
+ data: DataFrameLike, max_rows: int = ...
81
+ ) -> ToValuesReturnType: ...
82
+
83
+
84
+ @overload
85
+ def vegafusion_data_transformer(
86
+ data: dict | IntoDataFrame | SupportsGeoInterface, max_rows: int = ...
87
+ ) -> _VegaFusionReturnType: ...
88
+
89
+
90
+ def vegafusion_data_transformer(
91
+ data: DataType | None = None, max_rows: int = 100000
92
+ ) -> Callable[..., Any] | _VegaFusionReturnType:
93
+ """VegaFusion Data Transformer."""
94
+ if data is None:
95
+ return vegafusion_data_transformer
96
+
97
+ if is_supported_by_vf(data) and not isinstance(data, SupportsGeoInterface):
98
+ table_name = f"table_{uuid.uuid4()}".replace("-", "_")
99
+ extracted_inline_tables[table_name] = data
100
+ return {"url": VEGAFUSION_PREFIX + table_name}
101
+ else:
102
+ # Use default transformer for geo interface objects
103
+ # # (e.g. a geopandas GeoDataFrame)
104
+ # Or if we don't recognize data type
105
+ return default_data_transformer(data)
106
+
107
+
108
+ def get_inline_table_names(vega_spec: dict[str, Any]) -> set[str]:
109
+ """
110
+ Get a set of the inline datasets names in the provided Vega spec.
111
+
112
+ Inline datasets are encoded as URLs that start with the table://
113
+ prefix.
114
+
115
+ Parameters
116
+ ----------
117
+ vega_spec: dict
118
+ A Vega specification dict
119
+
120
+ Returns
121
+ -------
122
+ set of str
123
+ Set of the names of the inline datasets that are referenced
124
+ in the specification.
125
+
126
+ Examples
127
+ --------
128
+ >>> spec = {
129
+ ... "data": [
130
+ ... {"name": "foo", "url": "https://path/to/file.csv"},
131
+ ... {"name": "bar", "url": "vegafusion+dataset://inline_dataset_123"},
132
+ ... ]
133
+ ... }
134
+ >>> get_inline_table_names(spec)
135
+ {'inline_dataset_123'}
136
+ """
137
+ table_names = set()
138
+
139
+ # Process datasets
140
+ for data in vega_spec.get("data", []):
141
+ url = data.get("url", "")
142
+ if url.startswith(VEGAFUSION_PREFIX):
143
+ name = url[len(VEGAFUSION_PREFIX) :]
144
+ table_names.add(name)
145
+
146
+ # Recursively process child marks, which may have their own datasets
147
+ for mark in vega_spec.get("marks", []):
148
+ table_names.update(get_inline_table_names(mark))
149
+
150
+ return table_names
151
+
152
+
153
+ def get_inline_tables(vega_spec: dict[str, Any]) -> dict[str, DataFrameLike]:
154
+ """
155
+ Get the inline tables referenced by a Vega specification.
156
+
157
+ Note: This function should only be called on a Vega spec that corresponds
158
+ to a chart that was processed by the vegafusion_data_transformer.
159
+ Furthermore, this function may only be called once per spec because
160
+ the returned dataframes are deleted from internal storage.
161
+
162
+ Parameters
163
+ ----------
164
+ vega_spec: dict
165
+ A Vega specification dict
166
+
167
+ Returns
168
+ -------
169
+ dict from str to dataframe
170
+ dict from inline dataset name to dataframe object
171
+ """
172
+ inline_names = get_inline_table_names(vega_spec)
173
+ # exclude named dataset that was provided by the user,
174
+ # or dataframes that have been deleted.
175
+ table_names = inline_names.intersection(extracted_inline_tables)
176
+ return {k: extracted_inline_tables.pop(k) for k in table_names}
177
+
178
+
179
+ def compile_to_vegafusion_chart_state(
180
+ vegalite_spec: dict[str, Any], local_tz: str
181
+ ) -> ChartState:
182
+ """
183
+ Compile a Vega-Lite spec to a VegaFusion ChartState.
184
+
185
+ Note: This function should only be called on a Vega-Lite spec
186
+ that was generated with the "vegafusion" data transformer enabled.
187
+ In particular, this spec may contain references to extract datasets
188
+ using table:// prefixed URLs.
189
+
190
+ Parameters
191
+ ----------
192
+ vegalite_spec: dict
193
+ A Vega-Lite spec that was generated from an Altair chart with
194
+ the "vegafusion" data transformer enabled
195
+ local_tz: str
196
+ Local timezone name (e.g. 'America/New_York')
197
+
198
+ Returns
199
+ -------
200
+ ChartState
201
+ A VegaFusion ChartState object
202
+ """
203
+ # Local import to avoid circular ImportError
204
+ from altair import data_transformers, vegalite_compilers
205
+
206
+ vf = import_vegafusion()
207
+
208
+ # Compile Vega-Lite spec to Vega
209
+ compiler = vegalite_compilers.get()
210
+ if compiler is None:
211
+ msg = "No active vega-lite compiler plugin found"
212
+ raise ValueError(msg)
213
+
214
+ vega_spec = compiler(vegalite_spec)
215
+
216
+ # Retrieve dict of inline tables referenced by the spec
217
+ inline_tables = get_inline_tables(vega_spec)
218
+
219
+ # Pre-evaluate transforms in vega spec with vegafusion
220
+ row_limit = data_transformers.options.get("max_rows", None)
221
+
222
+ chart_state = vf.runtime.new_chart_state(
223
+ vega_spec,
224
+ local_tz=local_tz,
225
+ inline_datasets=inline_tables,
226
+ row_limit=row_limit,
227
+ )
228
+
229
+ # Check from row limit warning and convert to MaxRowsError
230
+ handle_row_limit_exceeded(row_limit, chart_state.get_warnings())
231
+
232
+ return chart_state
233
+
234
+
235
+ def compile_with_vegafusion(vegalite_spec: dict[str, Any]) -> dict[str, Any]:
236
+ """
237
+ Compile a Vega-Lite spec to Vega and pre-transform with VegaFusion.
238
+
239
+ Note: This function should only be called on a Vega-Lite spec
240
+ that was generated with the "vegafusion" data transformer enabled.
241
+ In particular, this spec may contain references to extract datasets
242
+ using table:// prefixed URLs.
243
+
244
+ Parameters
245
+ ----------
246
+ vegalite_spec: dict
247
+ A Vega-Lite spec that was generated from an Altair chart with
248
+ the "vegafusion" data transformer enabled
249
+
250
+ Returns
251
+ -------
252
+ dict
253
+ A Vega spec that has been pre-transformed by VegaFusion
254
+ """
255
+ # Local import to avoid circular ImportError
256
+ from altair import data_transformers, vegalite_compilers
257
+
258
+ vf = import_vegafusion()
259
+
260
+ # Compile Vega-Lite spec to Vega
261
+ compiler = vegalite_compilers.get()
262
+ if compiler is None:
263
+ msg = "No active vega-lite compiler plugin found"
264
+ raise ValueError(msg)
265
+
266
+ vega_spec = compiler(vegalite_spec)
267
+
268
+ # Retrieve dict of inline tables referenced by the spec
269
+ inline_tables = get_inline_tables(vega_spec)
270
+
271
+ # Pre-evaluate transforms in vega spec with vegafusion
272
+ row_limit = data_transformers.options.get("max_rows", None)
273
+ transformed_vega_spec, warnings = vf.runtime.pre_transform_spec(
274
+ vega_spec,
275
+ vf.get_local_tz(),
276
+ inline_datasets=inline_tables,
277
+ row_limit=row_limit,
278
+ )
279
+
280
+ # Check from row limit warning and convert to MaxRowsError
281
+ handle_row_limit_exceeded(row_limit, warnings)
282
+
283
+ return transformed_vega_spec
284
+
285
+
286
+ def handle_row_limit_exceeded(row_limit: int | None, warnings: list):
287
+ for warning in warnings:
288
+ if warning.get("type") == "RowLimitExceeded":
289
+ msg = (
290
+ "The number of dataset rows after filtering and aggregation exceeds\n"
291
+ f"the current limit of {row_limit}. Try adding an aggregation to reduce\n"
292
+ "the size of the dataset that must be loaded into the browser. Or, disable\n"
293
+ "the limit by calling alt.data_transformers.disable_max_rows(). Note that\n"
294
+ "disabling this limit may cause the browser to freeze or crash."
295
+ )
296
+ raise MaxRowsError(msg)
297
+
298
+
299
+ def using_vegafusion() -> bool:
300
+ """Check whether the vegafusion data transformer is enabled."""
301
+ # Local import to avoid circular ImportError
302
+ from altair import data_transformers
303
+
304
+ return data_transformers.active == "vegafusion"
.venv/lib/python3.13/site-packages/altair/utils/compiler.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ from typing import Any
3
+
4
+ from altair.utils import PluginRegistry
5
+
6
+ # ==============================================================================
7
+ # Vega-Lite to Vega compiler registry
8
+ # ==============================================================================
9
+ VegaLiteCompilerType = Callable[[dict[str, Any]], dict[str, Any]]
10
+
11
+
12
+ class VegaLiteCompilerRegistry(PluginRegistry[VegaLiteCompilerType, dict[str, Any]]):
13
+ pass
.venv/lib/python3.13/site-packages/altair/utils/core.py ADDED
@@ -0,0 +1,981 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility routines."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import itertools
6
+ import json
7
+ import re
8
+ import sys
9
+ import traceback
10
+ import warnings
11
+ from collections.abc import Callable, Iterator, Mapping, MutableMapping
12
+ from copy import deepcopy
13
+ from itertools import groupby
14
+ from operator import itemgetter
15
+ from typing import TYPE_CHECKING, Any, Literal, TypeVar, cast, overload
16
+
17
+ import jsonschema
18
+ import narwhals.stable.v1 as nw
19
+ from narwhals.stable.v1.dependencies import is_pandas_dataframe, is_polars_dataframe
20
+ from narwhals.stable.v1.typing import IntoDataFrame
21
+
22
+ from altair.utils.schemapi import SchemaBase, SchemaLike, Undefined
23
+
24
+ if sys.version_info >= (3, 12):
25
+ from typing import Protocol, TypeAliasType, runtime_checkable
26
+ else:
27
+ from typing_extensions import Protocol, TypeAliasType, runtime_checkable
28
+ if sys.version_info >= (3, 10):
29
+ from typing import Concatenate, ParamSpec
30
+ else:
31
+ from typing_extensions import Concatenate, ParamSpec
32
+
33
+
34
+ if TYPE_CHECKING:
35
+ import pandas as pd
36
+ from narwhals.stable.v1.typing import IntoExpr
37
+
38
+ from altair.utils._dfi_types import DataFrame as DfiDataFrame
39
+ from altair.vegalite.v6.schema._typing import StandardType_T as InferredVegaLiteType
40
+
41
+ _PandasDataFrameT = TypeVar("_PandasDataFrameT", bound="pd.DataFrame")
42
+
43
+ TIntoDataFrame = TypeVar("TIntoDataFrame", bound=IntoDataFrame)
44
+ T = TypeVar("T")
45
+ P = ParamSpec("P")
46
+ R = TypeVar("R")
47
+
48
+ WrapsFunc = TypeAliasType("WrapsFunc", Callable[..., R], type_params=(R,))
49
+ WrappedFunc = TypeAliasType("WrappedFunc", Callable[P, R], type_params=(P, R))
50
+ # NOTE: Requires stringized form to avoid `< (3, 11)` issues
51
+ # See: https://github.com/vega/altair/actions/runs/10667859416/job/29567290871?pr=3565
52
+ WrapsMethod = TypeAliasType(
53
+ "WrapsMethod", "Callable[Concatenate[T, ...], R]", type_params=(T, R)
54
+ )
55
+ WrappedMethod = TypeAliasType(
56
+ "WrappedMethod", Callable[Concatenate[T, P], R], type_params=(T, P, R)
57
+ )
58
+
59
+
60
+ @runtime_checkable
61
+ class DataFrameLike(Protocol):
62
+ def __dataframe__(
63
+ self, nan_as_null: bool = False, allow_copy: bool = True
64
+ ) -> DfiDataFrame: ...
65
+
66
+
67
+ TYPECODE_MAP = {
68
+ "ordinal": "O",
69
+ "nominal": "N",
70
+ "quantitative": "Q",
71
+ "temporal": "T",
72
+ "geojson": "G",
73
+ }
74
+
75
+ INV_TYPECODE_MAP = {v: k for k, v in TYPECODE_MAP.items()}
76
+
77
+
78
+ # aggregates from vega-lite version 4.6.0
79
+ AGGREGATES = [
80
+ "argmax",
81
+ "argmin",
82
+ "average",
83
+ "count",
84
+ "distinct",
85
+ "max",
86
+ "mean",
87
+ "median",
88
+ "min",
89
+ "missing",
90
+ "product",
91
+ "q1",
92
+ "q3",
93
+ "ci0",
94
+ "ci1",
95
+ "stderr",
96
+ "stdev",
97
+ "stdevp",
98
+ "sum",
99
+ "valid",
100
+ "values",
101
+ "variance",
102
+ "variancep",
103
+ "exponential",
104
+ "exponentialb",
105
+ ]
106
+
107
+ # window aggregates from vega-lite version 4.6.0
108
+ WINDOW_AGGREGATES = [
109
+ "row_number",
110
+ "rank",
111
+ "dense_rank",
112
+ "percent_rank",
113
+ "cume_dist",
114
+ "ntile",
115
+ "lag",
116
+ "lead",
117
+ "first_value",
118
+ "last_value",
119
+ "nth_value",
120
+ ]
121
+
122
+ # timeUnits from vega-lite version 4.17.0
123
+ TIMEUNITS = [
124
+ "year",
125
+ "quarter",
126
+ "month",
127
+ "week",
128
+ "day",
129
+ "dayofyear",
130
+ "date",
131
+ "hours",
132
+ "minutes",
133
+ "seconds",
134
+ "milliseconds",
135
+ "yearquarter",
136
+ "yearquartermonth",
137
+ "yearmonth",
138
+ "yearmonthdate",
139
+ "yearmonthdatehours",
140
+ "yearmonthdatehoursminutes",
141
+ "yearmonthdatehoursminutesseconds",
142
+ "yearweek",
143
+ "yearweekday",
144
+ "yearweekdayhours",
145
+ "yearweekdayhoursminutes",
146
+ "yearweekdayhoursminutesseconds",
147
+ "yeardayofyear",
148
+ "quartermonth",
149
+ "monthdate",
150
+ "monthdatehours",
151
+ "monthdatehoursminutes",
152
+ "monthdatehoursminutesseconds",
153
+ "weekday",
154
+ "weeksdayhours",
155
+ "weekdayhours",
156
+ "weekdayhoursminutes",
157
+ "weekdayhoursminutesseconds",
158
+ "dayhours",
159
+ "dayhoursminutes",
160
+ "dayhoursminutesseconds",
161
+ "hoursminutes",
162
+ "hoursminutesseconds",
163
+ "minutesseconds",
164
+ "secondsmilliseconds",
165
+ "utcyear",
166
+ "utcquarter",
167
+ "utcmonth",
168
+ "utcweek",
169
+ "utcday",
170
+ "utcdayofyear",
171
+ "utcdate",
172
+ "utchours",
173
+ "utcminutes",
174
+ "utcseconds",
175
+ "utcmilliseconds",
176
+ "utcyearquarter",
177
+ "utcyearquartermonth",
178
+ "utcyearmonth",
179
+ "utcyearmonthdate",
180
+ "utcyearmonthdatehours",
181
+ "utcyearmonthdatehoursminutes",
182
+ "utcyearmonthdatehoursminutesseconds",
183
+ "utcyearweek",
184
+ "utcyearweekday",
185
+ "utcyearweekdayhours",
186
+ "utcyearweekdayhoursminutes",
187
+ "utcyearweekdayhoursminutesseconds",
188
+ "utcyeardayofyear",
189
+ "utcquartermonth",
190
+ "utcmonthdate",
191
+ "utcmonthdatehours",
192
+ "utcmonthdatehoursminutes",
193
+ "utcmonthdatehoursminutesseconds",
194
+ "utcweekday",
195
+ "utcweekdayhours",
196
+ "utcweekdayhoursminutes",
197
+ "utcweekdayhoursminutesseconds",
198
+ "utcdayhours",
199
+ "utcdayhoursminutes",
200
+ "utcdayhoursminutesseconds",
201
+ "utchoursminutes",
202
+ "utchoursminutesseconds",
203
+ "utcminutesseconds",
204
+ "utcsecondsmilliseconds",
205
+ ]
206
+
207
+ VALID_TYPECODES = list(itertools.chain(iter(TYPECODE_MAP), iter(INV_TYPECODE_MAP)))
208
+
209
+ SHORTHAND_UNITS = {
210
+ "field": "(?P<field>.*)",
211
+ "type": "(?P<type>{})".format("|".join(VALID_TYPECODES)),
212
+ "agg_count": "(?P<aggregate>count)",
213
+ "op_count": "(?P<op>count)",
214
+ "aggregate": "(?P<aggregate>{})".format("|".join(AGGREGATES)),
215
+ "window_op": "(?P<op>{})".format("|".join(AGGREGATES + WINDOW_AGGREGATES)),
216
+ "timeUnit": "(?P<timeUnit>{})".format("|".join(TIMEUNITS)),
217
+ }
218
+
219
+ SHORTHAND_KEYS: frozenset[Literal["field", "aggregate", "type", "timeUnit"]] = (
220
+ frozenset(("field", "aggregate", "type", "timeUnit"))
221
+ )
222
+
223
+
224
+ def infer_vegalite_type_for_pandas(
225
+ data: Any,
226
+ ) -> InferredVegaLiteType | tuple[InferredVegaLiteType, list[Any]]:
227
+ """
228
+ From an array-like input, infer the correct vega typecode.
229
+
230
+ ('ordinal', 'nominal', 'quantitative', or 'temporal').
231
+
232
+ Parameters
233
+ ----------
234
+ data: Any
235
+ """
236
+ # This is safe to import here, as this function is only called on pandas input.
237
+ from pandas.api.types import infer_dtype
238
+
239
+ typ = infer_dtype(data, skipna=False)
240
+
241
+ if typ in {
242
+ "floating",
243
+ "mixed-integer-float",
244
+ "integer",
245
+ "mixed-integer",
246
+ "complex",
247
+ }:
248
+ return "quantitative"
249
+ elif typ == "categorical" and hasattr(data, "cat") and data.cat.ordered:
250
+ return ("ordinal", data.cat.categories.tolist())
251
+ elif typ in {"string", "bytes", "categorical", "boolean", "mixed", "unicode"}:
252
+ return "nominal"
253
+ elif typ in {
254
+ "datetime",
255
+ "datetime64",
256
+ "timedelta",
257
+ "timedelta64",
258
+ "date",
259
+ "time",
260
+ "period",
261
+ }:
262
+ return "temporal"
263
+ else:
264
+ warnings.warn(
265
+ f"I don't know how to infer vegalite type from '{typ}'. "
266
+ "Defaulting to nominal.",
267
+ stacklevel=1,
268
+ )
269
+ return "nominal"
270
+
271
+
272
+ def merge_props_geom(feat: dict[str, Any]) -> dict[str, Any]:
273
+ """
274
+ Merge properties with geometry.
275
+
276
+ * Overwrites 'type' and 'geometry' entries if existing.
277
+ """
278
+ geom = {k: feat[k] for k in ("type", "geometry")}
279
+ try:
280
+ feat["properties"].update(geom)
281
+ props_geom = feat["properties"]
282
+ except (AttributeError, KeyError):
283
+ # AttributeError when 'properties' equals None
284
+ # KeyError when 'properties' is non-existing
285
+ props_geom = geom
286
+
287
+ return props_geom
288
+
289
+
290
+ def sanitize_geo_interface(geo: MutableMapping[Any, Any]) -> dict[str, Any]:
291
+ """
292
+ Sanitize a geo_interface to prepare it for serialization.
293
+
294
+ * Make a copy
295
+ * Convert type array or _Array to list
296
+ * Convert tuples to lists (using json.loads/dumps)
297
+ * Merge properties with geometry
298
+ """
299
+ geo = deepcopy(geo)
300
+
301
+ # convert type _Array or array to list
302
+ for key in geo:
303
+ if str(type(geo[key]).__name__).startswith(("_Array", "array")):
304
+ geo[key] = geo[key].tolist()
305
+
306
+ # convert (nested) tuples to lists
307
+ geo_dct: dict = json.loads(json.dumps(geo))
308
+
309
+ # sanitize features
310
+ if geo_dct["type"] == "FeatureCollection":
311
+ geo_dct = geo_dct["features"]
312
+ if len(geo_dct) > 0:
313
+ for idx, feat in enumerate(geo_dct):
314
+ geo_dct[idx] = merge_props_geom(feat)
315
+ elif geo_dct["type"] == "Feature":
316
+ geo_dct = merge_props_geom(geo_dct)
317
+ else:
318
+ geo_dct = {"type": "Feature", "geometry": geo_dct}
319
+
320
+ return geo_dct
321
+
322
+
323
+ def numpy_is_subtype(dtype: Any, subtype: Any) -> bool:
324
+ # This is only called on `numpy` inputs, so it's safe to import it here.
325
+ import numpy as np
326
+
327
+ try:
328
+ return cast("bool", np.issubdtype(dtype, subtype))
329
+ except (NotImplementedError, TypeError):
330
+ return False
331
+
332
+
333
+ def sanitize_pandas_dataframe(df: _PandasDataFrameT) -> _PandasDataFrameT: # noqa: C901
334
+ """
335
+ Sanitize a DataFrame to prepare it for serialization.
336
+
337
+ * Make a copy
338
+ * Convert RangeIndex columns to strings
339
+ * Raise ValueError if column names are not strings
340
+ * Raise ValueError if it has a hierarchical index.
341
+ * Convert categoricals to strings.
342
+ * Convert np.bool_ dtypes to Python bool objects
343
+ * Convert np.int dtypes to Python int objects
344
+ * Convert floats to objects and replace NaNs/infs with None.
345
+ * Convert DateTime dtypes into appropriate string representations
346
+ * Convert Nullable integers to objects and replace NaN with None
347
+ * Convert Nullable boolean to objects and replace NaN with None
348
+ * convert dedicated string column to objects and replace NaN with None
349
+ * Raise a ValueError for TimeDelta dtypes
350
+ """
351
+ # This is safe to import here, as this function is only called on pandas input.
352
+ # NumPy is a required dependency of pandas so is also safe to import.
353
+ import numpy as np
354
+ import pandas as pd
355
+
356
+ df = cast("_PandasDataFrameT", df.copy())
357
+
358
+ if isinstance(df.columns, pd.RangeIndex):
359
+ df.columns = df.columns.astype(str)
360
+
361
+ for col_name in df.columns:
362
+ if not isinstance(col_name, str):
363
+ msg = (
364
+ f"Dataframe contains invalid column name: {col_name!r}. "
365
+ "Column names must be strings"
366
+ )
367
+ raise ValueError(msg)
368
+
369
+ if isinstance(df.index, pd.MultiIndex):
370
+ msg = "Hierarchical indices not supported"
371
+ raise ValueError(msg)
372
+ if isinstance(df.columns, pd.MultiIndex):
373
+ msg = "Hierarchical indices not supported"
374
+ raise ValueError(msg)
375
+
376
+ def to_list_if_array(val):
377
+ if isinstance(val, np.ndarray):
378
+ return val.tolist()
379
+ else:
380
+ return val
381
+
382
+ for dtype_item in df.dtypes.items():
383
+ # We know that the column names are strings from the isinstance check
384
+ # further above but mypy thinks it is of type Hashable and therefore does not
385
+ # let us assign it to the col_name variable which is already of type str.
386
+ col_name = cast("str", dtype_item[0])
387
+ dtype = dtype_item[1]
388
+ dtype_name = str(dtype)
389
+ if dtype_name == "category":
390
+ # Work around bug in to_json for categorical types in older versions
391
+ # of pandas as they do not properly convert NaN values to null in to_json.
392
+ # We can probably remove this part once we require pandas >= 1.0
393
+ col = df[col_name].astype(object)
394
+ df[col_name] = col.where(col.notnull(), None)
395
+ elif dtype_name == "string":
396
+ # dedicated string datatype (since 1.0)
397
+ # https://pandas.pydata.org/pandas-docs/version/1.0.0/whatsnew/v1.0.0.html#dedicated-string-data-type
398
+ col = df[col_name].astype(object)
399
+ df[col_name] = col.where(col.notnull(), None)
400
+ elif dtype_name == "bool":
401
+ # convert numpy bools to objects; np.bool is not JSON serializable
402
+ df[col_name] = df[col_name].astype(object)
403
+ elif dtype_name == "boolean":
404
+ # dedicated boolean datatype (since 1.0)
405
+ # https://pandas.io/docs/user_guide/boolean.html
406
+ col = df[col_name].astype(object)
407
+ df[col_name] = col.where(col.notnull(), None)
408
+ elif dtype_name.startswith(("datetime", "timestamp")):
409
+ # Convert datetimes to strings. This needs to be a full ISO string
410
+ # with time, which is why we cannot use ``col.astype(str)``.
411
+ # This is because Javascript parses date-only times in UTC, but
412
+ # parses full ISO-8601 dates as local time, and dates in Vega and
413
+ # Vega-Lite are displayed in local time by default.
414
+ # (see https://github.com/vega/altair/issues/1027)
415
+ df[col_name] = (
416
+ df[col_name].apply(lambda x: x.isoformat()).replace("NaT", "")
417
+ )
418
+ elif dtype_name.startswith("timedelta"):
419
+ msg = (
420
+ f'Field "{col_name}" has type "{dtype}" which is '
421
+ "not supported by Altair. Please convert to "
422
+ "either a timestamp or a numerical value."
423
+ ""
424
+ )
425
+ raise ValueError(msg)
426
+ elif dtype_name.startswith("geometry"):
427
+ # geopandas >=0.6.1 uses the dtype geometry. Continue here
428
+ # otherwise it will give an error on np.issubdtype(dtype, np.integer)
429
+ continue
430
+ elif (
431
+ dtype_name
432
+ in {
433
+ "Int8",
434
+ "Int16",
435
+ "Int32",
436
+ "Int64",
437
+ "UInt8",
438
+ "UInt16",
439
+ "UInt32",
440
+ "UInt64",
441
+ "Float32",
442
+ "Float64",
443
+ }
444
+ ): # nullable integer datatypes (since 24.0) and nullable float datatypes (since 1.2.0)
445
+ # https://pandas.pydata.org/pandas-docs/version/0.25/whatsnew/v0.24.0.html#optional-integer-na-support
446
+ col = df[col_name].astype(object)
447
+ df[col_name] = col.where(col.notnull(), None)
448
+ elif numpy_is_subtype(dtype, np.integer):
449
+ # convert integers to objects; np.int is not JSON serializable
450
+ df[col_name] = df[col_name].astype(object)
451
+ elif numpy_is_subtype(dtype, np.floating):
452
+ # For floats, convert to Python float: np.float is not JSON serializable
453
+ # Also convert NaN/inf values to null, as they are not JSON serializable
454
+ col = df[col_name]
455
+ bad_values = col.isnull() | np.isinf(col)
456
+ df[col_name] = col.astype(object).where(~bad_values, None)
457
+ elif dtype == object: # noqa: E721
458
+ # Convert numpy arrays saved as objects to lists
459
+ # Arrays are not JSON serializable
460
+ col = df[col_name].astype(object).apply(to_list_if_array)
461
+ df[col_name] = col.where(col.notnull(), None)
462
+ return df
463
+
464
+
465
+ def sanitize_narwhals_dataframe(
466
+ data: nw.DataFrame[TIntoDataFrame],
467
+ ) -> nw.DataFrame[TIntoDataFrame]:
468
+ """Sanitize narwhals.DataFrame for JSON serialization."""
469
+ schema = data.schema
470
+ columns: list[IntoExpr] = []
471
+ # See https://github.com/vega/altair/issues/1027 for why this is necessary.
472
+ local_iso_fmt_string = "%Y-%m-%dT%H:%M:%S"
473
+ is_polars = is_polars_dataframe(data.to_native())
474
+ for name, dtype in schema.items():
475
+ if dtype == nw.Date and is_polars:
476
+ # Polars doesn't allow formatting `Date` with time directives.
477
+ # The date -> datetime cast is extremely fast compared with `to_string`
478
+ columns.append(
479
+ nw.col(name).cast(nw.Datetime).dt.to_string(local_iso_fmt_string)
480
+ )
481
+ elif dtype == nw.Date:
482
+ columns.append(nw.col(name).dt.to_string(local_iso_fmt_string))
483
+ elif dtype == nw.Datetime:
484
+ columns.append(nw.col(name).dt.to_string(f"{local_iso_fmt_string}%.f"))
485
+ elif dtype == nw.Duration:
486
+ msg = (
487
+ f'Field "{name}" has type "{dtype}" which is '
488
+ "not supported by Altair. Please convert to "
489
+ "either a timestamp or a numerical value."
490
+ ""
491
+ )
492
+ raise ValueError(msg)
493
+ else:
494
+ columns.append(name)
495
+ return data.select(columns)
496
+
497
+
498
+ def to_eager_narwhals_dataframe(data: IntoDataFrame) -> nw.DataFrame[Any]:
499
+ """
500
+ Wrap `data` in `narwhals.DataFrame`.
501
+
502
+ If `data` is not supported by Narwhals, but it is convertible
503
+ to a PyArrow table, then first convert to a PyArrow Table,
504
+ and then wrap in `narwhals.DataFrame`.
505
+ """
506
+ data_nw = nw.from_native(data, eager_or_interchange_only=True)
507
+ if nw.get_level(data_nw) == "interchange":
508
+ # If Narwhals' support for `data`'s class is only metadata-level, then we
509
+ # use the interchange protocol to convert to a PyArrow Table.
510
+ from altair.utils.data import arrow_table_from_dfi_dataframe
511
+
512
+ pa_table = arrow_table_from_dfi_dataframe(data) # type: ignore[arg-type]
513
+ data_nw = nw.from_native(pa_table, eager_only=True)
514
+ return data_nw
515
+
516
+
517
+ def parse_shorthand( # noqa: C901
518
+ shorthand: dict[str, Any] | str,
519
+ data: IntoDataFrame | None = None,
520
+ parse_aggregates: bool = True,
521
+ parse_window_ops: bool = False,
522
+ parse_timeunits: bool = True,
523
+ parse_types: bool = True,
524
+ ) -> dict[str, Any]:
525
+ """
526
+ General tool to parse shorthand values.
527
+
528
+ These are of the form:
529
+
530
+ - "col_name"
531
+ - "col_name:O"
532
+ - "average(col_name)"
533
+ - "average(col_name):O"
534
+
535
+ Optionally, a dataframe may be supplied, from which the type
536
+ will be inferred if not specified in the shorthand.
537
+
538
+ Parameters
539
+ ----------
540
+ shorthand : dict or string
541
+ The shorthand representation to be parsed
542
+ data : DataFrame, optional
543
+ If specified and of type DataFrame, then use these values to infer the
544
+ column type if not provided by the shorthand.
545
+ parse_aggregates : boolean
546
+ If True (default), then parse aggregate functions within the shorthand.
547
+ parse_window_ops : boolean
548
+ If True then parse window operations within the shorthand (default:False)
549
+ parse_timeunits : boolean
550
+ If True (default), then parse timeUnits from within the shorthand
551
+ parse_types : boolean
552
+ If True (default), then parse typecodes within the shorthand
553
+
554
+ Returns
555
+ -------
556
+ attrs : dict
557
+ a dictionary of attributes extracted from the shorthand
558
+
559
+ Examples
560
+ --------
561
+ >>> import pandas as pd
562
+ >>> data = pd.DataFrame({"foo": ["A", "B", "A", "B"], "bar": [1, 2, 3, 4]})
563
+
564
+ >>> parse_shorthand("name") == {"field": "name"}
565
+ True
566
+
567
+ >>> parse_shorthand("name:Q") == {"field": "name", "type": "quantitative"}
568
+ True
569
+
570
+ >>> parse_shorthand("average(col)") == {"aggregate": "average", "field": "col"}
571
+ True
572
+
573
+ >>> parse_shorthand("foo:O") == {"field": "foo", "type": "ordinal"}
574
+ True
575
+
576
+ >>> parse_shorthand("min(foo):Q") == {
577
+ ... "aggregate": "min",
578
+ ... "field": "foo",
579
+ ... "type": "quantitative",
580
+ ... }
581
+ True
582
+
583
+ >>> parse_shorthand("month(col)") == {
584
+ ... "field": "col",
585
+ ... "timeUnit": "month",
586
+ ... "type": "temporal",
587
+ ... }
588
+ True
589
+
590
+ >>> parse_shorthand("year(col):O") == {
591
+ ... "field": "col",
592
+ ... "timeUnit": "year",
593
+ ... "type": "ordinal",
594
+ ... }
595
+ True
596
+
597
+ >>> parse_shorthand("foo", data) == {"field": "foo", "type": "nominal"}
598
+ True
599
+
600
+ >>> parse_shorthand("bar", data) == {"field": "bar", "type": "quantitative"}
601
+ True
602
+
603
+ >>> parse_shorthand("bar:O", data) == {"field": "bar", "type": "ordinal"}
604
+ True
605
+
606
+ >>> parse_shorthand("sum(bar)", data) == {
607
+ ... "aggregate": "sum",
608
+ ... "field": "bar",
609
+ ... "type": "quantitative",
610
+ ... }
611
+ True
612
+
613
+ >>> parse_shorthand("count()", data) == {
614
+ ... "aggregate": "count",
615
+ ... "type": "quantitative",
616
+ ... }
617
+ True
618
+ """
619
+ from altair.utils.data import is_data_type
620
+
621
+ if not shorthand:
622
+ return {}
623
+
624
+ patterns = []
625
+
626
+ if parse_aggregates:
627
+ patterns.extend([r"{agg_count}\(\)"])
628
+ patterns.extend([r"{aggregate}\({field}\)"])
629
+ if parse_window_ops:
630
+ patterns.extend([r"{op_count}\(\)"])
631
+ patterns.extend([r"{window_op}\({field}\)"])
632
+ if parse_timeunits:
633
+ patterns.extend([r"{timeUnit}\({field}\)"])
634
+
635
+ patterns.extend([r"{field}"])
636
+
637
+ if parse_types:
638
+ patterns = list(itertools.chain(*((p + ":{type}", p) for p in patterns)))
639
+
640
+ regexps = (
641
+ re.compile(r"\A" + p.format(**SHORTHAND_UNITS) + r"\Z", re.DOTALL)
642
+ for p in patterns
643
+ )
644
+
645
+ # find matches depending on valid fields passed
646
+ if isinstance(shorthand, dict):
647
+ attrs = shorthand
648
+ else:
649
+ attrs = next(
650
+ exp.match(shorthand).groupdict() # type: ignore[union-attr]
651
+ for exp in regexps
652
+ if exp.match(shorthand) is not None
653
+ )
654
+
655
+ # Handle short form of the type expression
656
+ if "type" in attrs:
657
+ attrs["type"] = INV_TYPECODE_MAP.get(attrs["type"], attrs["type"])
658
+
659
+ # counts are quantitative by default
660
+ if attrs == {"aggregate": "count"}:
661
+ attrs["type"] = "quantitative"
662
+
663
+ # times are temporal by default
664
+ if "timeUnit" in attrs and "type" not in attrs:
665
+ attrs["type"] = "temporal"
666
+
667
+ # if data is specified and type is not, infer type from data
668
+ if "type" not in attrs and is_data_type(data):
669
+ unescaped_field = attrs["field"].replace("\\", "")
670
+ data_nw = nw.from_native(data, eager_or_interchange_only=True)
671
+ schema = data_nw.schema
672
+ if unescaped_field in schema:
673
+ column = data_nw[unescaped_field]
674
+ if schema[unescaped_field] in {
675
+ nw.Object,
676
+ nw.Unknown,
677
+ } and is_pandas_dataframe(data_nw.to_native()):
678
+ attrs["type"] = infer_vegalite_type_for_pandas(column.to_native())
679
+ else:
680
+ attrs["type"] = infer_vegalite_type_for_narwhals(column)
681
+ if isinstance(attrs["type"], tuple):
682
+ attrs["sort"] = attrs["type"][1]
683
+ attrs["type"] = attrs["type"][0]
684
+
685
+ # If an unescaped colon is still present, it's often due to an incorrect data type specification
686
+ # but could also be due to using a column name with ":" in it.
687
+ if (
688
+ "field" in attrs
689
+ and ":" in attrs["field"]
690
+ and attrs["field"][attrs["field"].rfind(":") - 1] != "\\"
691
+ ):
692
+ raise ValueError(
693
+ '"{}" '.format(attrs["field"].split(":")[-1])
694
+ + "is not one of the valid encoding data types: {}.".format(
695
+ ", ".join(TYPECODE_MAP.values())
696
+ )
697
+ + "\nFor more details, see https://altair-viz.github.io/user_guide/encodings/index.html#encoding-data-types. "
698
+ + "If you are trying to use a column name that contains a colon, "
699
+ + 'prefix it with a backslash; for example "column\\:name" instead of "column:name".'
700
+ )
701
+ return attrs
702
+
703
+
704
+ def infer_vegalite_type_for_narwhals(
705
+ column: nw.Series,
706
+ ) -> InferredVegaLiteType | tuple[InferredVegaLiteType, list]:
707
+ dtype = column.dtype
708
+ if (
709
+ nw.is_ordered_categorical(column)
710
+ and not (categories := column.cat.get_categories()).is_empty()
711
+ ):
712
+ return "ordinal", categories.to_list()
713
+ if dtype == nw.String or dtype == nw.Categorical or dtype == nw.Boolean: # noqa: PLR1714
714
+ return "nominal"
715
+ elif dtype.is_numeric():
716
+ return "quantitative"
717
+ elif dtype == nw.Datetime or dtype == nw.Date: # noqa: PLR1714
718
+ # We use `== nw.Datetime` to check for any kind of Datetime, regardless of time
719
+ # unit and time zone. Prefer this over `dtype in {nw.Datetime, nw.Date}`,
720
+ # see https://narwhals-dev.github.io/narwhals/backcompat.
721
+ return "temporal"
722
+ else:
723
+ msg = f"Unexpected DtypeKind: {dtype}"
724
+ raise ValueError(msg)
725
+
726
+
727
+ def use_signature(tp: Callable[P, Any], /):
728
+ """
729
+ Use the signature and doc of ``tp`` for the decorated callable ``cb``.
730
+
731
+ - **Overload 1**: Decorating method
732
+ - **Overload 2**: Decorating function
733
+
734
+ Returns
735
+ -------
736
+ **Adding the annotation breaks typing**:
737
+
738
+ Overload[Callable[[WrapsMethod[T, R]], WrappedMethod[T, P, R]], Callable[[WrapsFunc[R]], WrappedFunc[P, R]]]
739
+ """
740
+
741
+ @overload
742
+ def decorate(cb: WrapsMethod[T, R], /) -> WrappedMethod[T, P, R]: ... # pyright: ignore[reportOverlappingOverload]
743
+
744
+ @overload
745
+ def decorate(cb: WrapsFunc[R], /) -> WrappedFunc[P, R]: ... # pyright: ignore[reportOverlappingOverload]
746
+
747
+ def decorate(cb: WrapsFunc[R], /) -> WrappedMethod[T, P, R] | WrappedFunc[P, R]:
748
+ """
749
+ Raises when no doc was found.
750
+
751
+ Notes
752
+ -----
753
+ - Reference to ``tp`` is stored in ``cb.__wrapped__``.
754
+ - The doc for ``cb`` will have a ``.rst`` link added, referring to ``tp``.
755
+ """
756
+ cb.__wrapped__ = getattr(tp, "__init__", tp) # type: ignore[attr-defined]
757
+
758
+ if doc_in := tp.__doc__:
759
+ line_1 = f"{cb.__doc__ or f'Refer to :class:`{tp.__name__}`'}\n"
760
+ cb.__doc__ = "".join((line_1, *doc_in.splitlines(keepends=True)[1:]))
761
+ return cb
762
+ else:
763
+ msg = f"Found no doc for {tp!r}"
764
+ raise AttributeError(msg)
765
+
766
+ return decorate
767
+
768
+
769
+ @overload
770
+ def update_nested(
771
+ original: MutableMapping[Any, Any],
772
+ update: Mapping[Any, Any],
773
+ copy: Literal[False] = ...,
774
+ ) -> MutableMapping[Any, Any]: ...
775
+ @overload
776
+ def update_nested(
777
+ original: Mapping[Any, Any],
778
+ update: Mapping[Any, Any],
779
+ copy: Literal[True],
780
+ ) -> MutableMapping[Any, Any]: ...
781
+ def update_nested(
782
+ original: Any,
783
+ update: Mapping[Any, Any],
784
+ copy: bool = False,
785
+ ) -> MutableMapping[Any, Any]:
786
+ """
787
+ Update nested dictionaries.
788
+
789
+ Parameters
790
+ ----------
791
+ original : MutableMapping
792
+ the original (nested) dictionary, which will be updated in-place
793
+ update : Mapping
794
+ the nested dictionary of updates
795
+ copy : bool, default False
796
+ if True, then copy the original dictionary rather than modifying it
797
+
798
+ Returns
799
+ -------
800
+ original : MutableMapping
801
+ a reference to the (modified) original dict
802
+
803
+ Examples
804
+ --------
805
+ >>> original = {"x": {"b": 2, "c": 4}}
806
+ >>> update = {"x": {"b": 5, "d": 6}, "y": 40}
807
+ >>> update_nested(original, update) # doctest: +SKIP
808
+ {'x': {'b': 5, 'c': 4, 'd': 6}, 'y': 40}
809
+ >>> original # doctest: +SKIP
810
+ {'x': {'b': 5, 'c': 4, 'd': 6}, 'y': 40}
811
+ """
812
+ if copy:
813
+ original = deepcopy(original)
814
+ for key, val in update.items():
815
+ if isinstance(val, Mapping):
816
+ orig_val = original.get(key, {})
817
+ if isinstance(orig_val, MutableMapping):
818
+ original[key] = update_nested(orig_val, val)
819
+ else:
820
+ original[key] = val
821
+ else:
822
+ original[key] = val
823
+ return original
824
+
825
+
826
+ def display_traceback(in_ipython: bool = True):
827
+ exc_info = sys.exc_info()
828
+
829
+ if in_ipython:
830
+ from IPython.core.getipython import get_ipython
831
+
832
+ ip = get_ipython()
833
+ else:
834
+ ip = None
835
+
836
+ if ip is not None:
837
+ ip.showtraceback(exc_info)
838
+ else:
839
+ traceback.print_exception(*exc_info)
840
+
841
+
842
+ _ChannelType = Literal["field", "datum", "value"]
843
+ _CHANNEL_CACHE: _ChannelCache
844
+ """Singleton `_ChannelCache` instance.
845
+
846
+ Initialized on first use.
847
+ """
848
+
849
+
850
+ class _ChannelCache:
851
+ channel_to_name: dict[type[SchemaBase], str]
852
+ name_to_channel: dict[str, dict[_ChannelType, type[SchemaBase]]]
853
+
854
+ @classmethod
855
+ def from_cache(cls) -> _ChannelCache:
856
+ global _CHANNEL_CACHE
857
+ try:
858
+ cached = _CHANNEL_CACHE
859
+ except NameError:
860
+ cached = cls.__new__(cls)
861
+ cached.channel_to_name = _init_channel_to_name() # pyright: ignore[reportAttributeAccessIssue]
862
+ cached.name_to_channel = _invert_group_channels(cached.channel_to_name)
863
+ _CHANNEL_CACHE = cached
864
+ return _CHANNEL_CACHE
865
+
866
+ def get_encoding(self, tp: type[Any], /) -> str:
867
+ if encoding := self.channel_to_name.get(tp):
868
+ return encoding
869
+ msg = f"positional of type {type(tp).__name__!r}"
870
+ raise NotImplementedError(msg)
871
+
872
+ def _wrap_in_channel(self, obj: Any, encoding: str, /):
873
+ if isinstance(obj, SchemaBase):
874
+ return obj
875
+ elif isinstance(obj, str):
876
+ obj = {"shorthand": obj}
877
+ elif isinstance(obj, (list, tuple)):
878
+ return [self._wrap_in_channel(el, encoding) for el in obj]
879
+ elif isinstance(obj, SchemaLike):
880
+ obj = obj.to_dict()
881
+ if channel := self.name_to_channel.get(encoding):
882
+ tp = channel["value" if "value" in obj else "field"]
883
+ try:
884
+ # Don't force validation here; some objects won't be valid until
885
+ # they're created in the context of a chart.
886
+ return tp.from_dict(obj, validate=False)
887
+ except jsonschema.ValidationError:
888
+ # our attempts at finding the correct class have failed
889
+ return obj
890
+ else:
891
+ warnings.warn(f"Unrecognized encoding channel {encoding!r}", stacklevel=1)
892
+ return obj
893
+
894
+ def infer_encoding_types(self, kwargs: dict[str, Any], /):
895
+ return {
896
+ encoding: self._wrap_in_channel(obj, encoding)
897
+ for encoding, obj in kwargs.items()
898
+ if obj is not Undefined
899
+ }
900
+
901
+
902
+ def _init_channel_to_name():
903
+ """
904
+ Construct a dictionary of channel type to encoding name.
905
+
906
+ Note
907
+ ----
908
+ The return type is not expressible using annotations, but is used
909
+ internally by `mypy`/`pyright` and avoids the need for type ignores.
910
+
911
+ Returns
912
+ -------
913
+ mapping: dict[type[`<subclass of FieldChannelMixin and SchemaBase>`] | type[`<subclass of ValueChannelMixin and SchemaBase>`] | type[`<subclass of DatumChannelMixin and SchemaBase>`], str]
914
+ """
915
+ from altair.vegalite.v6.schema import channels as ch
916
+
917
+ mixins = ch.FieldChannelMixin, ch.ValueChannelMixin, ch.DatumChannelMixin
918
+
919
+ return {
920
+ c: c._encoding_name
921
+ for c in ch.__dict__.values()
922
+ if isinstance(c, type) and issubclass(c, mixins) and issubclass(c, SchemaBase)
923
+ }
924
+
925
+
926
+ def _invert_group_channels(
927
+ m: dict[type[SchemaBase], str], /
928
+ ) -> dict[str, dict[_ChannelType, type[SchemaBase]]]:
929
+ """Grouped inverted index for `_ChannelCache.channel_to_name`."""
930
+
931
+ def _reduce(it: Iterator[tuple[type[Any], str]]) -> Any:
932
+ """
933
+ Returns a 1-2 item dict, per channel.
934
+
935
+ Never includes `datum`, as it is never utilized in `wrap_in_channel`.
936
+ """
937
+ item: dict[Any, type[SchemaBase]] = {}
938
+ for tp, _ in it:
939
+ name = tp.__name__
940
+ if name.endswith("Datum"):
941
+ continue
942
+ elif name.endswith("Value"):
943
+ sub_key = "value"
944
+ else:
945
+ sub_key = "field"
946
+ item[sub_key] = tp
947
+ return item
948
+
949
+ grouper = groupby(m.items(), itemgetter(1))
950
+ return {k: _reduce(chans) for k, chans in grouper}
951
+
952
+
953
+ def infer_encoding_types(args: tuple[Any, ...], kwargs: dict[str, Any]):
954
+ """
955
+ Infer typed keyword arguments for args and kwargs.
956
+
957
+ Parameters
958
+ ----------
959
+ args : Sequence
960
+ Sequence of function args
961
+ kwargs : MutableMapping
962
+ Dict of function kwargs
963
+
964
+ Returns
965
+ -------
966
+ kwargs : dict
967
+ All args and kwargs in a single dict, with keys and types
968
+ based on the channels mapping.
969
+ """
970
+ cache = _ChannelCache.from_cache()
971
+ # First use the mapping to convert args to kwargs based on their types.
972
+ for arg in args:
973
+ el = next(iter(arg), None) if isinstance(arg, (list, tuple)) else arg
974
+ encoding = cache.get_encoding(type(el))
975
+ if encoding not in kwargs:
976
+ kwargs[encoding] = arg
977
+ else:
978
+ msg = f"encoding {encoding!r} specified twice."
979
+ raise ValueError(msg)
980
+
981
+ return cache.infer_encoding_types(kwargs)
.venv/lib/python3.13/site-packages/altair/utils/data.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import random
6
+ import sys
7
+ from collections.abc import Callable, MutableMapping, Sequence
8
+ from functools import partial
9
+ from pathlib import Path
10
+ from typing import TYPE_CHECKING, Any, Literal, TypedDict, TypeVar, Union, overload
11
+
12
+ import narwhals.stable.v1 as nw
13
+ from narwhals.stable.v1.dependencies import is_pandas_dataframe
14
+ from narwhals.stable.v1.typing import IntoDataFrame
15
+
16
+ from ._importers import import_pyarrow_interchange
17
+ from .core import (
18
+ DataFrameLike,
19
+ sanitize_geo_interface,
20
+ sanitize_narwhals_dataframe,
21
+ sanitize_pandas_dataframe,
22
+ to_eager_narwhals_dataframe,
23
+ )
24
+ from .plugin_registry import PluginRegistry
25
+
26
+ if sys.version_info >= (3, 13):
27
+ from typing import Protocol, runtime_checkable
28
+ else:
29
+ from typing_extensions import Protocol, runtime_checkable
30
+ if sys.version_info >= (3, 10):
31
+ from typing import Concatenate, ParamSpec
32
+ else:
33
+ from typing_extensions import Concatenate, ParamSpec
34
+
35
+ if TYPE_CHECKING:
36
+ if sys.version_info >= (3, 13):
37
+ from typing import TypeIs
38
+ else:
39
+ from typing_extensions import TypeIs
40
+
41
+ if sys.version_info >= (3, 10):
42
+ from typing import TypeAlias
43
+ else:
44
+ from typing_extensions import TypeAlias
45
+ import pandas as pd
46
+ import pyarrow as pa
47
+
48
+
49
+ @runtime_checkable
50
+ class SupportsGeoInterface(Protocol):
51
+ __geo_interface__: MutableMapping
52
+
53
+
54
+ DataType: TypeAlias = Union[
55
+ dict[Any, Any], IntoDataFrame, SupportsGeoInterface, DataFrameLike
56
+ ]
57
+
58
+ TDataType = TypeVar("TDataType", bound=DataType)
59
+ TIntoDataFrame = TypeVar("TIntoDataFrame", bound=IntoDataFrame)
60
+
61
+ VegaLiteDataDict: TypeAlias = dict[
62
+ str, Union[str, dict[Any, Any], list[dict[Any, Any]]]
63
+ ]
64
+ ToValuesReturnType: TypeAlias = dict[str, Union[dict[Any, Any], list[dict[Any, Any]]]]
65
+ SampleReturnType = Union[IntoDataFrame, dict[str, Sequence], None]
66
+
67
+
68
+ def is_data_type(obj: Any) -> TypeIs[DataType]:
69
+ return isinstance(obj, (dict, SupportsGeoInterface)) or isinstance(
70
+ nw.from_native(obj, eager_or_interchange_only=True, pass_through=True),
71
+ nw.DataFrame,
72
+ )
73
+
74
+
75
+ # ==============================================================================
76
+ # Data transformer registry
77
+ #
78
+ # A data transformer is a callable that takes a supported data type and returns
79
+ # a transformed dictionary version of it which is compatible with the VegaLite schema.
80
+ # The dict objects will be the Data portion of the VegaLite schema.
81
+ #
82
+ # Renderers only deal with the dict form of a
83
+ # VegaLite spec, after the Data model has been put into a schema compliant
84
+ # form.
85
+ # ==============================================================================
86
+
87
+ P = ParamSpec("P")
88
+ # NOTE: `Any` required due to the complexity of existing signatures imported in `altair.vegalite.v6.data.py`
89
+ R = TypeVar("R", VegaLiteDataDict, Any)
90
+ DataTransformerType = Callable[Concatenate[DataType, P], R]
91
+
92
+
93
+ class DataTransformerRegistry(PluginRegistry[DataTransformerType, R]):
94
+ _global_settings = {"consolidate_datasets": True}
95
+
96
+ @property
97
+ def consolidate_datasets(self) -> bool:
98
+ return self._global_settings["consolidate_datasets"]
99
+
100
+ @consolidate_datasets.setter
101
+ def consolidate_datasets(self, value: bool) -> None:
102
+ self._global_settings["consolidate_datasets"] = value
103
+
104
+
105
+ # ==============================================================================
106
+ class MaxRowsError(Exception):
107
+ """Raised when a data model has too many rows."""
108
+
109
+ def __init__(self, message: str, /) -> None:
110
+ self.message = message
111
+ super().__init__(self.message)
112
+
113
+ @classmethod
114
+ def from_limit_rows(cls, user_rows: int, max_rows: int, /) -> MaxRowsError:
115
+ msg = (
116
+ f"The number of rows in your dataset ({user_rows}) is greater "
117
+ f"than the maximum allowed ({max_rows}).\n\n"
118
+ "Try enabling the VegaFusion data transformer which "
119
+ "raises this limit by pre-evaluating data\n"
120
+ "transformations in Python.\n"
121
+ " >> import altair as alt\n"
122
+ ' >> alt.data_transformers.enable("vegafusion")\n\n'
123
+ "Or, see https://altair-viz.github.io/user_guide/large_datasets.html "
124
+ "for additional information\n"
125
+ "on how to plot large datasets."
126
+ )
127
+ return cls(msg)
128
+
129
+
130
+ @overload
131
+ def limit_rows(data: None = ..., max_rows: int | None = ...) -> partial: ...
132
+ @overload
133
+ def limit_rows(data: DataType, max_rows: int | None = ...) -> DataType: ...
134
+ def limit_rows(
135
+ data: DataType | None = None, max_rows: int | None = 5000
136
+ ) -> partial | DataType:
137
+ """
138
+ Raise MaxRowsError if the data model has more than max_rows.
139
+
140
+ If max_rows is None, then do not perform any check.
141
+ """
142
+ if data is None:
143
+ return partial(limit_rows, max_rows=max_rows)
144
+ check_data_type(data)
145
+
146
+ if isinstance(data, SupportsGeoInterface):
147
+ if data.__geo_interface__["type"] == "FeatureCollection":
148
+ values = data.__geo_interface__["features"]
149
+ else:
150
+ values = data.__geo_interface__
151
+ elif isinstance(data, dict):
152
+ if "values" in data:
153
+ values = data["values"]
154
+ else:
155
+ return data
156
+ else:
157
+ data = to_eager_narwhals_dataframe(data)
158
+ values = data
159
+
160
+ n = len(values)
161
+ if max_rows is not None and n > max_rows:
162
+ raise MaxRowsError.from_limit_rows(n, max_rows)
163
+
164
+ return data
165
+
166
+
167
+ @overload
168
+ def sample(
169
+ data: None = ..., n: int | None = ..., frac: float | None = ...
170
+ ) -> partial: ...
171
+ @overload
172
+ def sample(
173
+ data: TIntoDataFrame, n: int | None = ..., frac: float | None = ...
174
+ ) -> TIntoDataFrame: ...
175
+ @overload
176
+ def sample(
177
+ data: DataType, n: int | None = ..., frac: float | None = ...
178
+ ) -> SampleReturnType: ...
179
+ def sample(
180
+ data: DataType | None = None,
181
+ n: int | None = None,
182
+ frac: float | None = None,
183
+ ) -> partial | SampleReturnType:
184
+ """Reduce the size of the data model by sampling without replacement."""
185
+ if data is None:
186
+ return partial(sample, n=n, frac=frac)
187
+ check_data_type(data)
188
+ if is_pandas_dataframe(data):
189
+ return data.sample(n=n, frac=frac)
190
+ elif isinstance(data, dict):
191
+ if "values" in data:
192
+ values = data["values"]
193
+ if not n:
194
+ if frac is None:
195
+ msg = "frac cannot be None if n is None and data is a dictionary"
196
+ raise ValueError(msg)
197
+ n = int(frac * len(values))
198
+ values = random.sample(values, n)
199
+ return {"values": values}
200
+ else:
201
+ # Maybe this should raise an error or return something useful?
202
+ return None
203
+ data = nw.from_native(data, eager_only=True)
204
+ if not n:
205
+ if frac is None:
206
+ msg = "frac cannot be None if n is None with this data input type"
207
+ raise ValueError(msg)
208
+ n = int(frac * len(data))
209
+ indices = random.sample(range(len(data)), n)
210
+ return data[indices].to_native()
211
+
212
+
213
+ _FormatType = Literal["csv", "json"]
214
+
215
+
216
+ class _FormatDict(TypedDict):
217
+ type: _FormatType
218
+
219
+
220
+ class _ToFormatReturnUrlDict(TypedDict):
221
+ url: str
222
+ format: _FormatDict
223
+
224
+
225
+ @overload
226
+ def to_json(
227
+ data: None = ...,
228
+ prefix: str = ...,
229
+ extension: str = ...,
230
+ filename: str = ...,
231
+ urlpath: str = ...,
232
+ ) -> partial: ...
233
+
234
+
235
+ @overload
236
+ def to_json(
237
+ data: DataType,
238
+ prefix: str = ...,
239
+ extension: str = ...,
240
+ filename: str = ...,
241
+ urlpath: str = ...,
242
+ ) -> _ToFormatReturnUrlDict: ...
243
+
244
+
245
+ def to_json(
246
+ data: DataType | None = None,
247
+ prefix: str = "altair-data",
248
+ extension: str = "json",
249
+ filename: str = "{prefix}-{hash}.{extension}",
250
+ urlpath: str = "",
251
+ ) -> partial | _ToFormatReturnUrlDict:
252
+ """Write the data model to a .json file and return a url based data model."""
253
+ kwds = _to_text_kwds(prefix, extension, filename, urlpath)
254
+ if data is None:
255
+ return partial(to_json, **kwds)
256
+ else:
257
+ data_str = _data_to_json_string(data)
258
+ return _to_text(data_str, **kwds, format=_FormatDict(type="json"))
259
+
260
+
261
+ @overload
262
+ def to_csv(
263
+ data: None = ...,
264
+ prefix: str = ...,
265
+ extension: str = ...,
266
+ filename: str = ...,
267
+ urlpath: str = ...,
268
+ ) -> partial: ...
269
+
270
+
271
+ @overload
272
+ def to_csv(
273
+ data: dict | pd.DataFrame | DataFrameLike,
274
+ prefix: str = ...,
275
+ extension: str = ...,
276
+ filename: str = ...,
277
+ urlpath: str = ...,
278
+ ) -> _ToFormatReturnUrlDict: ...
279
+
280
+
281
+ def to_csv(
282
+ data: dict | pd.DataFrame | DataFrameLike | None = None,
283
+ prefix: str = "altair-data",
284
+ extension: str = "csv",
285
+ filename: str = "{prefix}-{hash}.{extension}",
286
+ urlpath: str = "",
287
+ ) -> partial | _ToFormatReturnUrlDict:
288
+ """Write the data model to a .csv file and return a url based data model."""
289
+ kwds = _to_text_kwds(prefix, extension, filename, urlpath)
290
+ if data is None:
291
+ return partial(to_csv, **kwds)
292
+ else:
293
+ data_str = _data_to_csv_string(data)
294
+ return _to_text(data_str, **kwds, format=_FormatDict(type="csv"))
295
+
296
+
297
+ def _to_text(
298
+ data: str,
299
+ prefix: str,
300
+ extension: str,
301
+ filename: str,
302
+ urlpath: str,
303
+ format: _FormatDict,
304
+ ) -> _ToFormatReturnUrlDict:
305
+ data_hash = _compute_data_hash(data)
306
+ filename = filename.format(prefix=prefix, hash=data_hash, extension=extension)
307
+ Path(filename).write_text(data, encoding="utf-8")
308
+ url = str(Path(urlpath, filename))
309
+ return _ToFormatReturnUrlDict({"url": url, "format": format})
310
+
311
+
312
+ def _to_text_kwds(prefix: str, extension: str, filename: str, urlpath: str, /) -> dict[str, str]: # fmt: skip
313
+ return {"prefix": prefix, "extension": extension, "filename": filename, "urlpath": urlpath} # fmt: skip
314
+
315
+
316
+ def to_values(data: DataType) -> ToValuesReturnType:
317
+ """Replace a DataFrame by a data model with values."""
318
+ check_data_type(data)
319
+ # `pass_through=True` passes `data` through as-is if it is not a Narwhals object.
320
+ data_native = nw.to_native(data, pass_through=True)
321
+ if isinstance(data_native, SupportsGeoInterface):
322
+ return {"values": _from_geo_interface(data_native)}
323
+ elif is_pandas_dataframe(data_native):
324
+ data_native = sanitize_pandas_dataframe(data_native)
325
+ return {"values": data_native.to_dict(orient="records")}
326
+ elif isinstance(data_native, dict):
327
+ if "values" not in data_native:
328
+ msg = "values expected in data dict, but not present."
329
+ raise KeyError(msg)
330
+ return data_native
331
+ elif isinstance(data, nw.DataFrame):
332
+ data = sanitize_narwhals_dataframe(data)
333
+ return {"values": data.rows(named=True)}
334
+ else:
335
+ # Should never reach this state as tested by check_data_type
336
+ msg = f"Unrecognized data type: {type(data)}"
337
+ raise ValueError(msg)
338
+
339
+
340
+ def check_data_type(data: DataType) -> None:
341
+ if not is_data_type(data):
342
+ msg = f"Expected dict, DataFrame or a __geo_interface__ attribute, got: {type(data)}"
343
+ raise TypeError(msg)
344
+
345
+
346
+ # ==============================================================================
347
+ # Private utilities
348
+ # ==============================================================================
349
+ def _compute_data_hash(data_str: str) -> str:
350
+ return hashlib.sha256(data_str.encode()).hexdigest()[:32]
351
+
352
+
353
+ def _from_geo_interface(data: SupportsGeoInterface) -> dict[str, Any]:
354
+ """
355
+ Sanitize a ``__geo_interface__`` w/ pre-sanitize step for ``pandas`` if needed.
356
+
357
+ Introduces an intersection type::
358
+
359
+ geo: <subclass of SupportsGeoInterface and DataFrame> | SupportsGeoInterface
360
+ """
361
+ geo = sanitize_pandas_dataframe(data) if is_pandas_dataframe(data) else data
362
+ return sanitize_geo_interface(geo.__geo_interface__)
363
+
364
+
365
+ def _data_to_json_string(data: DataType) -> str:
366
+ """Return a JSON string representation of the input data."""
367
+ check_data_type(data)
368
+ if isinstance(data, SupportsGeoInterface):
369
+ return json.dumps(_from_geo_interface(data))
370
+ elif is_pandas_dataframe(data):
371
+ data = sanitize_pandas_dataframe(data)
372
+ return data.to_json(orient="records", double_precision=15)
373
+ elif isinstance(data, dict):
374
+ if "values" not in data:
375
+ msg = "values expected in data dict, but not present."
376
+ raise KeyError(msg)
377
+ return json.dumps(data["values"], sort_keys=True)
378
+ try:
379
+ data_nw = nw.from_native(data, eager_only=True)
380
+ except TypeError as exc:
381
+ msg = "to_json only works with data expressed as a DataFrame or as a dict"
382
+ raise NotImplementedError(msg) from exc
383
+ data_nw = sanitize_narwhals_dataframe(data_nw)
384
+ return json.dumps(data_nw.rows(named=True))
385
+
386
+
387
+ def _data_to_csv_string(data: DataType) -> str:
388
+ """Return a CSV string representation of the input data."""
389
+ check_data_type(data)
390
+ if isinstance(data, SupportsGeoInterface):
391
+ msg = (
392
+ f"to_csv does not yet work with data that "
393
+ f"is of type {type(SupportsGeoInterface).__name__!r}.\n"
394
+ f"See https://github.com/vega/altair/issues/3441"
395
+ )
396
+ raise NotImplementedError(msg)
397
+ elif is_pandas_dataframe(data):
398
+ data = sanitize_pandas_dataframe(data)
399
+ return data.to_csv(index=False)
400
+ elif isinstance(data, dict):
401
+ if "values" not in data:
402
+ msg = "values expected in data dict, but not present"
403
+ raise KeyError(msg)
404
+ try:
405
+ import pandas as pd
406
+ except ImportError as exc:
407
+ msg = "pandas is required to convert a dict to a CSV string"
408
+ raise ImportError(msg) from exc
409
+ return pd.DataFrame.from_dict(data["values"]).to_csv(index=False)
410
+ try:
411
+ data_nw = nw.from_native(data, eager_only=True)
412
+ except TypeError as exc:
413
+ msg = "to_csv only works with data expressed as a DataFrame or as a dict"
414
+ raise NotImplementedError(msg) from exc
415
+ return data_nw.write_csv()
416
+
417
+
418
+ def arrow_table_from_dfi_dataframe(dfi_df: DataFrameLike) -> pa.Table:
419
+ """Convert a DataFrame Interchange Protocol compatible object to an Arrow Table."""
420
+ import pyarrow as pa
421
+
422
+ # First check if the dataframe object has a method to convert to arrow.
423
+ # Give this preference over the pyarrow from_dataframe function since the object
424
+ # has more control over the conversion, and may have broader compatibility.
425
+ # This is the case for Polars, which supports Date32 columns in direct conversion
426
+ # while pyarrow does not yet support this type in from_dataframe
427
+ for convert_method_name in ("arrow", "to_arrow", "to_arrow_table", "to_pyarrow"):
428
+ convert_method = getattr(dfi_df, convert_method_name, None)
429
+ if callable(convert_method):
430
+ result = convert_method()
431
+ if isinstance(result, pa.Table):
432
+ return result
433
+
434
+ pi = import_pyarrow_interchange()
435
+ return pi.from_dataframe(dfi_df)
.venv/lib/python3.13/site-packages/altair/utils/deprecation.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import threading
5
+ import warnings
6
+ from typing import TYPE_CHECKING, Literal
7
+
8
+ if sys.version_info >= (3, 13):
9
+ from warnings import deprecated as _deprecated
10
+ else:
11
+ from typing_extensions import deprecated as _deprecated
12
+
13
+
14
+ if TYPE_CHECKING:
15
+ if sys.version_info >= (3, 11):
16
+ from typing import LiteralString
17
+ else:
18
+ from typing_extensions import LiteralString
19
+
20
+ __all__ = [
21
+ "AltairDeprecationWarning",
22
+ "deprecated",
23
+ "deprecated_static_only",
24
+ "deprecated_warn",
25
+ ]
26
+
27
+
28
+ class AltairDeprecationWarning(DeprecationWarning): ...
29
+
30
+
31
+ def _format_message(
32
+ version: LiteralString,
33
+ alternative: LiteralString | None,
34
+ message: LiteralString | None,
35
+ /,
36
+ ) -> LiteralString:
37
+ output = f"\nDeprecated since `altair={version}`."
38
+ if alternative:
39
+ output = f"{output} Use {alternative} instead."
40
+ return f"{output}\n{message}" if message else output
41
+
42
+
43
+ # NOTE: Annotating the return type breaks `pyright` detecting [reportDeprecated]
44
+ # NOTE: `LiteralString` requirement is introduced by stubs
45
+ def deprecated(
46
+ *,
47
+ version: LiteralString,
48
+ alternative: LiteralString | None = None,
49
+ message: LiteralString | None = None,
50
+ category: type[AltairDeprecationWarning] | None = AltairDeprecationWarning,
51
+ stacklevel: int = 1,
52
+ ): # te.deprecated
53
+ """
54
+ Indicate that a class, function or overload is deprecated.
55
+
56
+ When this decorator is applied to an object, the type checker
57
+ will generate a diagnostic on usage of the deprecated object.
58
+
59
+ Parameters
60
+ ----------
61
+ version
62
+ ``altair`` version the deprecation first appeared.
63
+ alternative
64
+ Suggested replacement class/method/function.
65
+ message
66
+ Additional message appended to ``version``, ``alternative``.
67
+ category
68
+ If the *category* is ``None``, no warning is emitted at runtime.
69
+ stacklevel
70
+ The *stacklevel* determines where the
71
+ warning is emitted. If it is ``1`` (the default), the warning
72
+ is emitted at the direct caller of the deprecated object; if it
73
+ is higher, it is emitted further up the stack.
74
+ Static type checker behavior is not affected by the *category*
75
+ and *stacklevel* arguments.
76
+
77
+ References
78
+ ----------
79
+ [PEP 702](https://peps.python.org/pep-0702/)
80
+ """
81
+ msg = _format_message(version, alternative, message)
82
+ return _deprecated(msg, category=category, stacklevel=stacklevel)
83
+
84
+
85
+ def deprecated_warn(
86
+ message: LiteralString,
87
+ *,
88
+ version: LiteralString,
89
+ alternative: LiteralString | None = None,
90
+ category: type[AltairDeprecationWarning] = AltairDeprecationWarning,
91
+ stacklevel: int = 2,
92
+ action: Literal["once"] | None = None,
93
+ ) -> None:
94
+ """
95
+ Indicate that the current code path is deprecated.
96
+
97
+ This should be used for non-trivial cases *only*. ``@deprecated`` should
98
+ always be preferred as it is recognized by static type checkers.
99
+
100
+ Parameters
101
+ ----------
102
+ message
103
+ Explanation of the deprecated behaviour.
104
+
105
+ .. note::
106
+ Unlike ``@deprecated``, this is *not* optional.
107
+
108
+ version
109
+ ``altair`` version the deprecation first appeared.
110
+ alternative
111
+ Suggested replacement argument/method/function.
112
+ category
113
+ The runtime warning type emitted.
114
+ stacklevel
115
+ How far up the call stack to make this warning appear.
116
+ A value of ``2`` attributes the warning to the caller
117
+ of the code calling ``deprecated_warn()``.
118
+
119
+ References
120
+ ----------
121
+ [warnings.warn](https://docs.python.org/3/library/warnings.html#warnings.warn)
122
+ """
123
+ msg = _format_message(version, alternative, message)
124
+ if action is None:
125
+ warnings.warn(msg, category=category, stacklevel=stacklevel)
126
+ elif action == "once":
127
+ _warn_once(msg, category=category, stacklevel=stacklevel)
128
+ else:
129
+ raise NotImplementedError(action)
130
+
131
+
132
+ deprecated_static_only = _deprecated
133
+ """
134
+ Using this decorator **exactly as described**, ensures ``message`` is displayed to a static type checker.
135
+
136
+ **BE CAREFUL USING THIS**.
137
+
138
+ See screenshots in `comment`_ for motivation.
139
+
140
+ Every use should look like::
141
+
142
+ @deprecated_static_only(
143
+ "Deprecated since `altair=5.5.0`. Use altair.other instead.",
144
+ category=None,
145
+ )
146
+ def old_function(*args): ...
147
+
148
+ If a runtime warning is desired, use `@alt.utils.deprecated` instead.
149
+
150
+ Parameters
151
+ ----------
152
+ message : LiteralString
153
+ - **Not** a variable
154
+ - **Not** use placeholders
155
+ - **Not** use concatenation
156
+ - **Do not use anything that could be considered dynamic**
157
+
158
+ category : None
159
+ You **need** to explicitly pass ``None``
160
+
161
+ .. _comment:
162
+ https://github.com/vega/altair/pull/3618#issuecomment-2423991968
163
+ ---
164
+ """
165
+
166
+
167
+ class _WarningsMonitor:
168
+ def __init__(self) -> None:
169
+ self._warned: dict[LiteralString, Literal[True]] = {}
170
+ self._lock = threading.Lock()
171
+
172
+ def __contains__(self, key: LiteralString, /) -> bool:
173
+ with self._lock:
174
+ return key in self._warned
175
+
176
+ def hit(self, key: LiteralString, /) -> None:
177
+ with self._lock:
178
+ self._warned[key] = True
179
+
180
+ def clear(self) -> None:
181
+ with self._lock:
182
+ self._warned.clear()
183
+
184
+
185
+ _warnings_monitor = _WarningsMonitor()
186
+
187
+
188
+ def _warn_once(
189
+ msg: LiteralString, /, *, category: type[AltairDeprecationWarning], stacklevel: int
190
+ ) -> None:
191
+ global _warnings_monitor
192
+ if msg in _warnings_monitor:
193
+ return
194
+ else:
195
+ _warnings_monitor.hit(msg)
196
+ warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
.venv/lib/python3.13/site-packages/altair/utils/display.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import pkgutil
5
+ import textwrap
6
+ import uuid
7
+ from collections.abc import Callable
8
+ from typing import TYPE_CHECKING, Any, Union
9
+
10
+ from ._vegafusion_data import compile_with_vegafusion, using_vegafusion
11
+ from .mimebundle import spec_to_mimebundle
12
+ from .plugin_registry import PluginEnabler, PluginRegistry
13
+ from .schemapi import validate_jsonschema
14
+
15
+ if TYPE_CHECKING:
16
+ import sys
17
+
18
+ if sys.version_info >= (3, 10):
19
+ from typing import TypeAlias
20
+ else:
21
+ from typing_extensions import TypeAlias
22
+
23
+ # ==============================================================================
24
+ # Renderer registry
25
+ # ==============================================================================
26
+ # MimeBundleType needs to be the same as what are acceptable return values
27
+ # for _repr_mimebundle_,
28
+ # see https://ipython.readthedocs.io/en/stable/config/integrating.html#MyObject._repr_mimebundle_
29
+ MimeBundleDataType: TypeAlias = dict[str, Any]
30
+ MimeBundleMetaDataType: TypeAlias = dict[str, Any]
31
+ MimeBundleType: TypeAlias = Union[
32
+ MimeBundleDataType, tuple[MimeBundleDataType, MimeBundleMetaDataType]
33
+ ]
34
+ RendererType: TypeAlias = Callable[..., MimeBundleType]
35
+ # Subtype of MimeBundleType as more specific in the values of the dictionaries
36
+
37
+ DefaultRendererReturnType: TypeAlias = tuple[
38
+ dict[str, Union[str, dict[str, Any]]], dict[str, dict[str, Any]]
39
+ ]
40
+
41
+
42
+ class RendererRegistry(PluginRegistry[RendererType, MimeBundleType]):
43
+ entrypoint_err_messages = {
44
+ "notebook": textwrap.dedent(
45
+ """
46
+ To use the 'notebook' renderer, you must install the vega package
47
+ and the associated Jupyter extension.
48
+ See https://altair-viz.github.io/getting_started/installation.html
49
+ for more information.
50
+ """
51
+ ),
52
+ }
53
+
54
+ def set_embed_options(
55
+ self,
56
+ defaultStyle: bool | str | None = None,
57
+ renderer: str | None = None,
58
+ width: int | None = None,
59
+ height: int | None = None,
60
+ padding: int | None = None,
61
+ scaleFactor: float | None = None,
62
+ actions: bool | dict[str, bool] | None = None,
63
+ format_locale: str | dict | None = None,
64
+ time_format_locale: str | dict | None = None,
65
+ **kwargs,
66
+ ) -> PluginEnabler:
67
+ """
68
+ Set options for embeddings of Vega & Vega-Lite charts.
69
+
70
+ Options are fully documented at https://github.com/vega/vega-embed.
71
+ Similar to the `enable()` method, this can be used as either
72
+ a persistent global switch, or as a temporary local setting using
73
+ a context manager (i.e. a `with` statement).
74
+
75
+ Parameters
76
+ ----------
77
+ defaultStyle : bool or string
78
+ Specify a default stylesheet for embed actions.
79
+ renderer : string
80
+ The renderer to use for the view. One of "canvas" (default) or "svg"
81
+ width : integer
82
+ The view width in pixels
83
+ height : integer
84
+ The view height in pixels
85
+ padding : integer
86
+ The view padding in pixels
87
+ scaleFactor : number
88
+ The number by which to multiply the width and height (default 1)
89
+ of an exported PNG or SVG image.
90
+ actions : bool or dict
91
+ Determines if action links ("Export as PNG/SVG", "View Source",
92
+ "View Vega" (only for Vega-Lite), "Open in Vega Editor") are
93
+ included with the embedded view. If the value is true, all action
94
+ links will be shown and none if the value is false. This property
95
+ can take a key-value mapping object that maps keys (export, source,
96
+ compiled, editor) to boolean values for determining if
97
+ each action link should be shown.
98
+ format_locale : str or dict
99
+ d3-format locale name or dictionary. Defaults to "en-US" for United States English.
100
+ See https://github.com/d3/d3-format/tree/main/locale for available names and example
101
+ definitions.
102
+ time_format_locale : str or dict
103
+ d3-time-format locale name or dictionary. Defaults to "en-US" for United States English.
104
+ See https://github.com/d3/d3-time-format/tree/main/locale for available names and example
105
+ definitions.
106
+ **kwargs :
107
+ Additional options are passed directly to embed options.
108
+ """
109
+ options: dict[str, bool | str | float | dict[str, bool] | None] = {
110
+ "defaultStyle": defaultStyle,
111
+ "renderer": renderer,
112
+ "width": width,
113
+ "height": height,
114
+ "padding": padding,
115
+ "scaleFactor": scaleFactor,
116
+ "actions": actions,
117
+ "formatLocale": format_locale,
118
+ "timeFormatLocale": time_format_locale,
119
+ }
120
+ kwargs.update({key: val for key, val in options.items() if val is not None})
121
+ return self.enable(None, embed_options=kwargs)
122
+
123
+
124
+ # ==============================================================================
125
+ # VegaLite v1/v2 renderer logic
126
+ # ==============================================================================
127
+
128
+
129
+ class Displayable:
130
+ """
131
+ A base display class for VegaLite v1/v2.
132
+
133
+ This class takes a VegaLite v1/v2 spec and does the following:
134
+
135
+ 1. Optionally validates the spec against a schema.
136
+ 2. Uses the RendererPlugin to grab a renderer and call it when the
137
+ IPython/Jupyter display method (_repr_mimebundle_) is called.
138
+
139
+ The spec passed to this class must be fully schema compliant and already
140
+ have the data portion of the spec fully processed and ready to serialize.
141
+ In practice, this means, the data portion of the spec should have been passed
142
+ through appropriate data model transformers.
143
+ """
144
+
145
+ renderers: RendererRegistry | None = None
146
+ schema_path = ("altair", "")
147
+
148
+ def __init__(self, spec: dict[str, Any], validate: bool = False) -> None:
149
+ self.spec = spec
150
+ self.validate = validate
151
+ self._validate()
152
+
153
+ def _validate(self) -> None:
154
+ """Validate the spec against the schema."""
155
+ data = pkgutil.get_data(*self.schema_path)
156
+ assert data is not None
157
+ schema_dict: dict[str, Any] = json.loads(data.decode("utf-8"))
158
+ validate_jsonschema(
159
+ self.spec,
160
+ schema_dict,
161
+ )
162
+
163
+ def _repr_mimebundle_(
164
+ self, include: Any = None, exclude: Any = None
165
+ ) -> MimeBundleType:
166
+ """Return a MIME bundle for display in Jupyter frontends."""
167
+ if self.renderers is not None:
168
+ renderer_func = self.renderers.get()
169
+ assert renderer_func is not None
170
+ return renderer_func(self.spec)
171
+ else:
172
+ return {}
173
+
174
+
175
+ def default_renderer_base(
176
+ spec: dict[str, Any], mime_type: str, str_repr: str, **options
177
+ ) -> DefaultRendererReturnType:
178
+ """
179
+ A default renderer for Vega or VegaLite that works for modern frontends.
180
+
181
+ This renderer works with modern frontends (JupyterLab, nteract) that know
182
+ how to render the custom VegaLite MIME type listed above.
183
+ """
184
+ # Local import to avoid circular ImportError
185
+ from altair.vegalite.v6.display import VEGA_MIME_TYPE, VEGALITE_MIME_TYPE
186
+
187
+ assert isinstance(spec, dict)
188
+ bundle: dict[str, str | dict] = {}
189
+ metadata: dict[str, dict[str, Any]] = {}
190
+
191
+ if using_vegafusion():
192
+ spec = compile_with_vegafusion(spec)
193
+
194
+ # Swap mimetype from Vega-Lite to Vega.
195
+ # If mimetype was JSON, leave it alone
196
+ if mime_type == VEGALITE_MIME_TYPE:
197
+ mime_type = VEGA_MIME_TYPE
198
+
199
+ bundle[mime_type] = spec
200
+ bundle["text/plain"] = str_repr
201
+ if options:
202
+ metadata[mime_type] = options
203
+ return bundle, metadata
204
+
205
+
206
+ def json_renderer_base(
207
+ spec: dict[str, Any], str_repr: str, **options
208
+ ) -> DefaultRendererReturnType:
209
+ """
210
+ A renderer that returns a MIME type of application/json.
211
+
212
+ In JupyterLab/nteract this is rendered as a nice JSON tree.
213
+ """
214
+ return default_renderer_base(
215
+ spec, mime_type="application/json", str_repr=str_repr, **options
216
+ )
217
+
218
+
219
+ class HTMLRenderer:
220
+ """Object to render charts as HTML, with a unique output div each time."""
221
+
222
+ def __init__(self, output_div: str = "altair-viz-{}", **kwargs) -> None:
223
+ self._output_div = output_div
224
+ self.kwargs = kwargs
225
+
226
+ @property
227
+ def output_div(self) -> str:
228
+ return self._output_div.format(uuid.uuid4().hex)
229
+
230
+ def __call__(self, spec: dict[str, Any], **metadata) -> dict[str, str]:
231
+ kwargs = self.kwargs.copy()
232
+ kwargs.update(**metadata, output_div=self.output_div)
233
+ return spec_to_mimebundle(spec, format="html", **kwargs)
.venv/lib/python3.13/site-packages/altair/utils/execeval.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ import sys
5
+ from typing import TYPE_CHECKING, Any, Literal, overload
6
+
7
+ if TYPE_CHECKING:
8
+ from collections.abc import Callable
9
+ from os import PathLike
10
+
11
+ from _typeshed import ReadableBuffer
12
+
13
+ if sys.version_info >= (3, 11):
14
+ from typing import Self
15
+ else:
16
+ from typing_extensions import Self
17
+
18
+
19
+ class _CatchDisplay:
20
+ """Class to temporarily catch sys.displayhook."""
21
+
22
+ def __init__(self) -> None:
23
+ self.output: Any | None = None
24
+
25
+ def __enter__(self) -> Self:
26
+ self.old_hook: Callable[[object], Any] = sys.displayhook
27
+ sys.displayhook = self
28
+ return self
29
+
30
+ def __exit__(self, type, value, traceback) -> Literal[False]:
31
+ sys.displayhook = self.old_hook
32
+ # Returning False will cause exceptions to propagate
33
+ return False
34
+
35
+ def __call__(self, output: Any) -> None:
36
+ self.output = output
37
+
38
+
39
+ @overload
40
+ def eval_block(
41
+ code: str | Any,
42
+ namespace: dict[str, Any] | None = ...,
43
+ filename: str | ReadableBuffer | PathLike[Any] = ...,
44
+ *,
45
+ strict: Literal[False] = ...,
46
+ ) -> Any | None: ...
47
+ @overload
48
+ def eval_block(
49
+ code: str | Any,
50
+ namespace: dict[str, Any] | None = ...,
51
+ filename: str | ReadableBuffer | PathLike[Any] = ...,
52
+ *,
53
+ strict: Literal[True],
54
+ ) -> Any: ...
55
+ def eval_block(
56
+ code: str | Any,
57
+ namespace: dict[str, Any] | None = None,
58
+ filename: str | ReadableBuffer | PathLike[Any] = "<string>",
59
+ *,
60
+ strict: bool = False,
61
+ ) -> Any | None:
62
+ """
63
+ Execute a multi-line block of code in the given namespace.
64
+
65
+ If the final statement in the code is an expression, return
66
+ the result of the expression.
67
+
68
+ If ``strict``, raise a ``TypeError`` when the return value would be ``None``.
69
+ """
70
+ tree = ast.parse(code, filename="<ast>", mode="exec")
71
+ if namespace is None:
72
+ namespace = {}
73
+ catch_display = _CatchDisplay()
74
+
75
+ if isinstance(tree.body[-1], ast.Expr):
76
+ to_exec, to_eval = tree.body[:-1], tree.body[-1:]
77
+ else:
78
+ to_exec, to_eval = tree.body, []
79
+
80
+ for node in to_exec:
81
+ compiled = compile(ast.Module([node], []), filename=filename, mode="exec")
82
+ exec(compiled, namespace)
83
+
84
+ with catch_display:
85
+ for node in to_eval:
86
+ compiled = compile(
87
+ ast.Interactive([node]), filename=filename, mode="single"
88
+ )
89
+ exec(compiled, namespace)
90
+
91
+ if strict:
92
+ output = catch_display.output
93
+ if output is None:
94
+ msg = f"Expected a non-None value but got {output!r}"
95
+ raise TypeError(msg)
96
+ else:
97
+ return output
98
+ else:
99
+ return catch_display.output
.venv/lib/python3.13/site-packages/altair/utils/html.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import Any, Literal
5
+
6
+ import jinja2
7
+
8
+ from altair.utils._importers import import_vl_convert, vl_version_for_vl_convert
9
+
10
+ TemplateName = Literal["standard", "universal", "inline", "olli"]
11
+ RenderMode = Literal["vega", "vega-lite"]
12
+
13
+ HTML_TEMPLATE = jinja2.Template(
14
+ """
15
+ {%- if fullhtml -%}
16
+ <!DOCTYPE html>
17
+ <html>
18
+ <head>
19
+ <meta charset="UTF-8">
20
+ {%- endif %}
21
+ <style>
22
+ #{{ output_div }}.vega-embed {
23
+ width: 100%;
24
+ display: flex;
25
+ }
26
+
27
+ #{{ output_div }}.vega-embed details,
28
+ #{{ output_div }}.vega-embed details summary {
29
+ position: relative;
30
+ }
31
+ </style>
32
+ {%- if not requirejs %}
33
+ <script type="text/javascript" src="{{ base_url }}/vega@{{ vega_version }}"></script>
34
+ {%- if mode == 'vega-lite' %}
35
+ <script type="text/javascript" src="{{ base_url }}/vega-lite@{{ vegalite_version }}"></script>
36
+ {%- endif %}
37
+ <script type="text/javascript" src="{{ base_url }}/vega-embed@{{ vegaembed_version }}"></script>
38
+ {%- endif %}
39
+ {%- if fullhtml %}
40
+ {%- if requirejs %}
41
+ <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
42
+ <script>
43
+ requirejs.config({
44
+ "paths": {
45
+ "vega": "{{ base_url }}/vega@{{ vega_version }}?noext",
46
+ "vega-lib": "{{ base_url }}/vega-lib?noext",
47
+ "vega-lite": "{{ base_url }}/vega-lite@{{ vegalite_version }}?noext",
48
+ "vega-embed": "{{ base_url }}/vega-embed@{{ vegaembed_version }}?noext",
49
+ }
50
+ });
51
+ </script>
52
+ {%- endif %}
53
+ </head>
54
+ <body>
55
+ {%- endif %}
56
+ <div id="{{ output_div }}"></div>
57
+ <script>
58
+ {%- if requirejs and not fullhtml %}
59
+ requirejs.config({
60
+ "paths": {
61
+ "vega": "{{ base_url }}/vega@{{ vega_version }}?noext",
62
+ "vega-lib": "{{ base_url }}/vega-lib?noext",
63
+ "vega-lite": "{{ base_url }}/vega-lite@{{ vegalite_version }}?noext",
64
+ "vega-embed": "{{ base_url }}/vega-embed@{{ vegaembed_version }}?noext",
65
+ }
66
+ });
67
+ {% endif %}
68
+ {% if requirejs -%}
69
+ require(['vega-embed'],
70
+ {%- else -%}
71
+ (
72
+ {%- endif -%}
73
+ function(vegaEmbed) {
74
+ var spec = {{ spec }};
75
+ var embedOpt = {{ embed_options }};
76
+
77
+ function showError(el, error){
78
+ el.innerHTML = ('<div style="color:red;">'
79
+ + '<p>JavaScript Error: ' + error.message + '</p>'
80
+ + "<p>This usually means there's a typo in your chart specification. "
81
+ + "See the javascript console for the full traceback.</p>"
82
+ + '</div>');
83
+ throw error;
84
+ }
85
+ const el = document.getElementById('{{ output_div }}');
86
+ vegaEmbed("#{{ output_div }}", spec, embedOpt)
87
+ .catch(error => showError(el, error));
88
+ }){% if not requirejs %}(vegaEmbed){% endif %};
89
+
90
+ </script>
91
+ {%- if fullhtml %}
92
+ </body>
93
+ </html>
94
+ {%- endif %}
95
+ """
96
+ )
97
+
98
+
99
+ HTML_TEMPLATE_UNIVERSAL = jinja2.Template(
100
+ """
101
+ <style>
102
+ #{{ output_div }}.vega-embed {
103
+ width: 100%;
104
+ display: flex;
105
+ }
106
+
107
+ #{{ output_div }}.vega-embed details,
108
+ #{{ output_div }}.vega-embed details summary {
109
+ position: relative;
110
+ }
111
+ </style>
112
+ <div id="{{ output_div }}"></div>
113
+ <script type="text/javascript">
114
+ var VEGA_DEBUG = (typeof VEGA_DEBUG == "undefined") ? {} : VEGA_DEBUG;
115
+ (function(spec, embedOpt){
116
+ let outputDiv = document.currentScript.previousElementSibling;
117
+ if (outputDiv.id !== "{{ output_div }}") {
118
+ outputDiv = document.getElementById("{{ output_div }}");
119
+ }
120
+
121
+ const paths = {
122
+ "vega": "{{ base_url }}/vega@{{ vega_version }}?noext",
123
+ "vega-lib": "{{ base_url }}/vega-lib?noext",
124
+ "vega-lite": "{{ base_url }}/vega-lite@{{ vegalite_version }}?noext",
125
+ "vega-embed": "{{ base_url }}/vega-embed@{{ vegaembed_version }}?noext",
126
+ };
127
+
128
+ function maybeLoadScript(lib, version) {
129
+ var key = `${lib.replace("-", "")}_version`;
130
+ return (VEGA_DEBUG[key] == version) ?
131
+ Promise.resolve(paths[lib]) :
132
+ new Promise(function(resolve, reject) {
133
+ var s = document.createElement('script');
134
+ document.getElementsByTagName("head")[0].appendChild(s);
135
+ s.async = true;
136
+ s.onload = () => {
137
+ VEGA_DEBUG[key] = version;
138
+ return resolve(paths[lib]);
139
+ };
140
+ s.onerror = () => reject(`Error loading script: ${paths[lib]}`);
141
+ s.src = paths[lib];
142
+ });
143
+ }
144
+
145
+ function showError(err) {
146
+ outputDiv.innerHTML = `<div class="error" style="color:red;">${err}</div>`;
147
+ throw err;
148
+ }
149
+
150
+ function displayChart(vegaEmbed) {
151
+ vegaEmbed(outputDiv, spec, embedOpt)
152
+ .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));
153
+ }
154
+
155
+ if(typeof define === "function" && define.amd) {
156
+ requirejs.config({paths});
157
+ let deps = ["vega-embed"];
158
+ require(deps, displayChart, err => showError(`Error loading script: ${err.message}`));
159
+ } else {
160
+ maybeLoadScript("vega", "{{vega_version}}")
161
+ .then(() => maybeLoadScript("vega-lite", "{{vegalite_version}}"))
162
+ .then(() => maybeLoadScript("vega-embed", "{{vegaembed_version}}"))
163
+ .catch(showError)
164
+ .then(() => displayChart(vegaEmbed));
165
+ }
166
+ })({{ spec }}, {{ embed_options }});
167
+ </script>
168
+ """
169
+ )
170
+
171
+
172
+ # This is like the HTML_TEMPLATE template, but includes vega javascript inline
173
+ # so that the resulting file is not dependent on external resources. This was
174
+ # ported over from altair_saver.
175
+ #
176
+ # implies requirejs=False and full_html=True
177
+ INLINE_HTML_TEMPLATE = jinja2.Template(
178
+ """\
179
+ <!DOCTYPE html>
180
+ <html>
181
+ <head>
182
+ <meta charset="UTF-8">
183
+ <style>
184
+ #{{ output_div }}.vega-embed {
185
+ width: 100%;
186
+ display: flex;
187
+ }
188
+
189
+ #{{ output_div }}.vega-embed details,
190
+ #{{ output_div }}.vega-embed details summary {
191
+ position: relative;
192
+ }
193
+ </style>
194
+ <script type="text/javascript">
195
+ // vega-embed.js bundle with Vega-Lite version v{{ vegalite_version }}
196
+ {{ vegaembed_script }}
197
+ </script>
198
+ </head>
199
+ <body>
200
+ <div class="vega-visualization" id="{{ output_div }}"></div>
201
+ <script type="text/javascript">
202
+ const spec = {{ spec }};
203
+ const embedOpt = {{ embed_options }};
204
+ vegaEmbed('#{{ output_div }}', spec, embedOpt).catch(console.error);
205
+ </script>
206
+ </body>
207
+ </html>
208
+ """
209
+ )
210
+
211
+
212
+ HTML_TEMPLATE_OLLI = jinja2.Template(
213
+ """
214
+ <style>
215
+ #{{ output_div }}.vega-embed {
216
+ width: 100%;
217
+ display: flex;
218
+ }
219
+
220
+ #{{ output_div }}.vega-embed details,
221
+ #{{ output_div }}.vega-embed details summary {
222
+ position: relative;
223
+ }
224
+ </style>
225
+ <div id="{{ output_div }}"></div>
226
+ <script type="text/javascript">
227
+ var VEGA_DEBUG = (typeof VEGA_DEBUG == "undefined") ? {} : VEGA_DEBUG;
228
+ (function(spec, embedOpt){
229
+ let outputDiv = document.currentScript.previousElementSibling;
230
+ if (outputDiv.id !== "{{ output_div }}") {
231
+ outputDiv = document.getElementById("{{ output_div }}");
232
+ }
233
+ const olliDiv = document.createElement("div");
234
+ const vegaDiv = document.createElement("div");
235
+ outputDiv.appendChild(vegaDiv);
236
+ outputDiv.appendChild(olliDiv);
237
+ outputDiv = vegaDiv;
238
+
239
+ const paths = {
240
+ "vega": "{{ base_url }}/vega@{{ vega_version }}?noext",
241
+ "vega-lib": "{{ base_url }}/vega-lib?noext",
242
+ "vega-lite": "{{ base_url }}/vega-lite@{{ vegalite_version }}?noext",
243
+ "vega-embed": "{{ base_url }}/vega-embed@{{ vegaembed_version }}?noext",
244
+ "olli": "{{ base_url }}/olli@{{ olli_version }}?noext",
245
+ "olli-adapters": "{{ base_url }}/olli-adapters@{{ olli_adapters_version }}?noext",
246
+ };
247
+
248
+ function maybeLoadScript(lib, version) {
249
+ var key = `${lib.replace("-", "")}_version`;
250
+ return (VEGA_DEBUG[key] == version) ?
251
+ Promise.resolve(paths[lib]) :
252
+ new Promise(function(resolve, reject) {
253
+ var s = document.createElement('script');
254
+ document.getElementsByTagName("head")[0].appendChild(s);
255
+ s.async = true;
256
+ s.onload = () => {
257
+ VEGA_DEBUG[key] = version;
258
+ return resolve(paths[lib]);
259
+ };
260
+ s.onerror = () => reject(`Error loading script: ${paths[lib]}`);
261
+ s.src = paths[lib];
262
+ });
263
+ }
264
+
265
+ function showError(err) {
266
+ outputDiv.innerHTML = `<div class="error" style="color:red;">${err}</div>`;
267
+ throw err;
268
+ }
269
+
270
+ function displayChart(vegaEmbed, olli, olliAdapters) {
271
+ vegaEmbed(outputDiv, spec, embedOpt)
272
+ .catch(err => showError(`Javascript Error: ${err.message}<br>This usually means there's a typo in your chart specification. See the javascript console for the full traceback.`));
273
+ olliAdapters.VegaLiteAdapter(spec).then(olliVisSpec => {
274
+ const olliFunc = typeof olli === 'function' ? olli : olli.olli;
275
+ const olliRender = olliFunc(olliVisSpec);
276
+ olliDiv.append(olliRender);
277
+ });
278
+ }
279
+
280
+ if(typeof define === "function" && define.amd) {
281
+ requirejs.config({paths});
282
+ let deps = ["vega-embed", "olli", "olli-adapters"];
283
+ require(deps, displayChart, err => showError(`Error loading script: ${err.message}`));
284
+ } else {
285
+ maybeLoadScript("vega", "{{vega_version}}")
286
+ .then(() => maybeLoadScript("vega-lite", "{{vegalite_version}}"))
287
+ .then(() => maybeLoadScript("vega-embed", "{{vegaembed_version}}"))
288
+ .then(() => maybeLoadScript("olli", "{{olli_version}}"))
289
+ .then(() => maybeLoadScript("olli-adapters", "{{olli_adapters_version}}"))
290
+ .catch(showError)
291
+ .then(() => displayChart(vegaEmbed, olli, OlliAdapters));
292
+ }
293
+ })({{ spec }}, {{ embed_options }});
294
+ </script>
295
+ """
296
+ )
297
+
298
+
299
+ TEMPLATES: dict[TemplateName, jinja2.Template] = {
300
+ "standard": HTML_TEMPLATE,
301
+ "universal": HTML_TEMPLATE_UNIVERSAL,
302
+ "inline": INLINE_HTML_TEMPLATE,
303
+ "olli": HTML_TEMPLATE_OLLI,
304
+ }
305
+
306
+
307
+ def spec_to_html(
308
+ spec: dict[str, Any],
309
+ mode: RenderMode,
310
+ vega_version: str | None,
311
+ vegaembed_version: str | None,
312
+ vegalite_version: str | None = None,
313
+ base_url: str = "https://cdn.jsdelivr.net/npm",
314
+ output_div: str = "vis",
315
+ embed_options: dict[str, Any] | None = None,
316
+ json_kwds: dict[str, Any] | None = None,
317
+ fullhtml: bool = True,
318
+ requirejs: bool = False,
319
+ template: jinja2.Template | TemplateName = "standard",
320
+ ) -> str:
321
+ """
322
+ Embed a Vega/Vega-Lite spec into an HTML page.
323
+
324
+ Parameters
325
+ ----------
326
+ spec : dict
327
+ a dictionary representing a vega-lite plot spec.
328
+ mode : string {'vega' | 'vega-lite'}
329
+ The rendering mode. This value is overridden by embed_options['mode'],
330
+ if it is present.
331
+ vega_version : string
332
+ For html output, the version of vega.js to use.
333
+ vegalite_version : string
334
+ For html output, the version of vegalite.js to use.
335
+ vegaembed_version : string
336
+ For html output, the version of vegaembed.js to use.
337
+ base_url : string (optional)
338
+ The base url from which to load the javascript libraries.
339
+ output_div : string (optional)
340
+ The id of the div element where the plot will be shown.
341
+ embed_options : dict (optional)
342
+ Dictionary of options to pass to the vega-embed script. Default
343
+ entry is {'mode': mode}.
344
+ json_kwds : dict (optional)
345
+ Dictionary of keywords to pass to json.dumps().
346
+ fullhtml : boolean (optional)
347
+ If True (default) then return a full html page. If False, then return
348
+ an HTML snippet that can be embedded into an HTML page.
349
+ requirejs : boolean (optional)
350
+ If False (default) then load libraries from base_url using <script>
351
+ tags. If True, then load libraries using requirejs
352
+ template : jinja2.Template or string (optional)
353
+ Specify the template to use (default = 'standard'). If template is a
354
+ string, it must be one of {'universal', 'standard', 'inline'}. Otherwise, it
355
+ can be a jinja2.Template object containing a custom template.
356
+
357
+ Returns
358
+ -------
359
+ output : string
360
+ an HTML string for rendering the chart.
361
+ """
362
+ embed_options = embed_options or {}
363
+ json_kwds = json_kwds or {}
364
+
365
+ mode = embed_options.setdefault("mode", mode)
366
+
367
+ if mode not in {"vega", "vega-lite"}:
368
+ msg = "mode must be either 'vega' or 'vega-lite'"
369
+ raise ValueError(msg)
370
+
371
+ if vega_version is None:
372
+ msg = "must specify vega_version"
373
+ raise ValueError(msg)
374
+
375
+ if vegaembed_version is None:
376
+ msg = "must specify vegaembed_version"
377
+ raise ValueError(msg)
378
+
379
+ if mode == "vega-lite" and vegalite_version is None:
380
+ msg = "must specify vega-lite version for mode='vega-lite'"
381
+ raise ValueError(msg)
382
+
383
+ render_kwargs = {}
384
+ if template == "inline":
385
+ vlc = import_vl_convert()
386
+ vl_version = vl_version_for_vl_convert()
387
+ render_kwargs["vegaembed_script"] = vlc.javascript_bundle(vl_version=vl_version)
388
+ elif template == "olli":
389
+ OLLI_VERSION = "2"
390
+ OLLI_ADAPTERS_VERSION = "2"
391
+ render_kwargs["olli_version"] = OLLI_VERSION
392
+ render_kwargs["olli_adapters_version"] = OLLI_ADAPTERS_VERSION
393
+
394
+ jinja_template = TEMPLATES.get(template, template) # type: ignore[arg-type]
395
+ if not hasattr(jinja_template, "render"):
396
+ msg = f"Invalid template: {jinja_template}"
397
+ raise ValueError(msg)
398
+
399
+ return jinja_template.render(
400
+ spec=json.dumps(spec, **json_kwds),
401
+ embed_options=json.dumps(embed_options),
402
+ mode=mode,
403
+ vega_version=vega_version,
404
+ vegalite_version=vegalite_version,
405
+ vegaembed_version=vegaembed_version,
406
+ base_url=base_url,
407
+ output_div=output_div,
408
+ fullhtml=fullhtml,
409
+ requirejs=requirejs,
410
+ **render_kwargs,
411
+ )
.venv/lib/python3.13/site-packages/altair/utils/mimebundle.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import struct
4
+ from typing import TYPE_CHECKING, Any, Literal, cast, overload
5
+
6
+ from ._importers import import_vl_convert, vl_version_for_vl_convert
7
+ from .html import spec_to_html
8
+
9
+ if TYPE_CHECKING:
10
+ import sys
11
+
12
+ if sys.version_info >= (3, 10):
13
+ from typing import TypeAlias
14
+ else:
15
+ from typing_extensions import TypeAlias
16
+
17
+ MimeBundleFormat: TypeAlias = Literal[
18
+ "html", "json", "png", "svg", "pdf", "vega", "vega-lite"
19
+ ]
20
+
21
+
22
+ @overload
23
+ def spec_to_mimebundle(
24
+ spec: dict[str, Any],
25
+ format: Literal["json", "vega-lite"],
26
+ mode: Literal["vega-lite"] | None = ...,
27
+ vega_version: str | None = ...,
28
+ vegaembed_version: str | None = ...,
29
+ vegalite_version: str | None = ...,
30
+ embed_options: dict[str, Any] | None = ...,
31
+ engine: Literal["vl-convert"] | None = ...,
32
+ **kwargs,
33
+ ) -> dict[str, dict[str, Any]]: ...
34
+ @overload
35
+ def spec_to_mimebundle(
36
+ spec: dict[str, Any],
37
+ format: Literal["html"],
38
+ mode: Literal["vega-lite"] | None = ...,
39
+ vega_version: str | None = ...,
40
+ vegaembed_version: str | None = ...,
41
+ vegalite_version: str | None = ...,
42
+ embed_options: dict[str, Any] | None = ...,
43
+ engine: Literal["vl-convert"] | None = ...,
44
+ **kwargs,
45
+ ) -> dict[str, str]: ...
46
+ @overload
47
+ def spec_to_mimebundle(
48
+ spec: dict[str, Any],
49
+ format: Literal["pdf", "svg", "vega"],
50
+ mode: Literal["vega-lite"] | None = ...,
51
+ vega_version: str | None = ...,
52
+ vegaembed_version: str | None = ...,
53
+ vegalite_version: str | None = ...,
54
+ embed_options: dict[str, Any] | None = ...,
55
+ engine: Literal["vl-convert"] | None = ...,
56
+ **kwargs,
57
+ ) -> dict[str, Any]: ...
58
+ @overload
59
+ def spec_to_mimebundle(
60
+ spec: dict[str, Any],
61
+ format: Literal["png"],
62
+ mode: Literal["vega-lite"] | None = ...,
63
+ vega_version: str | None = ...,
64
+ vegaembed_version: str | None = ...,
65
+ vegalite_version: str | None = ...,
66
+ embed_options: dict[str, Any] | None = ...,
67
+ engine: Literal["vl-convert"] | None = ...,
68
+ **kwargs,
69
+ ) -> tuple[dict[str, Any], dict[str, Any]]: ...
70
+ def spec_to_mimebundle(
71
+ spec: dict[str, Any],
72
+ format: MimeBundleFormat,
73
+ mode: Literal["vega-lite"] | None = None,
74
+ vega_version: str | None = None,
75
+ vegaembed_version: str | None = None,
76
+ vegalite_version: str | None = None,
77
+ embed_options: dict[str, Any] | None = None,
78
+ engine: Literal["vl-convert"] | None = None,
79
+ **kwargs,
80
+ ) -> dict[str, Any] | tuple[dict[str, Any], dict[str, Any]]:
81
+ """
82
+ Convert a vega-lite specification to a mimebundle.
83
+
84
+ The mimebundle type is controlled by the ``format`` argument, which can be
85
+ one of the following ['html', 'json', 'png', 'svg', 'pdf', 'vega', 'vega-lite']
86
+
87
+ Parameters
88
+ ----------
89
+ spec : dict
90
+ a dictionary representing a vega-lite plot spec
91
+ format : string {'html', 'json', 'png', 'svg', 'pdf', 'vega', 'vega-lite'}
92
+ the file format to be saved.
93
+ mode : string {'vega-lite'}
94
+ The rendering mode.
95
+ vega_version : string
96
+ The version of vega.js to use
97
+ vegaembed_version : string
98
+ The version of vegaembed.js to use
99
+ vegalite_version : string
100
+ The version of vegalite.js to use. Only required if mode=='vega-lite'
101
+ embed_options : dict (optional)
102
+ The vegaEmbed options dictionary. Defaults to the embed options set with
103
+ alt.renderers.set_embed_options().
104
+ (See https://github.com/vega/vega-embed for details)
105
+ engine: string {'vl-convert'}
106
+ the conversion engine to use for 'png', 'svg', 'pdf', and 'vega' formats
107
+ **kwargs :
108
+ Additional arguments will be passed to the generating function
109
+
110
+ Returns
111
+ -------
112
+ output : dict
113
+ a mime-bundle representing the image
114
+
115
+ Note
116
+ ----
117
+ The png, svg, pdf, and vega outputs require the vl-convert package
118
+ """
119
+ # Local import to avoid circular ImportError
120
+ from altair import renderers
121
+ from altair.utils.display import compile_with_vegafusion, using_vegafusion
122
+
123
+ if mode != "vega-lite":
124
+ msg = "mode must be 'vega-lite'"
125
+ raise ValueError(msg)
126
+
127
+ internal_mode: Literal["vega-lite", "vega"] = mode
128
+ if using_vegafusion():
129
+ spec = compile_with_vegafusion(spec)
130
+ internal_mode = "vega"
131
+
132
+ # Default to the embed options set by alt.renderers.set_embed_options
133
+ if embed_options is None:
134
+ final_embed_options = renderers.options.get("embed_options", {})
135
+ else:
136
+ final_embed_options = embed_options
137
+
138
+ embed_options = preprocess_embed_options(final_embed_options)
139
+
140
+ if format in {"png", "svg", "pdf", "vega"}:
141
+ return _spec_to_mimebundle_with_engine(
142
+ spec,
143
+ cast("Literal['png', 'svg', 'pdf', 'vega']", format),
144
+ internal_mode,
145
+ engine=engine,
146
+ format_locale=embed_options.get("formatLocale", None),
147
+ time_format_locale=embed_options.get("timeFormatLocale", None),
148
+ **kwargs,
149
+ )
150
+ elif format == "html":
151
+ html = spec_to_html(
152
+ spec,
153
+ mode=internal_mode,
154
+ vega_version=vega_version,
155
+ vegaembed_version=vegaembed_version,
156
+ vegalite_version=vegalite_version,
157
+ embed_options=embed_options,
158
+ **kwargs,
159
+ )
160
+ return {"text/html": html}
161
+ elif format == "vega-lite":
162
+ if vegalite_version is None:
163
+ msg = "Must specify vegalite_version"
164
+ raise ValueError(msg)
165
+ return {f"application/vnd.vegalite.v{vegalite_version[0]}+json": spec}
166
+ elif format == "json":
167
+ return {"application/json": spec}
168
+ else:
169
+ msg = (
170
+ "format must be one of "
171
+ "['html', 'json', 'png', 'svg', 'pdf', 'vega', 'vega-lite']"
172
+ )
173
+ raise ValueError(msg)
174
+
175
+
176
+ def _spec_to_mimebundle_with_engine(
177
+ spec: dict,
178
+ format: Literal["png", "svg", "pdf", "vega"],
179
+ mode: Literal["vega-lite", "vega"],
180
+ format_locale: str | dict | None = None,
181
+ time_format_locale: str | dict | None = None,
182
+ **kwargs,
183
+ ) -> Any:
184
+ """
185
+ Helper for Vega-Lite to mimebundle conversions that require an engine.
186
+
187
+ Parameters
188
+ ----------
189
+ spec : dict
190
+ a dictionary representing a vega-lite plot spec
191
+ format : string {'png', 'svg', 'pdf', 'vega'}
192
+ the format of the mimebundle to be returned
193
+ mode : string {'vega-lite', 'vega'}
194
+ The rendering mode.
195
+ engine: string {'vl-convert'}
196
+ the conversion engine to use
197
+ format_locale : str or dict
198
+ d3-format locale name or dictionary. Defaults to "en-US" for United States English.
199
+ See https://github.com/d3/d3-format/tree/main/locale for available names and example
200
+ definitions.
201
+ time_format_locale : str or dict
202
+ d3-time-format locale name or dictionary. Defaults to "en-US" for United States English.
203
+ See https://github.com/d3/d3-time-format/tree/main/locale for available names and example
204
+ definitions.
205
+ **kwargs :
206
+ Additional arguments will be passed to the conversion function
207
+ """
208
+ # Normalize the engine string (if any) by lower casing
209
+ # and removing underscores and hyphens
210
+ engine = kwargs.pop("engine", None)
211
+ normalized_engine = _validate_normalize_engine(engine, format)
212
+
213
+ if normalized_engine == "vlconvert":
214
+ vlc = import_vl_convert()
215
+ vl_version = vl_version_for_vl_convert()
216
+ if format == "vega":
217
+ if mode == "vega":
218
+ vg = spec
219
+ else:
220
+ vg = vlc.vegalite_to_vega(spec, vl_version=vl_version)
221
+ return {"application/vnd.vega.v6+json": vg}
222
+ elif format == "svg":
223
+ if mode == "vega":
224
+ svg = vlc.vega_to_svg(
225
+ spec,
226
+ format_locale=format_locale,
227
+ time_format_locale=time_format_locale,
228
+ )
229
+ else:
230
+ svg = vlc.vegalite_to_svg(
231
+ spec,
232
+ vl_version=vl_version,
233
+ format_locale=format_locale,
234
+ time_format_locale=time_format_locale,
235
+ )
236
+ return {"image/svg+xml": svg}
237
+ elif format == "png":
238
+ scale = kwargs.get("scale_factor", 1)
239
+ # The default ppi for a PNG file is 72
240
+ default_ppi = 72
241
+ ppi = kwargs.get("ppi", default_ppi)
242
+ if mode == "vega":
243
+ png = vlc.vega_to_png(
244
+ spec,
245
+ scale=scale,
246
+ ppi=ppi,
247
+ format_locale=format_locale,
248
+ time_format_locale=time_format_locale,
249
+ )
250
+ else:
251
+ png = vlc.vegalite_to_png(
252
+ spec,
253
+ vl_version=vl_version,
254
+ scale=scale,
255
+ ppi=ppi,
256
+ format_locale=format_locale,
257
+ time_format_locale=time_format_locale,
258
+ )
259
+ factor = ppi / default_ppi
260
+ w, h = _pngxy(png)
261
+ return {"image/png": png}, {
262
+ "image/png": {"width": w / factor, "height": h / factor}
263
+ }
264
+ elif format == "pdf":
265
+ scale = kwargs.get("scale_factor", 1)
266
+ if mode == "vega":
267
+ pdf = vlc.vega_to_pdf(
268
+ spec,
269
+ scale=scale,
270
+ format_locale=format_locale,
271
+ time_format_locale=time_format_locale,
272
+ )
273
+ else:
274
+ pdf = vlc.vegalite_to_pdf(
275
+ spec,
276
+ vl_version=vl_version,
277
+ scale=scale,
278
+ format_locale=format_locale,
279
+ time_format_locale=time_format_locale,
280
+ )
281
+ return {"application/pdf": pdf}
282
+ else:
283
+ # This should be validated above
284
+ # but raise exception for the sake of future development
285
+ msg = f"Unexpected format {format!r}"
286
+ raise ValueError(msg)
287
+ else:
288
+ # This should be validated above
289
+ # but raise exception for the sake of future development
290
+ msg = f"Unexpected normalized_engine {normalized_engine!r}"
291
+ raise ValueError(msg)
292
+
293
+
294
+ def _validate_normalize_engine(
295
+ engine: Literal["vl-convert"] | None,
296
+ format: Literal["png", "svg", "pdf", "vega"],
297
+ ) -> str:
298
+ """
299
+ Helper to validate and normalize the user-provided engine.
300
+
301
+ engine : {None, 'vl-convert'}
302
+ the user-provided engine string
303
+ format : string {'png', 'svg', 'pdf', 'vega'}
304
+ the format of the mimebundle to be returned
305
+ """
306
+ # Try to import vl_convert
307
+ try:
308
+ vlc = import_vl_convert()
309
+ except ImportError:
310
+ vlc = None
311
+
312
+ # Normalize engine string by lower casing and removing underscores and hyphens
313
+ normalized_engine = (
314
+ None if engine is None else engine.lower().replace("-", "").replace("_", "")
315
+ )
316
+
317
+ # Validate or infer default value of normalized_engine
318
+ if normalized_engine == "vlconvert":
319
+ if vlc is None:
320
+ msg = "The 'vl-convert' conversion engine requires the vl-convert-python package"
321
+ raise ValueError(msg)
322
+ elif normalized_engine is None:
323
+ if vlc is not None:
324
+ normalized_engine = "vlconvert"
325
+ else:
326
+ msg = (
327
+ f"Saving charts in {format!r} format requires the vl-convert-python package: "
328
+ "see https://altair-viz.github.io/user_guide/saving_charts.html#png-svg-and-pdf-format"
329
+ )
330
+ raise ValueError(msg)
331
+ else:
332
+ msg = f"Invalid conversion engine {engine!r}. Expected vl-convert"
333
+ raise ValueError(msg)
334
+ return normalized_engine
335
+
336
+
337
+ def _pngxy(data):
338
+ """
339
+ Read the (width, height) from a PNG header.
340
+
341
+ Taken from IPython.display
342
+ """
343
+ ihdr = data.index(b"IHDR")
344
+ # next 8 bytes are width/height
345
+ return struct.unpack(">ii", data[ihdr + 4 : ihdr + 12])
346
+
347
+
348
+ def preprocess_embed_options(embed_options: dict) -> dict:
349
+ """
350
+ Preprocess embed options to a form compatible with Vega Embed.
351
+
352
+ Parameters
353
+ ----------
354
+ embed_options : dict
355
+ The embed options dictionary to preprocess.
356
+
357
+ Returns
358
+ -------
359
+ embed_opts : dict
360
+ The preprocessed embed options dictionary.
361
+ """
362
+ embed_options = (embed_options or {}).copy()
363
+
364
+ # Convert locale strings to objects compatible with Vega Embed using vl-convert
365
+ format_locale = embed_options.get("formatLocale", None)
366
+ if isinstance(format_locale, str):
367
+ vlc = import_vl_convert()
368
+ embed_options["formatLocale"] = vlc.get_format_locale(format_locale)
369
+
370
+ time_format_locale = embed_options.get("timeFormatLocale", None)
371
+ if isinstance(time_format_locale, str):
372
+ vlc = import_vl_convert()
373
+ embed_options["timeFormatLocale"] = vlc.get_time_format_locale(
374
+ time_format_locale
375
+ )
376
+
377
+ return embed_options
.venv/lib/python3.13/site-packages/altair/utils/plugin_registry.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from collections.abc import Callable
5
+ from functools import partial
6
+ from importlib.metadata import entry_points
7
+ from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast
8
+
9
+ from altair.utils.deprecation import deprecated_warn
10
+
11
+ if sys.version_info >= (3, 13):
12
+ from typing import TypeIs
13
+ else:
14
+ from typing_extensions import TypeIs
15
+ if sys.version_info >= (3, 12):
16
+ from typing import TypeAliasType
17
+ else:
18
+ from typing_extensions import TypeAliasType
19
+
20
+ if TYPE_CHECKING:
21
+ from types import TracebackType
22
+
23
+ T = TypeVar("T")
24
+ R = TypeVar("R")
25
+ Plugin = TypeAliasType("Plugin", Callable[..., R], type_params=(R,))
26
+ PluginT = TypeVar("PluginT", bound=Plugin[Any])
27
+ IsPlugin = Callable[[object], TypeIs[Plugin[Any]]]
28
+
29
+
30
+ def _is_type(tp: type[T], /) -> Callable[[object], TypeIs[type[T]]]:
31
+ """
32
+ Converts a type to guard function.
33
+
34
+ Added for compatibility with original `PluginRegistry` default.
35
+ """
36
+
37
+ def func(obj: object, /) -> TypeIs[type[T]]:
38
+ return isinstance(obj, tp)
39
+
40
+ return func
41
+
42
+
43
+ class NoSuchEntryPoint(Exception):
44
+ def __init__(self, group, name):
45
+ self.group = group
46
+ self.name = name
47
+
48
+ def __str__(self):
49
+ return f"No {self.name!r} entry point found in group {self.group!r}"
50
+
51
+
52
+ class PluginEnabler(Generic[PluginT, R]):
53
+ """
54
+ Context manager for enabling plugins.
55
+
56
+ This object lets you use enable() as a context manager to
57
+ temporarily enable a given plugin::
58
+
59
+ with plugins.enable("name"):
60
+ do_something() # 'name' plugin temporarily enabled
61
+ # plugins back to original state
62
+ """
63
+
64
+ def __init__(
65
+ self, registry: PluginRegistry[PluginT, R], name: str, **options: Any
66
+ ) -> None:
67
+ self.registry: PluginRegistry[PluginT, R] = registry
68
+ self.name: str = name
69
+ self.options: dict[str, Any] = options
70
+ self.original_state: dict[str, Any] = registry._get_state()
71
+ self.registry._enable(name, **options)
72
+
73
+ def __enter__(self) -> PluginEnabler[PluginT, R]:
74
+ return self
75
+
76
+ def __exit__(self, typ: type, value: Exception, traceback: TracebackType) -> None:
77
+ self.registry._set_state(self.original_state)
78
+
79
+ def __repr__(self) -> str:
80
+ return f"{type(self.registry).__name__}.enable({self.name!r})"
81
+
82
+
83
+ class PluginRegistry(Generic[PluginT, R]):
84
+ """
85
+ A registry for plugins.
86
+
87
+ This is a plugin registry that allows plugins to be loaded/registered
88
+ in two ways:
89
+
90
+ 1. Through an explicit call to ``.register(name, value)``.
91
+ 2. By looking for other Python packages that are installed and provide
92
+ a setuptools entry point group.
93
+
94
+ When you create an instance of this class, provide the name of the
95
+ entry point group to use::
96
+
97
+ reg = PluginRegister("my_entrypoint_group")
98
+
99
+ """
100
+
101
+ # this is a mapping of name to error message to allow custom error messages
102
+ # in case an entrypoint is not found
103
+ entrypoint_err_messages: dict[str, str] = {}
104
+
105
+ # global settings is a key-value mapping of settings that are stored globally
106
+ # in the registry rather than passed to the plugins
107
+ _global_settings: dict[str, Any] = {}
108
+
109
+ def __init__(
110
+ self, entry_point_group: str = "", plugin_type: IsPlugin = callable
111
+ ) -> None:
112
+ """
113
+ Create a PluginRegistry for a named entry point group.
114
+
115
+ Parameters
116
+ ----------
117
+ entry_point_group: str
118
+ The name of the entry point group.
119
+ plugin_type
120
+ A type narrowing function that will optionally be used for runtime
121
+ type checking loaded plugins.
122
+
123
+ References
124
+ ----------
125
+ https://typing.readthedocs.io/en/latest/spec/narrowing.html
126
+ """
127
+ self.entry_point_group: str = entry_point_group
128
+ self.plugin_type: IsPlugin
129
+ if plugin_type is not callable and isinstance(plugin_type, type):
130
+ msg: Any = (
131
+ f"Pass a callable `TypeIs` function to `plugin_type` instead.\n"
132
+ f"{type(self).__name__!r}(plugin_type)\n\n"
133
+ f"See also:\n"
134
+ f"https://typing.readthedocs.io/en/latest/spec/narrowing.html\n"
135
+ f"https://docs.astral.sh/ruff/rules/assert/"
136
+ )
137
+ deprecated_warn(msg, version="5.4.0")
138
+ self.plugin_type = cast("IsPlugin", _is_type(plugin_type))
139
+ else:
140
+ self.plugin_type = plugin_type
141
+ self._active: Plugin[R] | None = None
142
+ self._active_name: str = ""
143
+ self._plugins: dict[str, PluginT] = {}
144
+ self._options: dict[str, Any] = {}
145
+ self._global_settings: dict[str, Any] = self.__class__._global_settings.copy()
146
+
147
+ def register(self, name: str, value: PluginT | None) -> PluginT | None:
148
+ """
149
+ Register a plugin by name and value.
150
+
151
+ This method is used for explicit registration of a plugin and shouldn't be
152
+ used to manage entry point managed plugins, which are auto-loaded.
153
+
154
+ Parameters
155
+ ----------
156
+ name: str
157
+ The name of the plugin.
158
+ value: PluginType or None
159
+ The actual plugin object to register or None to unregister that plugin.
160
+
161
+ Returns
162
+ -------
163
+ plugin: PluginType or None
164
+ The plugin that was registered or unregistered.
165
+ """
166
+ if value is None:
167
+ return self._plugins.pop(name, None)
168
+ elif self.plugin_type(value):
169
+ self._plugins[name] = value
170
+ return value
171
+ else:
172
+ msg = f"{type(value).__name__!r} is not compatible with {type(self).__name__!r}"
173
+ raise TypeError(msg)
174
+
175
+ def names(self) -> list[str]:
176
+ """List the names of the registered and entry points plugins."""
177
+ exts = list(self._plugins.keys())
178
+ e_points = importlib_metadata_get(self.entry_point_group)
179
+ more_exts = [ep.name for ep in e_points]
180
+ exts.extend(more_exts)
181
+ return sorted(set(exts))
182
+
183
+ def _get_state(self) -> dict[str, Any]:
184
+ """Return a dictionary representing the current state of the registry."""
185
+ return {
186
+ "_active": self._active,
187
+ "_active_name": self._active_name,
188
+ "_plugins": self._plugins.copy(),
189
+ "_options": self._options.copy(),
190
+ "_global_settings": self._global_settings.copy(),
191
+ }
192
+
193
+ def _set_state(self, state: dict[str, Any]) -> None:
194
+ """Reset the state of the registry."""
195
+ assert set(state.keys()) == {
196
+ "_active",
197
+ "_active_name",
198
+ "_plugins",
199
+ "_options",
200
+ "_global_settings",
201
+ }
202
+ for key, val in state.items():
203
+ setattr(self, key, val)
204
+
205
+ def _enable(self, name: str, **options) -> None:
206
+ if name not in self._plugins:
207
+ try:
208
+ (ep,) = (
209
+ ep
210
+ for ep in importlib_metadata_get(self.entry_point_group)
211
+ if ep.name == name
212
+ )
213
+ except ValueError as err:
214
+ if name in self.entrypoint_err_messages:
215
+ raise ValueError(self.entrypoint_err_messages[name]) from err
216
+ else:
217
+ raise NoSuchEntryPoint(self.entry_point_group, name) from err
218
+ value = cast("PluginT", ep.load())
219
+ self.register(name, value)
220
+ self._active_name = name
221
+ self._active = self._plugins[name]
222
+ for key in set(options.keys()) & set(self._global_settings.keys()):
223
+ self._global_settings[key] = options.pop(key)
224
+ self._options = options
225
+
226
+ def enable(
227
+ self, name: str | None = None, **options: Any
228
+ ) -> PluginEnabler[PluginT, R]:
229
+ """
230
+ Enable a plugin by name.
231
+
232
+ This can be either called directly, or used as a context manager.
233
+
234
+ Parameters
235
+ ----------
236
+ name : string (optional)
237
+ The name of the plugin to enable. If not specified, then use the
238
+ current active name.
239
+ **options :
240
+ Any additional parameters will be passed to the plugin as keyword
241
+ arguments
242
+
243
+ Returns
244
+ -------
245
+ PluginEnabler:
246
+ An object that allows enable() to be used as a context manager
247
+ """
248
+ if name is None:
249
+ name = self.active
250
+ return PluginEnabler(self, name, **options)
251
+
252
+ @property
253
+ def active(self) -> str:
254
+ """Return the name of the currently active plugin."""
255
+ return self._active_name
256
+
257
+ @property
258
+ def options(self) -> dict[str, Any]:
259
+ """Return the current options dictionary."""
260
+ return self._options
261
+
262
+ def get(self) -> partial[R] | Plugin[R] | None:
263
+ """Return the currently active plugin."""
264
+ if (func := self._active) and self.plugin_type(func):
265
+ return partial(func, **self._options) if self._options else func
266
+ elif self._active is not None:
267
+ msg = (
268
+ f"{type(self).__name__!r} requires all plugins to be callable objects, "
269
+ f"but {type(self._active).__name__!r} is not callable."
270
+ )
271
+ raise TypeError(msg)
272
+ elif TYPE_CHECKING:
273
+ # NOTE: The `None` return is implicit, but `mypy` isn't satisfied
274
+ # - `ruff` will factor out explicit `None` return
275
+ # - `pyright` has no issue
276
+ raise NotImplementedError
277
+
278
+ def __repr__(self) -> str:
279
+ return f"{type(self).__name__}(active={self.active!r}, registered={self.names()!r})"
280
+
281
+
282
+ def importlib_metadata_get(group):
283
+ ep = entry_points()
284
+ # 'select' was introduced in Python 3.10 and 'get' got deprecated
285
+ # We don't check for Python version here as by checking with hasattr we
286
+ # also get compatibility with the importlib_metadata package which had a different
287
+ # deprecation cycle for 'get'
288
+ if hasattr(ep, "select"):
289
+ return ep.select(group=group) # pyright: ignore
290
+ else:
291
+ return ep.get(group, [])
.venv/lib/python3.13/site-packages/altair/utils/save.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import pathlib
5
+ import warnings
6
+ from typing import IO, TYPE_CHECKING, Any, Literal
7
+
8
+ from altair.utils._vegafusion_data import using_vegafusion
9
+ from altair.utils.deprecation import deprecated_warn
10
+ from altair.vegalite.v6.data import data_transformers
11
+
12
+ from .mimebundle import spec_to_mimebundle
13
+
14
+ if TYPE_CHECKING:
15
+ from pathlib import Path
16
+
17
+
18
+ def write_file_or_filename(
19
+ fp: str | Path | IO,
20
+ content: str | bytes,
21
+ mode: str = "w",
22
+ encoding: str | None = None,
23
+ ) -> None:
24
+ """Write content to fp, whether fp is a string, a pathlib Path or a file-like object."""
25
+ if isinstance(fp, (str, pathlib.Path)):
26
+ with pathlib.Path(fp).open(mode=mode, encoding=encoding) as f:
27
+ f.write(content)
28
+ else:
29
+ fp.write(content)
30
+
31
+
32
+ def set_inspect_format_argument(
33
+ format: str | None, fp: str | Path | IO, inline: bool
34
+ ) -> str:
35
+ """Inspect the format argument in the save function."""
36
+ if format is None:
37
+ if isinstance(fp, (str, pathlib.Path)):
38
+ format = pathlib.Path(fp).suffix.lstrip(".")
39
+ else:
40
+ msg = (
41
+ "must specify file format: "
42
+ "['png', 'svg', 'pdf', 'html', 'json', 'vega']"
43
+ )
44
+ raise ValueError(msg)
45
+
46
+ if format != "html" and inline:
47
+ warnings.warn("inline argument ignored for non HTML formats.", stacklevel=1)
48
+
49
+ return format
50
+
51
+
52
+ def set_inspect_mode_argument(
53
+ mode: Literal["vega-lite"] | None,
54
+ embed_options: dict[str, Any],
55
+ spec: dict[str, Any],
56
+ vegalite_version: str | None,
57
+ ) -> Literal["vega-lite"]:
58
+ """Inspect the mode argument in the save function."""
59
+ if mode is None:
60
+ if "mode" in embed_options:
61
+ mode = embed_options["mode"]
62
+ elif "$schema" in spec:
63
+ mode = spec["$schema"].split("/")[-2]
64
+ else:
65
+ mode = "vega-lite"
66
+
67
+ if mode != "vega-lite":
68
+ msg = f"mode must be 'vega-lite', not '{mode}'"
69
+ raise ValueError(msg)
70
+
71
+ if mode == "vega-lite" and vegalite_version is None:
72
+ msg = "must specify vega-lite version"
73
+ raise ValueError(msg)
74
+
75
+ return mode
76
+
77
+
78
+ def _save_mimebundle_format(
79
+ spec: dict[str, Any],
80
+ format: Literal["html", "png", "svg", "pdf", "vega"],
81
+ fp: str | Path | IO,
82
+ inner_mode: Literal["vega-lite"],
83
+ vega_version: str | None,
84
+ vegalite_version: str | None,
85
+ vegaembed_version: str | None,
86
+ embed_options: dict[str, Any] | None,
87
+ json_kwds: dict[str, Any],
88
+ encoding: str,
89
+ scale_factor: float,
90
+ engine: Literal["vl-convert"] | None,
91
+ inline: bool,
92
+ **kwargs: Any,
93
+ ) -> None:
94
+ """Save chart using spec_to_mimebundle for formats that require it."""
95
+ if format == "html":
96
+ if inline:
97
+ kwargs["template"] = "inline"
98
+ mb_result: dict[str, str] = spec_to_mimebundle(
99
+ spec=spec,
100
+ format=format,
101
+ mode=inner_mode,
102
+ vega_version=vega_version,
103
+ vegalite_version=vegalite_version,
104
+ vegaembed_version=vegaembed_version,
105
+ embed_options=embed_options,
106
+ json_kwds=json_kwds,
107
+ **kwargs,
108
+ )
109
+ write_file_or_filename(fp, mb_result["text/html"], mode="w", encoding=encoding)
110
+ elif format == "png":
111
+ mb_result_png: tuple[dict[str, Any], dict[str, Any]] = spec_to_mimebundle(
112
+ spec=spec,
113
+ format=format,
114
+ mode=inner_mode,
115
+ vega_version=vega_version,
116
+ vegalite_version=vegalite_version,
117
+ vegaembed_version=vegaembed_version,
118
+ embed_options=embed_options,
119
+ scale_factor=scale_factor,
120
+ engine=engine,
121
+ **kwargs,
122
+ )
123
+ write_file_or_filename(fp, mb_result_png[0]["image/png"], mode="wb")
124
+ elif format == "svg":
125
+ mb_result = spec_to_mimebundle(
126
+ spec=spec,
127
+ format=format,
128
+ mode=inner_mode,
129
+ vega_version=vega_version,
130
+ vegalite_version=vegalite_version,
131
+ vegaembed_version=vegaembed_version,
132
+ embed_options=embed_options,
133
+ scale_factor=scale_factor,
134
+ engine=engine,
135
+ **kwargs,
136
+ )
137
+ write_file_or_filename(
138
+ fp, mb_result["image/svg+xml"], mode="w", encoding=encoding
139
+ )
140
+ elif format == "pdf":
141
+ mb_result = spec_to_mimebundle(
142
+ spec=spec,
143
+ format=format,
144
+ mode=inner_mode,
145
+ vega_version=vega_version,
146
+ vegalite_version=vegalite_version,
147
+ vegaembed_version=vegaembed_version,
148
+ embed_options=embed_options,
149
+ scale_factor=scale_factor,
150
+ engine=engine,
151
+ **kwargs,
152
+ )
153
+ write_file_or_filename(fp, mb_result["application/pdf"], mode="wb")
154
+ else: # vega
155
+ mb_result = spec_to_mimebundle(
156
+ spec=spec,
157
+ format=format,
158
+ mode=inner_mode,
159
+ vega_version=vega_version,
160
+ vegalite_version=vegalite_version,
161
+ vegaembed_version=vegaembed_version,
162
+ embed_options=embed_options,
163
+ scale_factor=scale_factor,
164
+ engine=engine,
165
+ **kwargs,
166
+ )
167
+ json_spec = json.dumps(mb_result["application/vnd.vega.v6+json"], **json_kwds)
168
+ write_file_or_filename(fp, json_spec, mode="w", encoding=encoding)
169
+
170
+
171
+ def save(
172
+ chart,
173
+ fp: str | Path | IO,
174
+ vega_version: str | None,
175
+ vegaembed_version: str | None,
176
+ format: Literal["json", "html", "png", "svg", "pdf", "vega"] | None = None,
177
+ mode: Literal["vega-lite"] | None = None,
178
+ vegalite_version: str | None = None,
179
+ embed_options: dict | None = None,
180
+ json_kwds: dict | None = None,
181
+ scale_factor: float = 1,
182
+ engine: Literal["vl-convert"] | None = None,
183
+ inline: bool = False,
184
+ **kwargs,
185
+ ) -> None:
186
+ """
187
+ Save a chart to file in a variety of formats.
188
+
189
+ Supported formats are [json, html, png, svg, pdf, vega]
190
+
191
+ Parameters
192
+ ----------
193
+ chart : alt.Chart
194
+ the chart instance to save
195
+ fp : string filename, pathlib.Path or file-like object
196
+ file to which to write the chart.
197
+ format : string (optional)
198
+ the format to write: one of ['json', 'html', 'png', 'svg', 'pdf', 'vega'].
199
+ If not specified, the format will be determined from the filename.
200
+ mode : string (optional)
201
+ Must be 'vega-lite'. If not specified, then infer the mode from
202
+ the '$schema' property of the spec, or the ``opt`` dictionary.
203
+ If it's not specified in either of those places, then use 'vega-lite'.
204
+ vega_version : string (optional)
205
+ For html output, the version of vega.js to use
206
+ vegalite_version : string (optional)
207
+ For html output, the version of vegalite.js to use
208
+ vegaembed_version : string (optional)
209
+ For html output, the version of vegaembed.js to use
210
+ embed_options : dict (optional)
211
+ The vegaEmbed options dictionary. Default is {}
212
+ (See https://github.com/vega/vega-embed for details)
213
+ json_kwds : dict (optional)
214
+ Additional keyword arguments are passed to the output method
215
+ associated with the specified format.
216
+ scale_factor : float (optional)
217
+ scale_factor to use to change size/resolution of png or svg output
218
+ engine: string {'vl-convert'}
219
+ the conversion engine to use for 'png', 'svg', 'pdf', and 'vega' formats
220
+ inline: bool (optional)
221
+ If False (default), the required JavaScript libraries are loaded
222
+ from a CDN location in the resulting html file.
223
+ If True, the required JavaScript libraries are inlined into the resulting
224
+ html file so that it will work without an internet connection.
225
+ The vl-convert-python package is required if True.
226
+ **kwargs :
227
+ additional kwargs passed to spec_to_mimebundle.
228
+ """
229
+ if _ := kwargs.pop("webdriver", None):
230
+ deprecated_warn(
231
+ "The webdriver argument is not relevant for the new vl-convert engine which replaced altair_saver. "
232
+ "The argument will be removed in a future release.",
233
+ version="5.0.0",
234
+ )
235
+
236
+ json_kwds = json_kwds or {}
237
+ encoding = kwargs.get("encoding", "utf-8")
238
+ format = set_inspect_format_argument(format, fp, inline) # type: ignore[assignment]
239
+
240
+ def perform_save() -> None:
241
+ spec = chart.to_dict(context={"pre_transform": False})
242
+
243
+ inner_mode = set_inspect_mode_argument(
244
+ mode, embed_options or {}, spec, vegalite_version
245
+ )
246
+
247
+ if format == "json":
248
+ json_spec = json.dumps(spec, **json_kwds)
249
+ write_file_or_filename(fp, json_spec, mode="w", encoding=encoding)
250
+ elif format in {"html", "png", "svg", "pdf", "vega"}:
251
+ _save_mimebundle_format(
252
+ spec=spec,
253
+ format=format,
254
+ fp=fp,
255
+ inner_mode=inner_mode,
256
+ vega_version=vega_version,
257
+ vegalite_version=vegalite_version,
258
+ vegaembed_version=vegaembed_version,
259
+ embed_options=embed_options,
260
+ json_kwds=json_kwds,
261
+ encoding=encoding,
262
+ scale_factor=scale_factor,
263
+ engine=engine,
264
+ inline=inline,
265
+ **kwargs,
266
+ )
267
+ else:
268
+ msg = f"Unsupported format: '{format}'"
269
+ raise ValueError(msg)
270
+
271
+ if using_vegafusion():
272
+ # When the vegafusion data transformer is enabled, transforms will be
273
+ # evaluated during save and the resulting data will be included in the
274
+ # vega specification that is saved.
275
+ with data_transformers.disable_max_rows():
276
+ perform_save()
277
+ else:
278
+ # Temporarily turn off any data transformers so that all data is inlined
279
+ # when calling chart.to_dict. This is relevant for vl-convert which cannot access
280
+ # local json files which could be created by a json data transformer. Furthermore,
281
+ # we don't exit the with statement until this function completed due to the issue
282
+ # described at https://github.com/vega/vl-convert/issues/31
283
+ with data_transformers.enable("default"), data_transformers.disable_max_rows():
284
+ perform_save()
.venv/lib/python3.13/site-packages/altair/utils/schemapi.py ADDED
@@ -0,0 +1,1710 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The contents of this file are automatically written by
2
+ # tools/generate_schema_wrapper.py. Do not modify directly.
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import copy
7
+ import datetime as dt
8
+ import inspect
9
+ import json
10
+ import operator
11
+ import sys
12
+ import textwrap
13
+ from collections import defaultdict
14
+ from collections.abc import Iterable, Iterator, Mapping, Sequence
15
+ from functools import partial
16
+ from importlib.metadata import version as importlib_version
17
+ from itertools import chain, zip_longest
18
+ from math import ceil
19
+ from typing import (
20
+ TYPE_CHECKING,
21
+ Any,
22
+ Final,
23
+ Generic,
24
+ Literal,
25
+ TypeVar,
26
+ Union,
27
+ cast,
28
+ overload,
29
+ )
30
+
31
+ import jsonschema
32
+ import jsonschema.exceptions
33
+ import jsonschema.validators
34
+ import narwhals.stable.v1 as nw
35
+ from narwhals.stable.v1.dependencies import is_narwhals_series
36
+ from packaging.version import Version
37
+
38
+ if sys.version_info >= (3, 12):
39
+ from typing import Protocol, TypeAliasType, runtime_checkable
40
+ else:
41
+ from typing_extensions import Protocol, TypeAliasType, runtime_checkable
42
+
43
+ if TYPE_CHECKING:
44
+ from types import ModuleType
45
+ from typing import ClassVar
46
+
47
+ from jsonschema.exceptions import ValidationError
48
+ from referencing import Registry
49
+
50
+ from altair.typing import ChartType
51
+
52
+ if sys.version_info >= (3, 13):
53
+ from typing import TypeIs
54
+ else:
55
+ from typing_extensions import TypeIs
56
+
57
+ if sys.version_info >= (3, 11):
58
+ from typing import Never, Self
59
+ else:
60
+ from typing_extensions import Never, Self
61
+ if sys.version_info >= (3, 10):
62
+ from typing import TypeAlias
63
+ else:
64
+ from typing_extensions import TypeAlias
65
+
66
+ _OptionalModule: TypeAlias = "ModuleType | None"
67
+
68
+ ValidationErrorList: TypeAlias = list[jsonschema.exceptions.ValidationError]
69
+ GroupedValidationErrors: TypeAlias = dict[str, ValidationErrorList]
70
+
71
+ # This URI is arbitrary and could be anything else. It just cannot be an empty
72
+ # string as we need to reference the schema registered in
73
+ # the referencing.Registry.
74
+ _VEGA_LITE_ROOT_URI: Final = "urn:vega-lite-schema"
75
+
76
+ # Ideally, jsonschema specification would be parsed from the current Vega-Lite
77
+ # schema instead of being hardcoded here as a default value.
78
+ # However, due to circular imports between this module and the altair.vegalite
79
+ # modules, this information is not yet available at this point as altair.vegalite
80
+ # is only partially loaded. The draft version which is used is unlikely to
81
+ # change often so it's ok to keep this. There is also a test which validates
82
+ # that this value is always the same as in the Vega-Lite schema.
83
+ _DEFAULT_JSON_SCHEMA_DRAFT_URL: Final = "http://json-schema.org/draft-07/schema#"
84
+
85
+
86
+ # If DEBUG_MODE is True, then schema objects are converted to dict and
87
+ # validated at creation time. This slows things down, particularly for
88
+ # larger specs, but leads to much more useful tracebacks for the user.
89
+ # Individual schema classes can override this by setting the
90
+ # class-level _class_is_valid_at_instantiation attribute to False
91
+ DEBUG_MODE: bool = True
92
+
93
+ jsonschema_version_str = importlib_version("jsonschema")
94
+
95
+
96
+ def enable_debug_mode() -> None:
97
+ global DEBUG_MODE
98
+ DEBUG_MODE = True
99
+
100
+
101
+ def disable_debug_mode() -> None:
102
+ global DEBUG_MODE
103
+ DEBUG_MODE = False
104
+
105
+
106
+ @contextlib.contextmanager
107
+ def debug_mode(arg: bool) -> Iterator[None]:
108
+ global DEBUG_MODE
109
+ original = DEBUG_MODE
110
+ DEBUG_MODE = arg
111
+ try:
112
+ yield
113
+ finally:
114
+ DEBUG_MODE = original
115
+
116
+
117
+ @overload
118
+ def validate_jsonschema(
119
+ spec: Any,
120
+ schema: dict[str, Any],
121
+ rootschema: dict[str, Any] | None = ...,
122
+ *,
123
+ raise_error: Literal[True] = ...,
124
+ ) -> Never: ...
125
+
126
+
127
+ @overload
128
+ def validate_jsonschema(
129
+ spec: Any,
130
+ schema: dict[str, Any],
131
+ rootschema: dict[str, Any] | None = ...,
132
+ *,
133
+ raise_error: Literal[False],
134
+ ) -> jsonschema.exceptions.ValidationError | None: ...
135
+
136
+
137
+ def validate_jsonschema(
138
+ spec,
139
+ schema: dict[str, Any],
140
+ rootschema: dict[str, Any] | None = None,
141
+ *,
142
+ raise_error: bool = True,
143
+ ) -> jsonschema.exceptions.ValidationError | None:
144
+ """
145
+ Validates the passed in spec against the schema in the context of the rootschema.
146
+
147
+ If any errors are found, they are deduplicated and prioritized
148
+ and only the most relevant errors are kept. Errors are then either raised
149
+ or returned, depending on the value of `raise_error`.
150
+ """
151
+ errors = _get_errors_from_spec(spec, schema, rootschema=rootschema)
152
+ if errors:
153
+ leaf_errors = _get_leaves_of_error_tree(errors)
154
+ grouped_errors = _group_errors_by_json_path(leaf_errors)
155
+ grouped_errors = _subset_to_most_specific_json_paths(grouped_errors)
156
+ grouped_errors = _deduplicate_errors(grouped_errors)
157
+
158
+ # Nothing special about this first error but we need to choose one
159
+ # which can be raised
160
+ main_error: Any = next(iter(grouped_errors.values()))[0]
161
+ # All errors are then attached as a new attribute to ValidationError so that
162
+ # they can be used in SchemaValidationError to craft a more helpful
163
+ # error message. Setting a new attribute like this is not ideal as
164
+ # it then no longer matches the type ValidationError. It would be better
165
+ # to refactor this function to never raise but only return errors.
166
+ main_error._all_errors = grouped_errors
167
+ if raise_error:
168
+ raise main_error
169
+ else:
170
+ return main_error
171
+ else:
172
+ return None
173
+
174
+
175
+ def _get_errors_from_spec(
176
+ spec: dict[str, Any],
177
+ schema: dict[str, Any],
178
+ rootschema: dict[str, Any] | None = None,
179
+ ) -> ValidationErrorList:
180
+ """
181
+ Uses the relevant jsonschema validator to validate the passed in spec against the schema using the rootschema to resolve references.
182
+
183
+ The schema and rootschema themselves are not validated but instead considered as valid.
184
+ """
185
+ # We don't use jsonschema.validate as this would validate the schema itself.
186
+ # Instead, we pass the schema directly to the validator class. This is done for
187
+ # two reasons: The schema comes from Vega-Lite and is not based on the user
188
+ # input, therefore there is no need to validate it in the first place. Furthermore,
189
+ # the "uri-reference" format checker fails for some of the references as URIs in
190
+ # "$ref" are not encoded,
191
+ # e.g. '#/definitions/ValueDefWithCondition<MarkPropFieldOrDatumDef,
192
+ # (Gradient|string|null)>' would be a valid $ref in a Vega-Lite schema but
193
+ # it is not a valid URI reference due to the characters such as '<'.
194
+
195
+ json_schema_draft_url = _get_json_schema_draft_url(rootschema or schema)
196
+ validator_cls = jsonschema.validators.validator_for(
197
+ {"$schema": json_schema_draft_url}
198
+ )
199
+ validator_kwargs: dict[str, Any] = {}
200
+ if hasattr(validator_cls, "FORMAT_CHECKER"):
201
+ validator_kwargs["format_checker"] = validator_cls.FORMAT_CHECKER
202
+
203
+ if _use_referencing_library():
204
+ schema = _prepare_references_in_schema(schema)
205
+ validator_kwargs["registry"] = _get_referencing_registry(
206
+ rootschema or schema, json_schema_draft_url
207
+ )
208
+
209
+ else:
210
+ # No resolver is necessary if the schema is already the full schema
211
+ validator_kwargs["resolver"] = (
212
+ jsonschema.RefResolver.from_schema(rootschema)
213
+ if rootschema is not None
214
+ else None
215
+ )
216
+
217
+ validator = validator_cls(schema, **validator_kwargs)
218
+ errors = list(validator.iter_errors(spec))
219
+ return errors
220
+
221
+
222
+ def _get_json_schema_draft_url(schema: dict[str, Any]) -> str:
223
+ return schema.get("$schema", _DEFAULT_JSON_SCHEMA_DRAFT_URL)
224
+
225
+
226
+ def _use_referencing_library() -> bool:
227
+ """In version 4.18.0, the jsonschema package deprecated RefResolver in favor of the referencing library."""
228
+ return Version(jsonschema_version_str) >= Version("4.18")
229
+
230
+
231
+ def _prepare_references_in_schema(schema: dict[str, Any]) -> dict[str, Any]:
232
+ # Create a copy so that $ref is not modified in the original schema in case
233
+ # that it would still reference a dictionary which might be attached to
234
+ # an Altair class _schema attribute
235
+ schema = copy.deepcopy(schema)
236
+
237
+ def _prepare_refs(d: dict[str, Any]) -> dict[str, Any]:
238
+ """
239
+ Add _VEGA_LITE_ROOT_URI in front of all $ref values.
240
+
241
+ This function recursively iterates through the whole dictionary.
242
+
243
+ $ref values can only be nested in dictionaries or lists
244
+ as the passed in `d` dictionary comes from the Vega-Lite json schema
245
+ and in json we only have arrays (-> lists in Python) and objects
246
+ (-> dictionaries in Python) which we need to iterate through.
247
+ """
248
+ for key, value in d.items():
249
+ if key == "$ref":
250
+ d[key] = _VEGA_LITE_ROOT_URI + d[key]
251
+ elif isinstance(value, dict):
252
+ d[key] = _prepare_refs(value)
253
+ elif isinstance(value, list):
254
+ prepared_values = []
255
+ for v in value:
256
+ if isinstance(v, dict):
257
+ v = _prepare_refs(v)
258
+ prepared_values.append(v)
259
+ d[key] = prepared_values
260
+ return d
261
+
262
+ schema = _prepare_refs(schema)
263
+ return schema
264
+
265
+
266
+ # We do not annotate the return value here as the referencing library is not always
267
+ # available and this function is only executed in those cases.
268
+ def _get_referencing_registry(
269
+ rootschema: dict[str, Any], json_schema_draft_url: str | None = None
270
+ ) -> Registry:
271
+ # Referencing is a dependency of newer jsonschema versions, starting with the
272
+ # version that is specified in _use_referencing_library and we therefore
273
+ # can expect that it is installed if the function returns True.
274
+ # We ignore 'import' mypy errors which happen when the referencing library
275
+ # is not installed. That's ok as in these cases this function is not called.
276
+ # We also have to ignore 'unused-ignore' errors as mypy raises those in case
277
+ # referencing is installed.
278
+ import referencing # type: ignore[import,unused-ignore]
279
+ import referencing.jsonschema # type: ignore[import,unused-ignore]
280
+
281
+ if json_schema_draft_url is None:
282
+ json_schema_draft_url = _get_json_schema_draft_url(rootschema)
283
+
284
+ specification = referencing.jsonschema.specification_with(json_schema_draft_url)
285
+ resource = specification.create_resource(rootschema)
286
+ return referencing.Registry().with_resource(
287
+ uri=_VEGA_LITE_ROOT_URI, resource=resource
288
+ )
289
+
290
+
291
+ def _json_path(err: jsonschema.exceptions.ValidationError) -> str:
292
+ """
293
+ Drop in replacement for the .json_path property of the jsonschema ValidationError class.
294
+
295
+ This is not available as property for ValidationError with jsonschema<4.0.1.
296
+
297
+ More info, see https://github.com/vega/altair/issues/3038.
298
+ """
299
+ path = "$"
300
+ for elem in err.absolute_path:
301
+ if isinstance(elem, int):
302
+ path += "[" + str(elem) + "]"
303
+ else:
304
+ path += "." + elem
305
+ return path
306
+
307
+
308
+ def _group_errors_by_json_path(
309
+ errors: ValidationErrorList,
310
+ ) -> GroupedValidationErrors:
311
+ """
312
+ Groups errors by the `json_path` attribute of the jsonschema ValidationError class.
313
+
314
+ This attribute contains the path to the offending element within
315
+ a chart specification and can therefore be considered as an identifier of an
316
+ 'issue' in the chart that needs to be fixed.
317
+ """
318
+ errors_by_json_path = defaultdict(list)
319
+ for err in errors:
320
+ err_key = getattr(err, "json_path", _json_path(err))
321
+ errors_by_json_path[err_key].append(err)
322
+ return dict(errors_by_json_path)
323
+
324
+
325
+ def _get_leaves_of_error_tree(
326
+ errors: ValidationErrorList,
327
+ ) -> ValidationErrorList:
328
+ """
329
+ For each error in `errors`, it traverses down the "error tree" that is generated by the jsonschema library to find and return all "leaf" errors.
330
+
331
+ These are errors which have no further errors that caused it and so they are the most specific errors
332
+ with the most specific error messages.
333
+ """
334
+ leaves: ValidationErrorList = []
335
+ for err in errors:
336
+ if err.context:
337
+ # This means that the error `err` was caused by errors in subschemas.
338
+ # The list of errors from the subschemas are available in the property
339
+ # `context`.
340
+ leaves.extend(_get_leaves_of_error_tree(err.context))
341
+ else:
342
+ leaves.append(err)
343
+ return leaves
344
+
345
+
346
+ def _subset_to_most_specific_json_paths(
347
+ errors_by_json_path: GroupedValidationErrors,
348
+ ) -> GroupedValidationErrors:
349
+ """
350
+ Removes key (json path), value (errors) pairs where the json path is fully contained in another json path.
351
+
352
+ For example if `errors_by_json_path` has two keys, `$.encoding.X` and `$.encoding.X.tooltip`,
353
+ then the first one will be removed and only the second one is returned.
354
+
355
+ This is done under the assumption that more specific json paths give more helpful error messages to the user.
356
+ """
357
+ errors_by_json_path_specific: GroupedValidationErrors = {}
358
+ for json_path, errors in errors_by_json_path.items():
359
+ if not _contained_at_start_of_one_of_other_values(
360
+ json_path, list(errors_by_json_path.keys())
361
+ ):
362
+ errors_by_json_path_specific[json_path] = errors
363
+ return errors_by_json_path_specific
364
+
365
+
366
+ def _contained_at_start_of_one_of_other_values(x: str, values: Sequence[str]) -> bool:
367
+ # Does not count as "contained at start of other value" if the values are
368
+ # the same. These cases should be handled separately
369
+ return any(value.startswith(x) for value in values if x != value)
370
+
371
+
372
+ def _deduplicate_errors(
373
+ grouped_errors: GroupedValidationErrors,
374
+ ) -> GroupedValidationErrors:
375
+ """
376
+ Some errors have very similar error messages or are just in general not helpful for a user.
377
+
378
+ This function removes as many of these cases as possible and
379
+ can be extended over time to handle new cases that come up.
380
+ """
381
+ grouped_errors_deduplicated: GroupedValidationErrors = {}
382
+ for json_path, element_errors in grouped_errors.items():
383
+ errors_by_validator = _group_errors_by_validator(element_errors)
384
+
385
+ deduplication_functions = {
386
+ "enum": _deduplicate_enum_errors,
387
+ "additionalProperties": _deduplicate_additional_properties_errors,
388
+ }
389
+ deduplicated_errors: ValidationErrorList = []
390
+ for validator, errors in errors_by_validator.items():
391
+ deduplication_func = deduplication_functions.get(validator)
392
+ if deduplication_func is not None:
393
+ errors = deduplication_func(errors)
394
+ deduplicated_errors.extend(_deduplicate_by_message(errors))
395
+
396
+ # Removes any ValidationError "'value' is a required property" as these
397
+ # errors are unlikely to be the relevant ones for the user. They come from
398
+ # validation against a schema definition where the output of `alt.value`
399
+ # would be valid. However, if a user uses `alt.value`, the `value` keyword
400
+ # is included automatically from that function and so it's unlikely
401
+ # that this was what the user intended if the keyword is not present
402
+ # in the first place.
403
+ deduplicated_errors = [
404
+ err for err in deduplicated_errors if not _is_required_value_error(err)
405
+ ]
406
+
407
+ grouped_errors_deduplicated[json_path] = deduplicated_errors
408
+ return grouped_errors_deduplicated
409
+
410
+
411
+ def _is_required_value_error(err: jsonschema.exceptions.ValidationError) -> bool:
412
+ return err.validator == "required" and err.validator_value == ["value"]
413
+
414
+
415
+ def _group_errors_by_validator(errors: ValidationErrorList) -> GroupedValidationErrors:
416
+ """
417
+ Groups the errors by the json schema "validator" that caused the error.
418
+
419
+ For example if the error is that a value is not one of an enumeration in the json schema
420
+ then the "validator" is `"enum"`, if the error is due to an unknown property that
421
+ was set although no additional properties are allowed then "validator" is
422
+ `"additionalProperties`, etc.
423
+ """
424
+ errors_by_validator: defaultdict[str, ValidationErrorList] = defaultdict(list)
425
+ for err in errors:
426
+ # Ignore mypy error as err.validator as it wrongly sees err.validator
427
+ # as of type Optional[Validator] instead of str which it is according
428
+ # to the documentation and all tested cases
429
+ errors_by_validator[err.validator].append(err) # type: ignore[index]
430
+ return dict(errors_by_validator)
431
+
432
+
433
+ def _deduplicate_enum_errors(errors: ValidationErrorList) -> ValidationErrorList:
434
+ """
435
+ Deduplicate enum errors by removing the errors where the allowed values are a subset of another error.
436
+
437
+ For example, if `enum` contains two errors and one has `validator_value` (i.e. accepted values) ["A", "B"] and the
438
+ other one ["A", "B", "C"] then the first one is removed and the final
439
+ `enum` list only contains the error with ["A", "B", "C"].
440
+ """
441
+ if len(errors) > 1:
442
+ # Values (and therefore `validator_value`) of an enum are always arrays,
443
+ # see https://json-schema.org/understanding-json-schema/reference/generic.html#enumerated-values
444
+ # which is why we can use join below
445
+ value_strings = [",".join(err.validator_value) for err in errors] # type: ignore
446
+ longest_enums: ValidationErrorList = []
447
+ for value_str, err in zip(value_strings, errors):
448
+ if not _contained_at_start_of_one_of_other_values(value_str, value_strings):
449
+ longest_enums.append(err)
450
+ errors = longest_enums
451
+ return errors
452
+
453
+
454
+ def _deduplicate_additional_properties_errors(
455
+ errors: ValidationErrorList,
456
+ ) -> ValidationErrorList:
457
+ """
458
+ If there are multiple additional property errors it usually means that the offending element was validated against multiple schemas and its parent is a common anyOf validator.
459
+
460
+ The error messages produced from these cases are usually
461
+ very similar and we just take the shortest one. For example,
462
+ the following 3 errors are raised for the `unknown` channel option in
463
+ `alt.X("variety", unknown=2)`:
464
+ - "Additional properties are not allowed ('unknown' was unexpected)"
465
+ - "Additional properties are not allowed ('field', 'unknown' were unexpected)"
466
+ - "Additional properties are not allowed ('field', 'type', 'unknown' were unexpected)".
467
+ """
468
+ if len(errors) > 1:
469
+ # Test if all parent errors are the same anyOf error and only do
470
+ # the prioritization in these cases. Can't think of a chart spec where this
471
+ # would not be the case but still allow for it below to not break anything.
472
+ parent = errors[0].parent
473
+ if (
474
+ parent is not None
475
+ and parent.validator == "anyOf"
476
+ # Use [1:] as don't have to check for first error as it was used
477
+ # above to define `parent`
478
+ and all(err.parent is parent for err in errors[1:])
479
+ ):
480
+ errors = [min(errors, key=lambda x: len(x.message))]
481
+ return errors
482
+
483
+
484
+ def _deduplicate_by_message(errors: ValidationErrorList) -> ValidationErrorList:
485
+ """Deduplicate errors by message. This keeps the original order in case it was chosen intentionally."""
486
+ return list({e.message: e for e in errors}.values())
487
+
488
+
489
+ def _subclasses(cls: type[Any]) -> Iterator[type[Any]]:
490
+ """Breadth-first sequence of all classes which inherit from cls."""
491
+ seen = {cls}
492
+ current_set = {cls}
493
+ while current_set:
494
+ next_set = set()
495
+ for base in current_set:
496
+ for sub in base.__subclasses__():
497
+ if sub not in seen:
498
+ yield sub
499
+ seen.add(sub)
500
+ next_set.add(sub)
501
+ current_set = next_set
502
+
503
+
504
+ def _from_array_like(obj: Iterable[Any], /) -> list[Any]:
505
+ # TODO @dangotbanned: Review after available (https://github.com/narwhals-dev/narwhals/pull/2110)
506
+ # See for what this silences for `narwhals` CI (https://github.com/narwhals-dev/narwhals/pull/2110#issuecomment-2687936504)
507
+ maybe_ser: Any = nw.from_native(obj, pass_through=True)
508
+ return maybe_ser.to_list() if is_narwhals_series(maybe_ser) else list(obj)
509
+
510
+
511
+ def _from_date_datetime(obj: dt.date | dt.datetime, /) -> dict[str, Any]:
512
+ """
513
+ Parse native `datetime.(date|datetime)` into a `DateTime`_ schema.
514
+
515
+ .. _DateTime:
516
+ https://vega.github.io/vega-lite/docs/datetime.html
517
+ """
518
+ result: dict[str, Any] = {"year": obj.year, "month": obj.month, "date": obj.day}
519
+ if isinstance(obj, dt.datetime):
520
+ if obj.time() != dt.time.min:
521
+ us = obj.microsecond
522
+ ms = us if us == 0 else us // 1_000
523
+ result.update(
524
+ hours=obj.hour, minutes=obj.minute, seconds=obj.second, milliseconds=ms
525
+ )
526
+ if tzinfo := obj.tzinfo:
527
+ if tzinfo is dt.timezone.utc:
528
+ result["utc"] = True
529
+ else:
530
+ msg = (
531
+ f"Unsupported timezone {tzinfo!r}.\n"
532
+ "Only `'UTC'` or naive (local) datetimes are permitted.\n"
533
+ "See https://altair-viz.github.io/user_guide/generated/core/altair.DateTime.html"
534
+ )
535
+ raise TypeError(msg)
536
+ return result
537
+
538
+
539
+ def _todict(obj: Any, context: dict[str, Any] | None, np_opt: Any, pd_opt: Any) -> Any: # noqa: C901
540
+ """Convert an object to a dict representation."""
541
+ if np_opt is not None:
542
+ np = np_opt
543
+ if isinstance(obj, np.ndarray):
544
+ return [_todict(v, context, np_opt, pd_opt) for v in obj]
545
+ elif isinstance(obj, np.number):
546
+ return float(obj)
547
+ elif isinstance(obj, np.datetime64):
548
+ result = str(obj)
549
+ if "T" not in result:
550
+ # See https://github.com/vega/altair/issues/1027 for why this is necessary.
551
+ result += "T00:00:00"
552
+ return result
553
+ if isinstance(obj, SchemaBase):
554
+ return obj.to_dict(validate=False, context=context)
555
+ elif isinstance(obj, (list, tuple)):
556
+ return [_todict(v, context, np_opt, pd_opt) for v in obj]
557
+ elif isinstance(obj, dict):
558
+ return {
559
+ k: _todict(v, context, np_opt, pd_opt)
560
+ for k, v in obj.items()
561
+ if v is not Undefined
562
+ }
563
+ elif isinstance(obj, SchemaLike):
564
+ return obj.to_dict()
565
+ elif pd_opt is not None and isinstance(obj, pd_opt.Timestamp):
566
+ return pd_opt.Timestamp(obj).isoformat()
567
+ elif _is_iterable(obj, exclude=(str, bytes)):
568
+ return _todict(_from_array_like(obj), context, np_opt, pd_opt)
569
+ elif isinstance(obj, dt.date):
570
+ return _from_date_datetime(obj)
571
+ else:
572
+ return obj
573
+
574
+
575
+ def _resolve_references(
576
+ schema: dict[str, Any], rootschema: dict[str, Any] | None = None
577
+ ) -> dict[str, Any]:
578
+ """Resolve schema references until there is no $ref anymore in the top-level of the dictionary."""
579
+ if _use_referencing_library():
580
+ registry = _get_referencing_registry(rootschema or schema)
581
+ # Using a different variable name to show that this is not the
582
+ # jsonschema.RefResolver but instead a Resolver from the referencing
583
+ # library
584
+ referencing_resolver = registry.resolver()
585
+ while "$ref" in schema:
586
+ schema = referencing_resolver.lookup(
587
+ _VEGA_LITE_ROOT_URI + schema["$ref"]
588
+ ).contents
589
+ else:
590
+ resolver = jsonschema.RefResolver.from_schema(rootschema or schema)
591
+ while "$ref" in schema:
592
+ with resolver.resolving(schema["$ref"]) as resolved:
593
+ schema = resolved
594
+ return schema
595
+
596
+
597
+ def _validator_values(errors: Iterable[ValidationError], /) -> Iterator[str]:
598
+ """Unwrap each error's ``.validator_value``, convince ``mypy`` it stores a string."""
599
+ for err in errors:
600
+ yield cast("str", err.validator_value)
601
+
602
+
603
+ def _iter_channels(tp: type[Any], spec: Mapping[str, Any], /) -> Iterator[type[Any]]:
604
+ from altair import vegalite
605
+
606
+ for channel_type in ("datum", "value"):
607
+ if channel_type in spec:
608
+ name = f"{tp.__name__}{channel_type.capitalize()}"
609
+ if narrower := getattr(vegalite, name, None):
610
+ yield narrower
611
+
612
+
613
+ def _is_channel(obj: Any) -> TypeIs[dict[str, Any]]:
614
+ props = {"datum", "value"}
615
+ return (
616
+ _is_dict(obj)
617
+ and all(isinstance(k, str) for k in obj)
618
+ and not (props.isdisjoint(obj))
619
+ )
620
+
621
+
622
+ def _maybe_channel(tp: type[Any], spec: Any, /) -> type[Any]:
623
+ """
624
+ Replace a channel type with a `more specific`_ one or passthrough unchanged.
625
+
626
+ Parameters
627
+ ----------
628
+ tp
629
+ An imported ``SchemaBase`` class.
630
+ spec
631
+ The instance that failed validation.
632
+
633
+ .. _more specific:
634
+ https://github.com/vega/altair/issues/2913#issuecomment-2571762700
635
+ """
636
+ return next(_iter_channels(tp, spec), tp) if _is_channel(spec) else tp
637
+
638
+
639
+ class SchemaValidationError(jsonschema.ValidationError):
640
+ _JS_TO_PY: ClassVar[Mapping[str, str]] = {
641
+ "boolean": "bool",
642
+ "integer": "int",
643
+ "number": "float",
644
+ "string": "str",
645
+ "null": "None",
646
+ "object": "Mapping[str, Any]",
647
+ "array": "Sequence",
648
+ }
649
+
650
+ def __init__(self, obj: SchemaBase, err: jsonschema.ValidationError) -> None:
651
+ """
652
+ A wrapper for ``jsonschema.ValidationError`` with friendlier traceback.
653
+
654
+ Parameters
655
+ ----------
656
+ obj
657
+ The instance that failed ``self.validate(...)``.
658
+ err
659
+ The original ``ValidationError``.
660
+
661
+ Notes
662
+ -----
663
+ We do not raise `from err` as else the resulting traceback is very long
664
+ as it contains part of the Vega-Lite schema.
665
+
666
+ It would also first show the less helpful `ValidationError` instead of
667
+ the more user friendly `SchemaValidationError`.
668
+ """
669
+ super().__init__(**err._contents())
670
+ self.obj = obj
671
+ self._errors: GroupedValidationErrors = getattr(
672
+ err, "_all_errors", {getattr(err, "json_path", _json_path(err)): [err]}
673
+ )
674
+ # This is the message from err
675
+ self._original_message = self.message
676
+ self.message = self._get_message()
677
+
678
+ def __str__(self) -> str:
679
+ return self.message
680
+
681
+ def _get_message(self) -> str:
682
+ def indent_second_line_onwards(message: str, indent: int = 4) -> str:
683
+ modified_lines: list[str] = []
684
+ for idx, line in enumerate(message.split("\n")):
685
+ if idx > 0 and len(line) > 0:
686
+ line = " " * indent + line
687
+ modified_lines.append(line)
688
+ return "\n".join(modified_lines)
689
+
690
+ error_messages: list[str] = []
691
+ # Only show a maximum of 3 errors as else the final message returned by this
692
+ # method could get very long.
693
+ for errors in list(self._errors.values())[:3]:
694
+ error_messages.append(self._get_message_for_errors_group(errors))
695
+
696
+ message = ""
697
+ if len(error_messages) > 1:
698
+ error_messages = [
699
+ indent_second_line_onwards(f"Error {error_id}: {m}")
700
+ for error_id, m in enumerate(error_messages, start=1)
701
+ ]
702
+ message += "Multiple errors were found.\n\n"
703
+ message += "\n\n".join(error_messages)
704
+ return message
705
+
706
+ def _get_message_for_errors_group(
707
+ self,
708
+ errors: ValidationErrorList,
709
+ ) -> str:
710
+ if errors[0].validator == "additionalProperties":
711
+ # During development, we only found cases where an additionalProperties
712
+ # error was raised if that was the only error for the offending instance
713
+ # as identifiable by the json path. Therefore, we just check here the first
714
+ # error. However, other constellations might exist in which case
715
+ # this should be adapted so that other error messages are shown as well.
716
+ message = self._get_additional_properties_error_message(errors[0])
717
+ else:
718
+ message = self._get_default_error_message(errors=errors)
719
+
720
+ return message.strip()
721
+
722
+ def _get_additional_properties_error_message(
723
+ self,
724
+ error: jsonschema.exceptions.ValidationError,
725
+ ) -> str:
726
+ """Output all existing parameters when an unknown parameter is specified."""
727
+ altair_cls = self._get_altair_class_for_error(error)
728
+ param_dict_keys = inspect.signature(altair_cls).parameters.keys()
729
+ param_names_table = self._format_params_as_table(param_dict_keys)
730
+
731
+ # Error messages for these errors look like this:
732
+ # "Additional properties are not allowed ('unknown' was unexpected)"
733
+ # Line below extracts "unknown" from this string
734
+ parameter_name = error.message.split("('")[-1].split("'")[0]
735
+ message = f"""\
736
+ `{altair_cls.__name__}` has no parameter named '{parameter_name}'
737
+
738
+ Existing parameter names are:
739
+ {param_names_table}
740
+ See the help for `{altair_cls.__name__}` to read the full description of these parameters"""
741
+ return message
742
+
743
+ def _get_altair_class_for_error(
744
+ self, error: jsonschema.exceptions.ValidationError
745
+ ) -> type[SchemaBase]:
746
+ """
747
+ Try to get the lowest class possible in the chart hierarchy so it can be displayed in the error message.
748
+
749
+ This should lead to more informative error messages pointing the user closer to the source of the issue.
750
+
751
+ If we did not find a suitable class based on traversing the path so we fall
752
+ back on the class of the top-level object which created the SchemaValidationError
753
+ """
754
+ from altair import vegalite
755
+
756
+ for prop_name in reversed(error.absolute_path):
757
+ # Check if str as e.g. first item can be a 0
758
+ if isinstance(prop_name, str):
759
+ candidate = prop_name[0].upper() + prop_name[1:]
760
+ if tp := getattr(vegalite, candidate, None):
761
+ return _maybe_channel(tp, self.instance)
762
+ return type(self.obj)
763
+
764
+ @staticmethod
765
+ def _format_params_as_table(param_dict_keys: Iterable[str]) -> str:
766
+ """Format param names into a table so that they are easier to read."""
767
+ param_names: tuple[str, ...]
768
+ name_lengths: tuple[int, ...]
769
+ param_names, name_lengths = zip(
770
+ *[
771
+ (name, len(name))
772
+ for name in param_dict_keys
773
+ if name not in {"kwds", "self"}
774
+ ]
775
+ )
776
+ # Worst case scenario with the same longest param name in the same
777
+ # row for all columns
778
+ max_name_length = max(name_lengths)
779
+ max_column_width = 80
780
+ # Output a square table if not too big (since it is easier to read)
781
+ num_param_names = len(param_names)
782
+ square_columns = ceil(num_param_names**0.5)
783
+ columns = min(max_column_width // max_name_length, square_columns)
784
+
785
+ # Compute roughly equal column heights to evenly divide the param names
786
+ def split_into_equal_parts(n: int, p: int) -> list[int]:
787
+ return [n // p + 1] * (n % p) + [n // p] * (p - n % p)
788
+
789
+ column_heights = split_into_equal_parts(num_param_names, columns)
790
+
791
+ # Section the param names into columns and compute their widths
792
+ param_names_columns: list[tuple[str, ...]] = []
793
+ column_max_widths: list[int] = []
794
+ last_end_idx: int = 0
795
+ for ch in column_heights:
796
+ param_names_columns.append(param_names[last_end_idx : last_end_idx + ch])
797
+ column_max_widths.append(
798
+ max(len(param_name) for param_name in param_names_columns[-1])
799
+ )
800
+ last_end_idx = ch + last_end_idx
801
+
802
+ # Transpose the param name columns into rows to facilitate looping
803
+ param_names_rows: list[tuple[str, ...]] = []
804
+ for li in zip_longest(*param_names_columns, fillvalue=""):
805
+ param_names_rows.append(li)
806
+ # Build the table as a string by iterating over and formatting the rows
807
+ param_names_table: str = ""
808
+ for param_names_row in param_names_rows:
809
+ for num, param_name in enumerate(param_names_row):
810
+ # Set column width based on the longest param in the column
811
+ max_name_length_column = column_max_widths[num]
812
+ column_pad = 3
813
+ param_names_table += "{:<{}}".format(
814
+ param_name, max_name_length_column + column_pad
815
+ )
816
+ # Insert newlines and spacing after the last element in each row
817
+ if num == (len(param_names_row) - 1):
818
+ param_names_table += "\n"
819
+ return param_names_table
820
+
821
+ def _format_type_reprs(self, errors: Iterable[ValidationError], /) -> str:
822
+ """
823
+ Translate jsonschema types to how they appear in annotations.
824
+
825
+ Adapts parts of:
826
+ - `tools.schemapi.utils.sort_type_reprs`_
827
+ - `tools.schemapi.utils.SchemaInfo.to_type_repr`_
828
+
829
+ .. _tools.schemapi.utils.sort_type_reprs:
830
+ https://github.com/vega/altair/blob/48e976ef9388ce08a2e871a0f67ed012b914597a/tools/schemapi/utils.py#L1106-L1146
831
+ .. _tools.schemapi.utils.SchemaInfo.to_type_repr:
832
+ https://github.com/vega/altair/blob/48e976ef9388ce08a2e871a0f67ed012b914597a/tools/schemapi/utils.py#L449-L543
833
+ """
834
+ to_py_types = (
835
+ self._JS_TO_PY.get(val, val) for val in _validator_values(errors)
836
+ )
837
+ it = sorted(to_py_types, key=str.lower)
838
+ it = sorted(it, key=len)
839
+ it = sorted(it, key=partial(operator.eq, "None"))
840
+ return f"of type `{' | '.join(it)}`"
841
+
842
+ def _get_default_error_message(
843
+ self,
844
+ errors: ValidationErrorList,
845
+ ) -> str:
846
+ bullet_points: list[str] = []
847
+ errors_by_validator = _group_errors_by_validator(errors)
848
+ if errs_enum := errors_by_validator.get("enum", None):
849
+ bullet_points.extend(
850
+ f"one of {val}" for val in _validator_values(errs_enum)
851
+ )
852
+ if errs_type := errors_by_validator.get("type", None):
853
+ bullet_points.append(self._format_type_reprs(errs_type))
854
+
855
+ # It should not matter which error is specifically used as they are all
856
+ # about the same offending instance (i.e. invalid value), so we can just
857
+ # take the first one
858
+ error = errors[0]
859
+ # Add a summary line when parameters are passed an invalid value
860
+ # For example: "'asdf' is an invalid value for `stack`
861
+ message = f"'{error.instance}' is an invalid value"
862
+ if error.absolute_path:
863
+ message += f" for `{error.absolute_path[-1]}`"
864
+
865
+ # Add bullet points
866
+ if len(bullet_points) == 0:
867
+ message += ".\n\n"
868
+ elif len(bullet_points) == 1:
869
+ message += f". Valid values are {bullet_points[0]}.\n\n"
870
+ else:
871
+ # We don't use .capitalize below to make the first letter uppercase
872
+ # as that makes the rest of the message lowercase
873
+ bullet_points = [point[0].upper() + point[1:] for point in bullet_points]
874
+ message += ". Valid values are:\n\n"
875
+ message += "\n".join([f"- {point}" for point in bullet_points])
876
+ message += "\n\n"
877
+
878
+ # Add unformatted messages of any remaining errors which were not
879
+ # considered so far. This is not expected to be used but more exists
880
+ # as a fallback for cases which were not known during development.
881
+ it = (
882
+ "\n".join(e.message for e in errors)
883
+ for validator, errors in errors_by_validator.items()
884
+ if validator not in {"enum", "type"}
885
+ )
886
+ message += "".join(it)
887
+ return message
888
+
889
+
890
+ _JSON_VT_co = TypeVar(
891
+ "_JSON_VT_co",
892
+ Literal["string"],
893
+ Literal["object"],
894
+ Literal["array"],
895
+ covariant=True,
896
+ )
897
+ """
898
+ One of a subset of JSON Schema `primitive types`_:
899
+
900
+ ["string", "object", "array"]
901
+
902
+ .. _primitive types:
903
+ https://json-schema.org/draft-07/json-schema-validation#rfc.section.6.1.1
904
+ """
905
+
906
+ _TypeMap = TypeAliasType(
907
+ "_TypeMap", Mapping[Literal["type"], _JSON_VT_co], type_params=(_JSON_VT_co,)
908
+ )
909
+ """
910
+ A single item JSON Schema using the `type`_ keyword.
911
+
912
+ This may represent **one of**:
913
+
914
+ {"type": "string"}
915
+ {"type": "object"}
916
+ {"type": "array"}
917
+
918
+ .. _type:
919
+ https://json-schema.org/understanding-json-schema/reference/type
920
+ """
921
+
922
+ # NOTE: Type checkers want opposing things:
923
+ # - `mypy` : Covariant type variable "_JSON_VT_co" used in protocol where invariant one is expected [misc]
924
+ # - `pyright`: Type variable "_JSON_VT_co" used in generic protocol "SchemaLike" should be covariant [reportInvalidTypeVarUse]
925
+ # Siding with `pyright` as this is consistent with https://github.com/python/typeshed/blob/9e506eb5e8fc2823db8c60ad561b1145ff114947/stdlib/typing.pyi#L690
926
+
927
+
928
+ @runtime_checkable
929
+ class SchemaLike(Generic[_JSON_VT_co], Protocol): # type: ignore[misc]
930
+ """
931
+ Represents ``altair`` classes which *may* not derive ``SchemaBase``.
932
+
933
+ Attributes
934
+ ----------
935
+ _schema
936
+ A single item JSON Schema using the `type`_ keyword.
937
+
938
+ Notes
939
+ -----
940
+ Should be kept tightly defined to the **minimum** requirements for:
941
+ - Converting into a form that can be validated by `jsonschema`_.
942
+ - Avoiding calling ``.to_dict()`` on a class external to ``altair``.
943
+ - ``_schema`` is more accurately described as a ``ClassVar``
944
+ - See `discussion`_ for blocking issue.
945
+
946
+ .. _jsonschema:
947
+ https://github.com/python-jsonschema/jsonschema
948
+ .. _type:
949
+ https://json-schema.org/understanding-json-schema/reference/type
950
+ .. _discussion:
951
+ https://github.com/python/typing/discussions/1424
952
+ """
953
+
954
+ _schema: _TypeMap[_JSON_VT_co]
955
+
956
+ def to_dict(self, *args, **kwds) -> Any: ...
957
+
958
+
959
+ @runtime_checkable
960
+ class ConditionLike(SchemaLike[Literal["object"]], Protocol):
961
+ """
962
+ Represents the wrapped state of a conditional encoding or property.
963
+
964
+ Attributes
965
+ ----------
966
+ condition
967
+ One or more (predicate, statement) pairs which each form a condition.
968
+
969
+ Notes
970
+ -----
971
+ - Can be extended with additional conditions.
972
+ - *Does not* define a default value, but can be finalized with one.
973
+ """
974
+
975
+ condition: Any
976
+ _schema: _TypeMap[Literal["object"]] = {"type": "object"}
977
+
978
+
979
+ class UndefinedType:
980
+ """A singleton object for marking undefined parameters."""
981
+
982
+ __instance = None
983
+
984
+ def __new__(cls, *args, **kwargs) -> Self:
985
+ if not isinstance(cls.__instance, cls):
986
+ cls.__instance = object.__new__(cls, *args, **kwargs)
987
+ return cls.__instance
988
+
989
+ def __repr__(self) -> str:
990
+ return "Undefined"
991
+
992
+
993
+ Undefined = UndefinedType()
994
+ T = TypeVar("T")
995
+ Optional: TypeAlias = Union[T, UndefinedType]
996
+ """One of ``T`` specified type(s), or the ``Undefined`` singleton.
997
+
998
+ Examples
999
+ --------
1000
+ The parameters ``short``, ``long`` accept the same range of types::
1001
+
1002
+ # ruff: noqa: UP006, UP007
1003
+ from altair.typing import Optional
1004
+
1005
+ def func_1(
1006
+ short: Optional[str | bool | float | dict[str, Any] | SchemaBase] = Undefined,
1007
+ long: Union[
1008
+ str, bool, float, Dict[str, Any], SchemaBase, UndefinedType
1009
+ ] = Undefined,
1010
+ ): ...
1011
+
1012
+ This is distinct from `typing.Optional <https://typing.readthedocs.io/en/latest/spec/historical.html#union-and-optional>`__.
1013
+
1014
+ ``altair.typing.Optional`` treats ``None`` like any other type::
1015
+
1016
+ # ruff: noqa: UP006, UP007
1017
+ from altair.typing import Optional
1018
+
1019
+ def func_2(
1020
+ short: Optional[str | float | dict[str, Any] | None | SchemaBase] = Undefined,
1021
+ long: Union[
1022
+ str, float, Dict[str, Any], None, SchemaBase, UndefinedType
1023
+ ] = Undefined,
1024
+ ): ...
1025
+ """
1026
+
1027
+
1028
+ def is_undefined(obj: Any) -> TypeIs[UndefinedType]:
1029
+ """
1030
+ Type-safe singleton check for `UndefinedType`.
1031
+
1032
+ Notes
1033
+ -----
1034
+ - Using `obj is Undefined` does not narrow from `UndefinedType` in a union.
1035
+ - Due to the assumption that other `UndefinedType`'s could exist.
1036
+ - Current [typing spec advises](https://typing.readthedocs.io/en/latest/spec/concepts.html#support-for-singleton-types-in-unions) using an `Enum`.
1037
+ - Otherwise, requires an explicit guard to inform the type checker.
1038
+ """
1039
+ return obj is Undefined
1040
+
1041
+
1042
+ @overload
1043
+ def _shallow_copy(obj: _CopyImpl) -> _CopyImpl: ...
1044
+ @overload
1045
+ def _shallow_copy(obj: Any) -> Any: ...
1046
+ def _shallow_copy(obj: _CopyImpl | Any) -> _CopyImpl | Any:
1047
+ if isinstance(obj, SchemaBase):
1048
+ return obj.copy(deep=False)
1049
+ elif isinstance(obj, (list, dict)):
1050
+ return obj.copy()
1051
+ else:
1052
+ return obj
1053
+
1054
+
1055
+ @overload
1056
+ def _deep_copy(obj: _CopyImpl, by_ref: set[str]) -> _CopyImpl: ...
1057
+ @overload
1058
+ def _deep_copy(obj: Any, by_ref: set[str]) -> Any: ...
1059
+ def _deep_copy(obj: _CopyImpl | Any, by_ref: set[str]) -> _CopyImpl | Any:
1060
+ copy = partial(_deep_copy, by_ref=by_ref)
1061
+ if isinstance(obj, SchemaBase):
1062
+ if copier := getattr(obj, "__deepcopy__", None):
1063
+ with debug_mode(False):
1064
+ return copier(obj)
1065
+ args = (copy(arg) for arg in obj._args)
1066
+ kwds = {k: (copy(v) if k not in by_ref else v) for k, v in obj._kwds.items()}
1067
+ with debug_mode(False):
1068
+ return obj.__class__(*args, **kwds)
1069
+ elif isinstance(obj, list):
1070
+ return [copy(v) for v in obj]
1071
+ elif isinstance(obj, dict):
1072
+ return {k: (copy(v) if k not in by_ref else v) for k, v in obj.items()}
1073
+ else:
1074
+ return obj
1075
+
1076
+
1077
+ class SchemaBase:
1078
+ """
1079
+ Base class for schema wrappers.
1080
+
1081
+ Each derived class should set the _schema class attribute (and optionally
1082
+ the _rootschema class attribute) which is used for validation.
1083
+ """
1084
+
1085
+ _schema: ClassVar[dict[str, Any] | Any] = None
1086
+ _rootschema: ClassVar[dict[str, Any] | None] = None
1087
+ _class_is_valid_at_instantiation: ClassVar[bool] = True
1088
+
1089
+ def __init__(self, *args: Any, **kwds: Any) -> None:
1090
+ # Two valid options for initialization, which should be handled by
1091
+ # derived classes:
1092
+ # - a single arg with no kwds, for, e.g. {'type': 'string'}
1093
+ # - zero args with zero or more kwds for {'type': 'object'}
1094
+ if self._schema is None:
1095
+ msg = (
1096
+ f"Cannot instantiate object of type {self.__class__}: "
1097
+ "_schema class attribute is not defined."
1098
+ ""
1099
+ )
1100
+ raise ValueError(msg)
1101
+
1102
+ if kwds:
1103
+ assert len(args) == 0
1104
+ else:
1105
+ assert len(args) in {0, 1}
1106
+
1107
+ # use object.__setattr__ because we override setattr below.
1108
+ object.__setattr__(self, "_args", args)
1109
+ object.__setattr__(self, "_kwds", kwds)
1110
+
1111
+ if DEBUG_MODE and self._class_is_valid_at_instantiation:
1112
+ self.to_dict(validate=True)
1113
+
1114
+ def copy(
1115
+ self, deep: bool | Iterable[Any] = True, ignore: list[str] | None = None
1116
+ ) -> Self:
1117
+ """
1118
+ Return a copy of the object.
1119
+
1120
+ Parameters
1121
+ ----------
1122
+ deep : boolean or list, optional
1123
+ If True (default) then return a deep copy of all dict, list, and
1124
+ SchemaBase objects within the object structure.
1125
+ If False, then only copy the top object.
1126
+ If a list or iterable, then only copy the listed attributes.
1127
+ ignore : list, optional
1128
+ A list of keys for which the contents should not be copied, but
1129
+ only stored by reference.
1130
+ """
1131
+ if deep is True:
1132
+ return cast("Self", _deep_copy(self, set(ignore) if ignore else set()))
1133
+ with debug_mode(False):
1134
+ copy = self.__class__(*self._args, **self._kwds)
1135
+ if _is_iterable(deep):
1136
+ for attr in deep:
1137
+ copy[attr] = _shallow_copy(copy._get(attr))
1138
+ return copy
1139
+
1140
+ def _get(self, attr, default=Undefined):
1141
+ """Get an attribute, returning default if not present."""
1142
+ attr = self._kwds.get(attr, Undefined)
1143
+ if attr is Undefined:
1144
+ attr = default
1145
+ return attr
1146
+
1147
+ def __getattr__(self, attr):
1148
+ # reminder: getattr is called after the normal lookups
1149
+ if attr == "_kwds":
1150
+ raise AttributeError()
1151
+ if attr in self._kwds:
1152
+ return self._kwds[attr]
1153
+ else:
1154
+ try:
1155
+ _getattr = super().__getattr__ # pyright: ignore[reportAttributeAccessIssue]
1156
+ except AttributeError:
1157
+ _getattr = super().__getattribute__
1158
+ return _getattr(attr)
1159
+
1160
+ def __setattr__(self, item, val) -> None:
1161
+ self._kwds[item] = val
1162
+
1163
+ def __getitem__(self, item):
1164
+ return self._kwds[item]
1165
+
1166
+ def __setitem__(self, item, val) -> None:
1167
+ self._kwds[item] = val
1168
+
1169
+ def __repr__(self) -> str:
1170
+ name = type(self).__name__
1171
+ if kwds := self._kwds:
1172
+ it = (f"{k}: {v!r}" for k, v in sorted(kwds.items()) if v is not Undefined)
1173
+ args = ",\n".join(it).replace("\n", "\n ")
1174
+ LB, RB = "{", "}"
1175
+ return f"{name}({LB}\n {args}\n{RB})"
1176
+ else:
1177
+ return f"{name}({self._args[0]!r})"
1178
+
1179
+ def __eq__(self, other: Any) -> bool:
1180
+ return (
1181
+ type(self) is type(other)
1182
+ and self._args == other._args
1183
+ and self._kwds == other._kwds
1184
+ )
1185
+
1186
+ def to_dict(
1187
+ self,
1188
+ validate: bool = True,
1189
+ *,
1190
+ ignore: list[str] | None = None,
1191
+ context: dict[str, Any] | None = None,
1192
+ ) -> dict[str, Any]:
1193
+ """
1194
+ Return a dictionary representation of the object.
1195
+
1196
+ Parameters
1197
+ ----------
1198
+ validate : bool, optional
1199
+ If True (default), then validate the result against the schema.
1200
+ ignore : list[str], optional
1201
+ A list of keys to ignore.
1202
+ context : dict[str, Any], optional
1203
+ A context dictionary.
1204
+
1205
+ Raises
1206
+ ------
1207
+ SchemaValidationError :
1208
+ If ``validate`` and the result does not conform to the schema.
1209
+
1210
+ Notes
1211
+ -----
1212
+ - ``ignore``, ``context`` are usually not needed to be specified as a user.
1213
+ - *Technical*: ``ignore`` will **not** be passed to child :meth:`.to_dict()`.
1214
+ """
1215
+ context = context or {}
1216
+ ignore = ignore or []
1217
+ opts = _get_optional_modules(np_opt="numpy", pd_opt="pandas")
1218
+
1219
+ if self._args and not self._kwds:
1220
+ kwds = self._args[0]
1221
+ elif not self._args:
1222
+ kwds = self._kwds.copy()
1223
+ exclude = {*ignore, "shorthand"}
1224
+ if parsed := context.pop("parsed_shorthand", None):
1225
+ kwds = _replace_parsed_shorthand(parsed, kwds)
1226
+ kwds = {k: v for k, v in kwds.items() if k not in exclude}
1227
+ if (mark := kwds.get("mark")) and isinstance(mark, str):
1228
+ kwds["mark"] = {"type": mark}
1229
+ else:
1230
+ msg = f"{type(self)} instance has both a value and properties : cannot serialize to dict"
1231
+ raise ValueError(msg)
1232
+ result = _todict(kwds, context=context, **opts)
1233
+ if validate:
1234
+ # NOTE: Don't raise `from err`, see `SchemaValidationError` doc
1235
+ try:
1236
+ self.validate(result)
1237
+ except jsonschema.ValidationError as err:
1238
+ raise SchemaValidationError(self, err) from None
1239
+ return result
1240
+
1241
+ def to_json(
1242
+ self,
1243
+ validate: bool = True,
1244
+ indent: int | str | None = 2,
1245
+ sort_keys: bool = True,
1246
+ *,
1247
+ ignore: list[str] | None = None,
1248
+ context: dict[str, Any] | None = None,
1249
+ **kwargs,
1250
+ ) -> str:
1251
+ """
1252
+ Emit the JSON representation for this object as a string.
1253
+
1254
+ Parameters
1255
+ ----------
1256
+ validate : bool, optional
1257
+ If True (default), then validate the result against the schema.
1258
+ indent : int, optional
1259
+ The number of spaces of indentation to use. The default is 2.
1260
+ sort_keys : bool, optional
1261
+ If True (default), sort keys in the output.
1262
+ ignore : list[str], optional
1263
+ A list of keys to ignore.
1264
+ context : dict[str, Any], optional
1265
+ A context dictionary.
1266
+ **kwargs
1267
+ Additional keyword arguments are passed to ``json.dumps()``
1268
+
1269
+ Raises
1270
+ ------
1271
+ SchemaValidationError :
1272
+ If ``validate`` and the result does not conform to the schema.
1273
+
1274
+ Notes
1275
+ -----
1276
+ - ``ignore``, ``context`` are usually not needed to be specified as a user.
1277
+ - *Technical*: ``ignore`` will **not** be passed to child :meth:`.to_dict()`.
1278
+ """
1279
+ if ignore is None:
1280
+ ignore = []
1281
+ if context is None:
1282
+ context = {}
1283
+ dct = self.to_dict(validate=validate, ignore=ignore, context=context)
1284
+ return json.dumps(dct, indent=indent, sort_keys=sort_keys, **kwargs)
1285
+
1286
+ @classmethod
1287
+ def _default_wrapper_classes(cls) -> Iterator[type[SchemaBase]]:
1288
+ """Return the set of classes used within cls.from_dict()."""
1289
+ return _subclasses(SchemaBase)
1290
+
1291
+ @classmethod
1292
+ def from_dict(
1293
+ cls: type[TSchemaBase], dct: dict[str, Any], validate: bool = True
1294
+ ) -> TSchemaBase:
1295
+ """
1296
+ Construct class from a dictionary representation.
1297
+
1298
+ Parameters
1299
+ ----------
1300
+ dct : dictionary
1301
+ The dict from which to construct the class
1302
+ validate : boolean
1303
+ If True (default), then validate the input against the schema.
1304
+
1305
+ Raises
1306
+ ------
1307
+ jsonschema.ValidationError :
1308
+ If ``validate`` and ``dct`` does not conform to the schema
1309
+ """
1310
+ if validate:
1311
+ cls.validate(dct)
1312
+ converter = _FromDict(cls._default_wrapper_classes())
1313
+ return converter.from_dict(dct, cls)
1314
+
1315
+ @classmethod
1316
+ def from_json(
1317
+ cls,
1318
+ json_string: str,
1319
+ validate: bool = True,
1320
+ **kwargs: Any,
1321
+ # Type hints for this method would get rather complicated
1322
+ # if we want to provide a more specific return type
1323
+ ) -> ChartType:
1324
+ """
1325
+ Instantiate the object from a valid JSON string.
1326
+
1327
+ Parameters
1328
+ ----------
1329
+ json_string : string
1330
+ The string containing a valid JSON chart specification.
1331
+ validate : boolean
1332
+ If True (default), then validate the input against the schema.
1333
+ **kwargs :
1334
+ Additional keyword arguments are passed to json.loads
1335
+
1336
+ Returns
1337
+ -------
1338
+ chart : Chart object
1339
+ The altair Chart object built from the specification.
1340
+ """
1341
+ dct: dict[str, Any] = json.loads(json_string, **kwargs)
1342
+ return cls.from_dict(dct, validate=validate) # type: ignore[return-value]
1343
+
1344
+ @classmethod
1345
+ def validate(
1346
+ cls, instance: dict[str, Any], schema: dict[str, Any] | None = None
1347
+ ) -> None:
1348
+ """Validate the instance against the class schema in the context of the rootschema."""
1349
+ if schema is None:
1350
+ schema = cls._schema
1351
+ # For the benefit of mypy
1352
+ assert schema is not None
1353
+ validate_jsonschema(instance, schema, rootschema=cls._rootschema or cls._schema)
1354
+
1355
+ @classmethod
1356
+ def resolve_references(cls, schema: dict[str, Any] | None = None) -> dict[str, Any]:
1357
+ """Resolve references in the context of this object's schema or root schema."""
1358
+ schema_to_pass = schema or cls._schema
1359
+ # For the benefit of mypy
1360
+ assert schema_to_pass is not None
1361
+ return _resolve_references(
1362
+ schema=schema_to_pass,
1363
+ rootschema=(cls._rootschema or cls._schema or schema),
1364
+ )
1365
+
1366
+ @classmethod
1367
+ def validate_property(
1368
+ cls, name: str, value: Any, schema: dict[str, Any] | None = None
1369
+ ) -> None:
1370
+ """Validate a property against property schema in the context of the rootschema."""
1371
+ opts = _get_optional_modules(np_opt="numpy", pd_opt="pandas")
1372
+ value = _todict(value, context={}, **opts)
1373
+ props = cls.resolve_references(schema or cls._schema).get("properties", {})
1374
+ validate_jsonschema(
1375
+ value, props.get(name, {}), rootschema=cls._rootschema or cls._schema
1376
+ )
1377
+
1378
+ def __dir__(self) -> list[str]:
1379
+ return sorted(chain(super().__dir__(), self._kwds))
1380
+
1381
+
1382
+ def _get_optional_modules(**modules: str) -> dict[str, _OptionalModule]:
1383
+ """
1384
+ Returns packages only if they have already been imported - otherwise they return `None`.
1385
+
1386
+ This is useful for `isinstance` checks.
1387
+
1388
+ For example, if `pandas` has not been imported, then an object is
1389
+ definitely not a `pandas.Timestamp`.
1390
+
1391
+ Parameters
1392
+ ----------
1393
+ **modules
1394
+ Keyword-only binding from `{alias: module_name}`.
1395
+
1396
+ Examples
1397
+ --------
1398
+ >>> import pandas as pd # doctest: +SKIP
1399
+ >>> import polars as pl # doctest: +SKIP
1400
+ >>> from altair.utils.schemapi import _get_optional_modules # doctest: +SKIP
1401
+ >>>
1402
+ >>> _get_optional_modules(pd="pandas", pl="polars", ibis="ibis") # doctest: +SKIP
1403
+ {
1404
+ "pd": <module 'pandas' from '...'>,
1405
+ "pl": <module 'polars' from '...'>,
1406
+ "ibis": None,
1407
+ }
1408
+
1409
+ If the user later imports ``ibis``, it would appear in subsequent calls.
1410
+
1411
+ >>> import ibis # doctest: +SKIP
1412
+ >>>
1413
+ >>> _get_optional_modules(ibis="ibis") # doctest: +SKIP
1414
+ {
1415
+ "ibis": <module 'ibis' from '...'>,
1416
+ }
1417
+ """
1418
+ return {k: sys.modules.get(v) for k, v in modules.items()}
1419
+
1420
+
1421
+ def _replace_parsed_shorthand(
1422
+ parsed_shorthand: dict[str, Any], kwds: dict[str, Any]
1423
+ ) -> dict[str, Any]:
1424
+ """
1425
+ `parsed_shorthand` is added by `FieldChannelMixin`.
1426
+
1427
+ It's used below to replace shorthand with its long form equivalent
1428
+ `parsed_shorthand` is removed from `context` if it exists so that it is
1429
+ not passed to child `to_dict` function calls.
1430
+ """
1431
+ # Prevent that pandas categorical data is automatically sorted
1432
+ # when a non-ordinal data type is specified manually
1433
+ # or if the encoding channel does not support sorting
1434
+ if "sort" in parsed_shorthand and (
1435
+ "sort" not in kwds or kwds["type"] not in {"ordinal", Undefined}
1436
+ ):
1437
+ parsed_shorthand.pop("sort")
1438
+
1439
+ kwds.update(
1440
+ (k, v)
1441
+ for k, v in parsed_shorthand.items()
1442
+ if kwds.get(k, Undefined) is Undefined
1443
+ )
1444
+ return kwds
1445
+
1446
+
1447
+ TSchemaBase = TypeVar("TSchemaBase", bound=SchemaBase)
1448
+
1449
+ _CopyImpl = TypeVar("_CopyImpl", SchemaBase, dict[Any, Any], list[Any])
1450
+ """
1451
+ Types which have an implementation in ``SchemaBase.copy()``.
1452
+
1453
+ All other types are returned **by reference**.
1454
+ """
1455
+
1456
+
1457
+ def _is_dict(obj: Any | dict[Any, Any]) -> TypeIs[dict[Any, Any]]:
1458
+ return isinstance(obj, dict)
1459
+
1460
+
1461
+ def _is_list(obj: Any | list[Any]) -> TypeIs[list[Any]]:
1462
+ return isinstance(obj, list)
1463
+
1464
+
1465
+ def _is_iterable(
1466
+ obj: Any, *, exclude: type | tuple[type, ...] = (str, bytes)
1467
+ ) -> TypeIs[Iterable[Any]]:
1468
+ return not isinstance(obj, exclude) and isinstance(obj, Iterable)
1469
+
1470
+
1471
+ def _passthrough(*args: Any, **kwds: Any) -> Any | dict[str, Any]:
1472
+ return args[0] if args else kwds
1473
+
1474
+
1475
+ class _FromDict:
1476
+ """
1477
+ Class used to construct SchemaBase class hierarchies from a dict.
1478
+
1479
+ The primary purpose of using this class is to be able to build a hash table
1480
+ that maps schemas to their wrapper classes. The candidate classes are
1481
+ specified in the ``wrapper_classes`` positional-only argument to the constructor.
1482
+ """
1483
+
1484
+ _hash_exclude_keys = ("definitions", "title", "description", "$schema", "id")
1485
+
1486
+ def __init__(self, wrapper_classes: Iterable[type[SchemaBase]], /) -> None:
1487
+ # Create a mapping of a schema hash to a list of matching classes
1488
+ # This lets us quickly determine the correct class to construct
1489
+ self.class_dict: dict[int, list[type[SchemaBase]]] = defaultdict(list)
1490
+ for tp in wrapper_classes:
1491
+ if tp._schema is not None:
1492
+ self.class_dict[self.hash_schema(tp._schema)].append(tp)
1493
+
1494
+ @classmethod
1495
+ def hash_schema(cls, schema: dict[str, Any], use_json: bool = True) -> int:
1496
+ """
1497
+ Compute a python hash for a nested dictionary which properly handles dicts, lists, sets, and tuples.
1498
+
1499
+ At the top level, the function excludes from the hashed schema all keys
1500
+ listed in `exclude_keys`.
1501
+
1502
+ This implements two methods: one based on conversion to JSON, and one based
1503
+ on recursive conversions of unhashable to hashable types; the former seems
1504
+ to be slightly faster in several benchmarks.
1505
+ """
1506
+ if cls._hash_exclude_keys and isinstance(schema, dict):
1507
+ schema = {
1508
+ key: val
1509
+ for key, val in schema.items()
1510
+ if key not in cls._hash_exclude_keys
1511
+ }
1512
+ if use_json:
1513
+ s = json.dumps(schema, sort_keys=True)
1514
+ return hash(s)
1515
+ else:
1516
+
1517
+ def _freeze(val):
1518
+ if isinstance(val, dict):
1519
+ return frozenset((k, _freeze(v)) for k, v in val.items())
1520
+ elif isinstance(val, set):
1521
+ return frozenset(map(_freeze, val))
1522
+ elif isinstance(val, (list, tuple)):
1523
+ return tuple(map(_freeze, val))
1524
+ else:
1525
+ return val
1526
+
1527
+ return hash(_freeze(schema))
1528
+
1529
+ @overload
1530
+ def from_dict(
1531
+ self,
1532
+ dct: TSchemaBase,
1533
+ tp: None = ...,
1534
+ schema: None = ...,
1535
+ rootschema: None = ...,
1536
+ default_class: Any = ...,
1537
+ ) -> TSchemaBase: ...
1538
+ @overload
1539
+ def from_dict(
1540
+ self,
1541
+ dct: dict[str, Any] | list[dict[str, Any]],
1542
+ tp: Any = ...,
1543
+ schema: Any = ...,
1544
+ rootschema: Any = ...,
1545
+ default_class: type[TSchemaBase] = ..., # pyright: ignore[reportInvalidTypeVarUse]
1546
+ ) -> TSchemaBase: ...
1547
+ @overload
1548
+ def from_dict(
1549
+ self,
1550
+ dct: dict[str, Any],
1551
+ tp: None = ...,
1552
+ schema: dict[str, Any] = ...,
1553
+ rootschema: None = ...,
1554
+ default_class: Any = ...,
1555
+ ) -> SchemaBase: ...
1556
+ @overload
1557
+ def from_dict(
1558
+ self,
1559
+ dct: dict[str, Any],
1560
+ tp: type[TSchemaBase],
1561
+ schema: None = ...,
1562
+ rootschema: None = ...,
1563
+ default_class: Any = ...,
1564
+ ) -> TSchemaBase: ...
1565
+ @overload
1566
+ def from_dict(
1567
+ self,
1568
+ dct: dict[str, Any] | list[dict[str, Any]],
1569
+ tp: type[TSchemaBase],
1570
+ schema: dict[str, Any],
1571
+ rootschema: dict[str, Any] | None = ...,
1572
+ default_class: Any = ...,
1573
+ ) -> Never: ...
1574
+ def from_dict(
1575
+ self,
1576
+ dct: dict[str, Any] | list[dict[str, Any]] | TSchemaBase,
1577
+ tp: type[TSchemaBase] | None = None,
1578
+ schema: dict[str, Any] | None = None,
1579
+ rootschema: dict[str, Any] | None = None,
1580
+ default_class: Any = _passthrough,
1581
+ ) -> TSchemaBase | SchemaBase:
1582
+ """Construct an object from a dict representation."""
1583
+ target_tp: Any
1584
+ current_schema: dict[str, Any]
1585
+ if isinstance(dct, SchemaBase):
1586
+ return dct
1587
+ elif tp is not None:
1588
+ current_schema = tp._schema
1589
+ root_schema: dict[str, Any] = rootschema or tp._rootschema or current_schema
1590
+ target_tp = tp
1591
+ elif schema is not None:
1592
+ # If there are multiple matches, we use the first one in the dict.
1593
+ # Our class dict is constructed breadth-first from top to bottom,
1594
+ # so the first class that matches is the most general match.
1595
+ current_schema = schema
1596
+ root_schema = rootschema or current_schema
1597
+ matches = self.class_dict[self.hash_schema(current_schema)]
1598
+ target_tp = matches[0] if matches else default_class
1599
+ else:
1600
+ msg = "Must provide either `tp` or `schema`, but not both."
1601
+ raise ValueError(msg)
1602
+
1603
+ from_dict = partial(self.from_dict, rootschema=root_schema)
1604
+ # Can also return a list?
1605
+ resolved = _resolve_references(current_schema, root_schema)
1606
+ if "anyOf" in resolved or "oneOf" in resolved:
1607
+ schemas = resolved.get("anyOf", []) + resolved.get("oneOf", [])
1608
+ for possible in schemas:
1609
+ try:
1610
+ validate_jsonschema(dct, possible, rootschema=root_schema)
1611
+ except jsonschema.ValidationError:
1612
+ continue
1613
+ else:
1614
+ return from_dict(dct, schema=possible, default_class=target_tp)
1615
+
1616
+ if _is_dict(dct):
1617
+ # TODO: handle schemas for additionalProperties/patternProperties
1618
+ props: dict[str, Any] = resolved.get("properties", {})
1619
+ kwds = {
1620
+ k: (from_dict(v, schema=props[k]) if k in props else v)
1621
+ for k, v in dct.items()
1622
+ }
1623
+ return target_tp(**kwds)
1624
+ elif _is_list(dct):
1625
+ item_schema: dict[str, Any] = resolved.get("items", {})
1626
+ return target_tp([from_dict(k, schema=item_schema) for k in dct])
1627
+ else:
1628
+ # NOTE: Unsure what is valid here
1629
+ return target_tp(dct)
1630
+
1631
+
1632
+ class _PropertySetter:
1633
+ def __init__(self, prop: str, schema: dict[str, Any]) -> None:
1634
+ self.prop = prop
1635
+ self.schema = schema
1636
+
1637
+ def __get__(self, obj, cls):
1638
+ from altair import vegalite
1639
+
1640
+ self.obj = obj
1641
+ self.cls = cls
1642
+ # The docs from the encoding class parameter (e.g. `bin` in X, Color,
1643
+ # etc); this provides a general description of the parameter.
1644
+ self.__doc__ = self.schema["description"].replace("__", "**")
1645
+ property_name = f"{self.prop}"[0].upper() + f"{self.prop}"[1:]
1646
+ if altair_prop := getattr(vegalite, property_name, None):
1647
+ # Add the docstring from the helper class (e.g. `BinParams`) so
1648
+ # that all the parameter names of the helper class are included in
1649
+ # the final docstring
1650
+ parameter_index = altair_prop.__doc__.find("Parameters\n")
1651
+ if parameter_index > -1:
1652
+ self.__doc__ = (
1653
+ altair_prop.__doc__[:parameter_index].replace(" ", "")
1654
+ + self.__doc__
1655
+ + textwrap.dedent(
1656
+ f"\n\n {altair_prop.__doc__[parameter_index:]}"
1657
+ )
1658
+ )
1659
+ # For short docstrings such as Aggregate, Stack, et
1660
+ else:
1661
+ self.__doc__ = (
1662
+ altair_prop.__doc__.replace(" ", "") + "\n" + self.__doc__
1663
+ )
1664
+ # Add signatures and tab completion for the method and parameter names
1665
+ self.__signature__ = inspect.signature(altair_prop)
1666
+ self.__wrapped__ = inspect.getfullargspec(altair_prop)
1667
+ self.__name__ = altair_prop.__name__
1668
+ else:
1669
+ # It seems like bandPosition is the only parameter that doesn't
1670
+ # have a helper class.
1671
+ pass
1672
+ return self
1673
+
1674
+ def __call__(self, *args: Any, **kwargs: Any):
1675
+ obj = self.obj.copy()
1676
+ # TODO: use schema to validate
1677
+ obj[self.prop] = args[0] if args else kwargs
1678
+ return obj
1679
+
1680
+
1681
+ def with_property_setters(cls: type[TSchemaBase]) -> type[TSchemaBase]:
1682
+ """Decorator to add property setters to a Schema class."""
1683
+ schema = cls.resolve_references()
1684
+ for prop, propschema in schema.get("properties", {}).items():
1685
+ setattr(cls, prop, _PropertySetter(prop, propschema))
1686
+ return cls
1687
+
1688
+
1689
+ VERSIONS: Mapping[
1690
+ Literal[
1691
+ "vega-datasets", "vega-embed", "vega-lite", "vegafusion", "vl-convert-python"
1692
+ ],
1693
+ str,
1694
+ ] = {
1695
+ "vega-datasets": "v3.2.1",
1696
+ "vega-embed": "v7",
1697
+ "vega-lite": "v6.1.0",
1698
+ "vegafusion": "2.0.3",
1699
+ "vl-convert-python": "1.8.0",
1700
+ }
1701
+ """
1702
+ Version pins for non-``python`` `vega projects`_.
1703
+
1704
+ Notes
1705
+ -----
1706
+ When cutting a new release, make sure to update ``[tool.altair.vega]`` in ``pyproject.toml``.
1707
+
1708
+ .. _vega projects:
1709
+ https://github.com/vega
1710
+ """
.venv/lib/python3.13/site-packages/altair/utils/selection.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, NewType
5
+
6
+ # Type representing the "{selection}_store" dataset that corresponds to a
7
+ # Vega-Lite selection
8
+ Store = NewType("Store", list[dict[str, Any]])
9
+
10
+
11
+ @dataclass(frozen=True, eq=True)
12
+ class IndexSelection:
13
+ """
14
+ Represents the state of an alt.selection_point() when neither the fields nor encodings arguments are specified.
15
+
16
+ The value field is a list of zero-based indices into the
17
+ selected dataset.
18
+
19
+ Note: These indices only apply to the input DataFrame
20
+ for charts that do not include aggregations (e.g. a scatter chart).
21
+ """
22
+
23
+ name: str
24
+ value: list[int]
25
+ store: Store
26
+
27
+ @staticmethod
28
+ def from_vega(name: str, signal: dict[str, dict] | None, store: Store):
29
+ """
30
+ Construct an IndexSelection from the raw Vega signal and dataset values.
31
+
32
+ Parameters
33
+ ----------
34
+ name: str
35
+ The selection's name
36
+ signal: dict or None
37
+ The value of the Vega signal corresponding to the selection
38
+ store: list
39
+ The value of the Vega dataset corresponding to the selection.
40
+ This dataset is named "{name}_store" in the Vega view.
41
+
42
+ Returns
43
+ -------
44
+ IndexSelection
45
+ """
46
+ if signal is None:
47
+ indices = []
48
+ else:
49
+ points = signal.get("vlPoint", {}).get("or", [])
50
+ indices = [p["_vgsid_"] - 1 for p in points]
51
+ return IndexSelection(name=name, value=indices, store=store)
52
+
53
+
54
+ @dataclass(frozen=True, eq=True)
55
+ class PointSelection:
56
+ """
57
+ Represents the state of an alt.selection_point() when the fields or encodings arguments are specified.
58
+
59
+ The value field is a list of dicts of the form:
60
+ [{"dim1": 1, "dim2": "A"}, {"dim1": 2, "dim2": "BB"}]
61
+
62
+ where "dim1" and "dim2" are dataset columns and the dict values
63
+ correspond to the specific selected values.
64
+ """
65
+
66
+ name: str
67
+ value: list[dict[str, Any]]
68
+ store: Store
69
+
70
+ @staticmethod
71
+ def from_vega(name: str, signal: dict[str, dict] | None, store: Store):
72
+ """
73
+ Construct a PointSelection from the raw Vega signal and dataset values.
74
+
75
+ Parameters
76
+ ----------
77
+ name: str
78
+ The selection's name
79
+ signal: dict or None
80
+ The value of the Vega signal corresponding to the selection
81
+ store: list
82
+ The value of the Vega dataset corresponding to the selection.
83
+ This dataset is named "{name}_store" in the Vega view.
84
+
85
+ Returns
86
+ -------
87
+ PointSelection
88
+ """
89
+ points = [] if signal is None else signal.get("vlPoint", {}).get("or", [])
90
+ return PointSelection(name=name, value=points, store=store)
91
+
92
+
93
+ @dataclass(frozen=True, eq=True)
94
+ class IntervalSelection:
95
+ """
96
+ Represents the state of an alt.selection_interval().
97
+
98
+ The value field is a dict of the form:
99
+ {"dim1": [0, 10], "dim2": ["A", "BB", "CCC"]}
100
+
101
+ where "dim1" and "dim2" are dataset columns and the dict values
102
+ correspond to the selected range.
103
+ """
104
+
105
+ name: str
106
+ value: dict[str, list]
107
+ store: Store
108
+
109
+ @staticmethod
110
+ def from_vega(name: str, signal: dict[str, list] | None, store: Store):
111
+ """
112
+ Construct an IntervalSelection from the raw Vega signal and dataset values.
113
+
114
+ Parameters
115
+ ----------
116
+ name: str
117
+ The selection's name
118
+ signal: dict or None
119
+ The value of the Vega signal corresponding to the selection
120
+ store: list
121
+ The value of the Vega dataset corresponding to the selection.
122
+ This dataset is named "{name}_store" in the Vega view.
123
+
124
+ Returns
125
+ -------
126
+ PointSelection
127
+ """
128
+ if signal is None:
129
+ signal = {}
130
+ return IntervalSelection(name=name, value=signal, store=store)
.venv/lib/python3.13/site-packages/altair/utils/server.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A Simple server used to show altair graphics from a prompt or script.
3
+
4
+ This is adapted from the mpld3 package; see
5
+ https://github.com/mpld3/mpld3/blob/master/mpld3/_server.py
6
+ """
7
+
8
+ import itertools
9
+ import random
10
+ import socket
11
+ import sys
12
+ import threading
13
+ import webbrowser
14
+ from http import server
15
+ from io import BytesIO as IO
16
+
17
+ JUPYTER_WARNING = """
18
+ Note: if you're in the Jupyter notebook, Chart.serve() is not the best
19
+ way to view plots. Consider using Chart.display().
20
+ You must interrupt the kernel to cancel this command.
21
+ """
22
+
23
+
24
+ # Mock server used for testing
25
+
26
+
27
+ class MockRequest:
28
+ def makefile(self, *args, **kwargs):
29
+ return IO(b"GET /")
30
+
31
+ def sendall(self, response):
32
+ pass
33
+
34
+
35
+ class MockServer:
36
+ def __init__(self, ip_port, Handler):
37
+ Handler(MockRequest(), ip_port[0], self)
38
+
39
+ def serve_forever(self):
40
+ pass
41
+
42
+ def server_close(self):
43
+ pass
44
+
45
+
46
+ def generate_handler(html, files=None):
47
+ if files is None:
48
+ files = {}
49
+
50
+ class MyHandler(server.BaseHTTPRequestHandler):
51
+ def do_GET(self):
52
+ """Respond to a GET request."""
53
+ if self.path == "/":
54
+ self.send_response(200)
55
+ self.send_header("Content-type", "text/html")
56
+ self.end_headers()
57
+ self.wfile.write(html.encode())
58
+ elif self.path in files:
59
+ content_type, content = files[self.path]
60
+ self.send_response(200)
61
+ self.send_header("Content-type", content_type)
62
+ self.end_headers()
63
+ self.wfile.write(content.encode())
64
+ else:
65
+ self.send_error(404)
66
+
67
+ return MyHandler
68
+
69
+
70
+ def find_open_port(ip, port, n=50):
71
+ """Find an open port near the specified port."""
72
+ ports = itertools.chain(
73
+ (port + i for i in range(n)), (port + random.randint(-2 * n, 2 * n))
74
+ )
75
+
76
+ for port in ports:
77
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
78
+ result = s.connect_ex((ip, port))
79
+ s.close()
80
+ if result != 0:
81
+ return port
82
+ msg = "no open ports found"
83
+ raise ValueError(msg)
84
+
85
+
86
+ def serve(
87
+ html,
88
+ ip="127.0.0.1",
89
+ port=8888,
90
+ n_retries=50,
91
+ files=None,
92
+ jupyter_warning=True,
93
+ open_browser=True,
94
+ http_server=None,
95
+ ) -> None:
96
+ """
97
+ Start a server serving the given HTML, and (optionally) open a browser.
98
+
99
+ Parameters
100
+ ----------
101
+ html : string
102
+ HTML to serve
103
+ ip : string (default = '127.0.0.1')
104
+ ip address at which the HTML will be served.
105
+ port : int (default = 8888)
106
+ the port at which to serve the HTML
107
+ n_retries : int (default = 50)
108
+ the number of nearby ports to search if the specified port is in use.
109
+ files : dictionary (optional)
110
+ dictionary of extra content to serve
111
+ jupyter_warning : bool (optional)
112
+ if True (default), then print a warning if this is used within Jupyter
113
+ open_browser : bool (optional)
114
+ if True (default), then open a web browser to the given HTML
115
+ http_server : class (optional)
116
+ optionally specify an HTTPServer class to use for showing the
117
+ figure. The default is Python's basic HTTPServer.
118
+ """
119
+ port = find_open_port(ip, port, n_retries)
120
+ Handler = generate_handler(html, files)
121
+
122
+ if http_server is None:
123
+ srvr = server.HTTPServer((ip, port), Handler)
124
+ else:
125
+ srvr = http_server((ip, port), Handler)
126
+
127
+ if jupyter_warning:
128
+ try:
129
+ __IPYTHON__ # type: ignore # noqa
130
+ except NameError:
131
+ pass
132
+ else:
133
+ print(JUPYTER_WARNING)
134
+
135
+ # Start the server
136
+ print(f"Serving to http://{ip}:{port}/ [Ctrl-C to exit]")
137
+ sys.stdout.flush()
138
+
139
+ if open_browser:
140
+ # Use a thread to open a web browser pointing to the server
141
+ def b():
142
+ return webbrowser.open(f"http://{ip}:{port}")
143
+
144
+ threading.Thread(target=b).start()
145
+
146
+ try:
147
+ srvr.serve_forever()
148
+ except (KeyboardInterrupt, SystemExit):
149
+ print("\nstopping Server...")
150
+
151
+ srvr.server_close()
.venv/lib/python3.13/site-packages/altair/vegalite/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # ruff: noqa: F403
2
+ from .v6 import *
.venv/lib/python3.13/site-packages/altair/vegalite/api.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # ruff: noqa
2
+ from .v6.api import *
.venv/lib/python3.13/site-packages/altair/vegalite/data.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, overload
4
+
5
+ from altair.utils.core import sanitize_pandas_dataframe
6
+ from altair.utils.data import DataTransformerRegistry as _DataTransformerRegistry
7
+ from altair.utils.data import (
8
+ MaxRowsError,
9
+ check_data_type,
10
+ limit_rows,
11
+ sample,
12
+ to_csv,
13
+ to_json,
14
+ to_values,
15
+ )
16
+
17
+ if TYPE_CHECKING:
18
+ from collections.abc import Callable
19
+
20
+ from altair.utils.data import DataType, ToValuesReturnType
21
+ from altair.utils.plugin_registry import PluginEnabler
22
+
23
+
24
+ @overload
25
+ def default_data_transformer(
26
+ data: None = ..., max_rows: int = ...
27
+ ) -> Callable[[DataType], ToValuesReturnType]: ...
28
+ @overload
29
+ def default_data_transformer(
30
+ data: DataType, max_rows: int = ...
31
+ ) -> ToValuesReturnType: ...
32
+ def default_data_transformer(
33
+ data: DataType | None = None, max_rows: int = 5000
34
+ ) -> Callable[[DataType], ToValuesReturnType] | ToValuesReturnType:
35
+ if data is None:
36
+
37
+ def pipe(data: DataType, /) -> ToValuesReturnType:
38
+ data = limit_rows(data, max_rows=max_rows)
39
+ return to_values(data)
40
+
41
+ return pipe
42
+
43
+ else:
44
+ return to_values(limit_rows(data, max_rows=max_rows))
45
+
46
+
47
+ class DataTransformerRegistry(_DataTransformerRegistry):
48
+ def disable_max_rows(self) -> PluginEnabler:
49
+ """Disable the MaxRowsError."""
50
+ options = self.options
51
+ if self.active in {"default", "vegafusion"}:
52
+ options = options.copy()
53
+ options["max_rows"] = None
54
+ return self.enable(**options)
55
+
56
+
57
+ __all__ = (
58
+ "DataTransformerRegistry",
59
+ "MaxRowsError",
60
+ "check_data_type",
61
+ "default_data_transformer",
62
+ "limit_rows",
63
+ "sample",
64
+ "sanitize_pandas_dataframe",
65
+ "to_csv",
66
+ "to_json",
67
+ "to_values",
68
+ )
.venv/lib/python3.13/site-packages/altair/vegalite/display.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from altair.utils.display import (
2
+ DefaultRendererReturnType,
3
+ Displayable,
4
+ HTMLRenderer,
5
+ RendererRegistry,
6
+ default_renderer_base,
7
+ json_renderer_base,
8
+ )
9
+
10
+ __all__ = (
11
+ "DefaultRendererReturnType",
12
+ "Displayable",
13
+ "HTMLRenderer",
14
+ "RendererRegistry",
15
+ "default_renderer_base",
16
+ "json_renderer_base",
17
+ )
.venv/lib/python3.13/site-packages/altair/vegalite/schema.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """Altair schema wrappers."""
2
+
3
+ # ruff: noqa: F403
4
+ from .v6.schema import *
.venv/lib/python3.13/site-packages/altair/vegalite/v6/__init__.py ADDED
@@ -0,0 +1,659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ruff: noqa: F403, F405
2
+ from altair.expr.core import datum
3
+ from altair.vegalite.v6 import api, compiler, schema
4
+ from altair.vegalite.v6.api import *
5
+ from altair.vegalite.v6.compiler import vegalite_compilers
6
+ from altair.vegalite.v6.data import (
7
+ MaxRowsError,
8
+ data_transformers,
9
+ default_data_transformer,
10
+ limit_rows,
11
+ sample,
12
+ to_csv,
13
+ to_json,
14
+ to_values,
15
+ )
16
+ from altair.vegalite.v6.display import (
17
+ VEGA_VERSION,
18
+ VEGAEMBED_VERSION,
19
+ VEGALITE_VERSION,
20
+ VegaLite,
21
+ renderers,
22
+ )
23
+ from altair.vegalite.v6.schema import *
24
+
25
+ # The content of __all__ is automatically written by
26
+ # tools/update_init_file.py. Do not modify directly.
27
+
28
+ __all__ = [
29
+ "SCHEMA_URL",
30
+ "SCHEMA_VERSION",
31
+ "TOPLEVEL_ONLY_KEYS",
32
+ "URI",
33
+ "VEGAEMBED_VERSION",
34
+ "VEGALITE_VERSION",
35
+ "VEGA_VERSION",
36
+ "X2",
37
+ "Y2",
38
+ "Aggregate",
39
+ "AggregateOp",
40
+ "AggregateTransform",
41
+ "AggregatedFieldDef",
42
+ "Align",
43
+ "AllSortString",
44
+ "Angle",
45
+ "AngleDatum",
46
+ "AngleValue",
47
+ "AnyMark",
48
+ "AnyMarkConfig",
49
+ "AreaConfig",
50
+ "ArgmaxDef",
51
+ "ArgminDef",
52
+ "AutoSizeParams",
53
+ "AutosizeType",
54
+ "Axis",
55
+ "AxisConfig",
56
+ "AxisOrient",
57
+ "AxisResolveMap",
58
+ "BBox",
59
+ "BarConfig",
60
+ "BaseTitleNoValueRefs",
61
+ "Baseline",
62
+ "Bin",
63
+ "BinExtent",
64
+ "BinParams",
65
+ "BinTransform",
66
+ "BindCheckbox",
67
+ "BindDirect",
68
+ "BindInput",
69
+ "BindRadioSelect",
70
+ "BindRange",
71
+ "Binding",
72
+ "BinnedTimeUnit",
73
+ "Blend",
74
+ "BoxPlot",
75
+ "BoxPlotConfig",
76
+ "BoxPlotDef",
77
+ "BrushConfig",
78
+ "CalculateTransform",
79
+ "Categorical",
80
+ "ChainedWhen",
81
+ "Chart",
82
+ "ChartDataType",
83
+ "Color",
84
+ "ColorDatum",
85
+ "ColorDef",
86
+ "ColorName",
87
+ "ColorScheme",
88
+ "ColorValue",
89
+ "Column",
90
+ "CompositeMark",
91
+ "CompositeMarkDef",
92
+ "CompositionConfig",
93
+ "ConcatChart",
94
+ "ConcatSpecGenericSpec",
95
+ "ConditionalAxisColor",
96
+ "ConditionalAxisLabelAlign",
97
+ "ConditionalAxisLabelBaseline",
98
+ "ConditionalAxisLabelFontStyle",
99
+ "ConditionalAxisLabelFontWeight",
100
+ "ConditionalAxisNumber",
101
+ "ConditionalAxisNumberArray",
102
+ "ConditionalAxisPropertyAlignnull",
103
+ "ConditionalAxisPropertyColornull",
104
+ "ConditionalAxisPropertyFontStylenull",
105
+ "ConditionalAxisPropertyFontWeightnull",
106
+ "ConditionalAxisPropertyTextBaselinenull",
107
+ "ConditionalAxisPropertynumberArraynull",
108
+ "ConditionalAxisPropertynumbernull",
109
+ "ConditionalAxisPropertystringnull",
110
+ "ConditionalAxisString",
111
+ "ConditionalMarkPropFieldOrDatumDef",
112
+ "ConditionalMarkPropFieldOrDatumDefTypeForShape",
113
+ "ConditionalParameterMarkPropFieldOrDatumDef",
114
+ "ConditionalParameterMarkPropFieldOrDatumDefTypeForShape",
115
+ "ConditionalParameterStringFieldDef",
116
+ "ConditionalParameterValueDefGradientstringnullExprRef",
117
+ "ConditionalParameterValueDefTextExprRef",
118
+ "ConditionalParameterValueDefnumber",
119
+ "ConditionalParameterValueDefnumberArrayExprRef",
120
+ "ConditionalParameterValueDefnumberExprRef",
121
+ "ConditionalParameterValueDefstringExprRef",
122
+ "ConditionalParameterValueDefstringnullExprRef",
123
+ "ConditionalPredicateMarkPropFieldOrDatumDef",
124
+ "ConditionalPredicateMarkPropFieldOrDatumDefTypeForShape",
125
+ "ConditionalPredicateStringFieldDef",
126
+ "ConditionalPredicateValueDefAlignnullExprRef",
127
+ "ConditionalPredicateValueDefColornullExprRef",
128
+ "ConditionalPredicateValueDefFontStylenullExprRef",
129
+ "ConditionalPredicateValueDefFontWeightnullExprRef",
130
+ "ConditionalPredicateValueDefGradientstringnullExprRef",
131
+ "ConditionalPredicateValueDefTextBaselinenullExprRef",
132
+ "ConditionalPredicateValueDefTextExprRef",
133
+ "ConditionalPredicateValueDefnumber",
134
+ "ConditionalPredicateValueDefnumberArrayExprRef",
135
+ "ConditionalPredicateValueDefnumberArraynullExprRef",
136
+ "ConditionalPredicateValueDefnumberExprRef",
137
+ "ConditionalPredicateValueDefnumbernullExprRef",
138
+ "ConditionalPredicateValueDefstringExprRef",
139
+ "ConditionalPredicateValueDefstringnullExprRef",
140
+ "ConditionalStringFieldDef",
141
+ "ConditionalValueDefGradientstringnullExprRef",
142
+ "ConditionalValueDefTextExprRef",
143
+ "ConditionalValueDefnumber",
144
+ "ConditionalValueDefnumberArrayExprRef",
145
+ "ConditionalValueDefnumberExprRef",
146
+ "ConditionalValueDefstringExprRef",
147
+ "ConditionalValueDefstringnullExprRef",
148
+ "Config",
149
+ "CsvDataFormat",
150
+ "Cursor",
151
+ "Cyclical",
152
+ "Data",
153
+ "DataFormat",
154
+ "DataSource",
155
+ "DataType",
156
+ "Datasets",
157
+ "DateTime",
158
+ "DatumChannelMixin",
159
+ "DatumDef",
160
+ "Day",
161
+ "DensityTransform",
162
+ "DerivedStream",
163
+ "Description",
164
+ "DescriptionValue",
165
+ "Detail",
166
+ "DictInlineDataset",
167
+ "DictSelectionInit",
168
+ "DictSelectionInitInterval",
169
+ "Diverging",
170
+ "DomainUnionWith",
171
+ "DsvDataFormat",
172
+ "Element",
173
+ "Encoding",
174
+ "EncodingSortField",
175
+ "ErrorBand",
176
+ "ErrorBandConfig",
177
+ "ErrorBandDef",
178
+ "ErrorBar",
179
+ "ErrorBarConfig",
180
+ "ErrorBarDef",
181
+ "ErrorBarExtent",
182
+ "EventStream",
183
+ "EventType",
184
+ "Expr",
185
+ "ExprRef",
186
+ "ExtentTransform",
187
+ "Facet",
188
+ "FacetChart",
189
+ "FacetEncodingFieldDef",
190
+ "FacetFieldDef",
191
+ "FacetMapping",
192
+ "FacetSpec",
193
+ "FacetedEncoding",
194
+ "FacetedUnitSpec",
195
+ "Feature",
196
+ "FeatureCollection",
197
+ "FeatureGeometryGeoJsonProperties",
198
+ "Field",
199
+ "FieldChannelMixin",
200
+ "FieldDefWithoutScale",
201
+ "FieldEqualPredicate",
202
+ "FieldGTEPredicate",
203
+ "FieldGTPredicate",
204
+ "FieldLTEPredicate",
205
+ "FieldLTPredicate",
206
+ "FieldName",
207
+ "FieldOneOfPredicate",
208
+ "FieldOrDatumDefWithConditionDatumDefGradientstringnull",
209
+ "FieldOrDatumDefWithConditionDatumDefnumber",
210
+ "FieldOrDatumDefWithConditionDatumDefnumberArray",
211
+ "FieldOrDatumDefWithConditionDatumDefstringnull",
212
+ "FieldOrDatumDefWithConditionMarkPropFieldDefGradientstringnull",
213
+ "FieldOrDatumDefWithConditionMarkPropFieldDefTypeForShapestringnull",
214
+ "FieldOrDatumDefWithConditionMarkPropFieldDefnumber",
215
+ "FieldOrDatumDefWithConditionMarkPropFieldDefnumberArray",
216
+ "FieldOrDatumDefWithConditionStringDatumDefText",
217
+ "FieldOrDatumDefWithConditionStringFieldDefText",
218
+ "FieldOrDatumDefWithConditionStringFieldDefstring",
219
+ "FieldRange",
220
+ "FieldRangePredicate",
221
+ "FieldValidPredicate",
222
+ "Fill",
223
+ "FillDatum",
224
+ "FillOpacity",
225
+ "FillOpacityDatum",
226
+ "FillOpacityValue",
227
+ "FillValue",
228
+ "FilterTransform",
229
+ "Fit",
230
+ "FlattenTransform",
231
+ "FoldTransform",
232
+ "FontStyle",
233
+ "FontWeight",
234
+ "Format",
235
+ "FormatConfig",
236
+ "Generator",
237
+ "GenericUnitSpecEncodingAnyMark",
238
+ "GeoJsonFeature",
239
+ "GeoJsonFeatureCollection",
240
+ "GeoJsonProperties",
241
+ "Geometry",
242
+ "GeometryCollection",
243
+ "Gradient",
244
+ "GradientStop",
245
+ "GraticuleGenerator",
246
+ "GraticuleParams",
247
+ "HConcatChart",
248
+ "HConcatSpecGenericSpec",
249
+ "Header",
250
+ "HeaderConfig",
251
+ "HexColor",
252
+ "Href",
253
+ "HrefValue",
254
+ "Impute",
255
+ "ImputeMethod",
256
+ "ImputeParams",
257
+ "ImputeSequence",
258
+ "ImputeTransform",
259
+ "InlineData",
260
+ "InlineDataset",
261
+ "Interpolate",
262
+ "IntervalSelectionConfig",
263
+ "IntervalSelectionConfigWithoutType",
264
+ "JoinAggregateFieldDef",
265
+ "JoinAggregateTransform",
266
+ "JsonDataFormat",
267
+ "Key",
268
+ "LabelOverlap",
269
+ "LatLongDef",
270
+ "LatLongFieldDef",
271
+ "Latitude",
272
+ "Latitude2",
273
+ "Latitude2Datum",
274
+ "Latitude2Value",
275
+ "LatitudeDatum",
276
+ "LayerChart",
277
+ "LayerRepeatMapping",
278
+ "LayerRepeatSpec",
279
+ "LayerSpec",
280
+ "LayoutAlign",
281
+ "Legend",
282
+ "LegendBinding",
283
+ "LegendConfig",
284
+ "LegendOrient",
285
+ "LegendResolveMap",
286
+ "LegendStreamBinding",
287
+ "LineConfig",
288
+ "LineString",
289
+ "LinearGradient",
290
+ "LocalMultiTimeUnit",
291
+ "LocalSingleTimeUnit",
292
+ "Locale",
293
+ "LoessTransform",
294
+ "LogicalAndPredicate",
295
+ "LogicalNotPredicate",
296
+ "LogicalOrPredicate",
297
+ "Longitude",
298
+ "Longitude2",
299
+ "Longitude2Datum",
300
+ "Longitude2Value",
301
+ "LongitudeDatum",
302
+ "LookupData",
303
+ "LookupSelection",
304
+ "LookupTransform",
305
+ "Mark",
306
+ "MarkConfig",
307
+ "MarkDef",
308
+ "MarkInvalidDataMode",
309
+ "MarkPropDefGradientstringnull",
310
+ "MarkPropDefnumber",
311
+ "MarkPropDefnumberArray",
312
+ "MarkPropDefstringnullTypeForShape",
313
+ "MarkType",
314
+ "MaxRowsError",
315
+ "MergedStream",
316
+ "Month",
317
+ "MultiLineString",
318
+ "MultiPoint",
319
+ "MultiPolygon",
320
+ "MultiTimeUnit",
321
+ "NamedData",
322
+ "NonArgAggregateOp",
323
+ "NonLayerRepeatSpec",
324
+ "NonNormalizedSpec",
325
+ "NumberLocale",
326
+ "NumericArrayMarkPropDef",
327
+ "NumericMarkPropDef",
328
+ "OffsetDef",
329
+ "Opacity",
330
+ "OpacityDatum",
331
+ "OpacityValue",
332
+ "Order",
333
+ "OrderFieldDef",
334
+ "OrderOnlyDef",
335
+ "OrderValue",
336
+ "OrderValueDef",
337
+ "Orient",
338
+ "Orientation",
339
+ "OverlayMarkDef",
340
+ "Padding",
341
+ "Parameter",
342
+ "ParameterExpression",
343
+ "ParameterExtent",
344
+ "ParameterName",
345
+ "ParameterPredicate",
346
+ "Parse",
347
+ "ParseValue",
348
+ "PivotTransform",
349
+ "Point",
350
+ "PointSelectionConfig",
351
+ "PointSelectionConfigWithoutType",
352
+ "PolarDef",
353
+ "Polygon",
354
+ "Position",
355
+ "Position2Def",
356
+ "PositionDatumDef",
357
+ "PositionDatumDefBase",
358
+ "PositionDef",
359
+ "PositionFieldDef",
360
+ "PositionFieldDefBase",
361
+ "PositionValueDef",
362
+ "Predicate",
363
+ "PredicateComposition",
364
+ "PrimitiveValue",
365
+ "Projection",
366
+ "ProjectionConfig",
367
+ "ProjectionType",
368
+ "QuantileTransform",
369
+ "RadialGradient",
370
+ "Radius",
371
+ "Radius2",
372
+ "Radius2Datum",
373
+ "Radius2Value",
374
+ "RadiusDatum",
375
+ "RadiusValue",
376
+ "RangeConfig",
377
+ "RangeEnum",
378
+ "RangeRaw",
379
+ "RangeRawArray",
380
+ "RangeScheme",
381
+ "RectConfig",
382
+ "RegressionTransform",
383
+ "RelativeBandSize",
384
+ "RepeatChart",
385
+ "RepeatMapping",
386
+ "RepeatRef",
387
+ "RepeatSpec",
388
+ "Resolve",
389
+ "ResolveMode",
390
+ "Root",
391
+ "Row",
392
+ "RowColLayoutAlign",
393
+ "RowColboolean",
394
+ "RowColnumber",
395
+ "RowColumnEncodingFieldDef",
396
+ "SampleTransform",
397
+ "Scale",
398
+ "ScaleBinParams",
399
+ "ScaleBins",
400
+ "ScaleConfig",
401
+ "ScaleDatumDef",
402
+ "ScaleFieldDef",
403
+ "ScaleInterpolateEnum",
404
+ "ScaleInterpolateParams",
405
+ "ScaleInvalidDataConfig",
406
+ "ScaleInvalidDataShowAsValueangle",
407
+ "ScaleInvalidDataShowAsValuecolor",
408
+ "ScaleInvalidDataShowAsValuefill",
409
+ "ScaleInvalidDataShowAsValuefillOpacity",
410
+ "ScaleInvalidDataShowAsValueopacity",
411
+ "ScaleInvalidDataShowAsValueradius",
412
+ "ScaleInvalidDataShowAsValueshape",
413
+ "ScaleInvalidDataShowAsValuesize",
414
+ "ScaleInvalidDataShowAsValuestroke",
415
+ "ScaleInvalidDataShowAsValuestrokeDash",
416
+ "ScaleInvalidDataShowAsValuestrokeOpacity",
417
+ "ScaleInvalidDataShowAsValuestrokeWidth",
418
+ "ScaleInvalidDataShowAsValuetheta",
419
+ "ScaleInvalidDataShowAsValuetime",
420
+ "ScaleInvalidDataShowAsValuex",
421
+ "ScaleInvalidDataShowAsValuexOffset",
422
+ "ScaleInvalidDataShowAsValuey",
423
+ "ScaleInvalidDataShowAsValueyOffset",
424
+ "ScaleInvalidDataShowAsangle",
425
+ "ScaleInvalidDataShowAscolor",
426
+ "ScaleInvalidDataShowAsfill",
427
+ "ScaleInvalidDataShowAsfillOpacity",
428
+ "ScaleInvalidDataShowAsopacity",
429
+ "ScaleInvalidDataShowAsradius",
430
+ "ScaleInvalidDataShowAsshape",
431
+ "ScaleInvalidDataShowAssize",
432
+ "ScaleInvalidDataShowAsstroke",
433
+ "ScaleInvalidDataShowAsstrokeDash",
434
+ "ScaleInvalidDataShowAsstrokeOpacity",
435
+ "ScaleInvalidDataShowAsstrokeWidth",
436
+ "ScaleInvalidDataShowAstheta",
437
+ "ScaleInvalidDataShowAstime",
438
+ "ScaleInvalidDataShowAsx",
439
+ "ScaleInvalidDataShowAsxOffset",
440
+ "ScaleInvalidDataShowAsy",
441
+ "ScaleInvalidDataShowAsyOffset",
442
+ "ScaleResolveMap",
443
+ "ScaleType",
444
+ "SchemaBase",
445
+ "SchemeParams",
446
+ "SecondaryFieldDef",
447
+ "SelectionConfig",
448
+ "SelectionExpression",
449
+ "SelectionInit",
450
+ "SelectionInitInterval",
451
+ "SelectionInitIntervalMapping",
452
+ "SelectionInitMapping",
453
+ "SelectionParameter",
454
+ "SelectionPredicateComposition",
455
+ "SelectionResolution",
456
+ "SelectionType",
457
+ "SequenceGenerator",
458
+ "SequenceParams",
459
+ "SequentialMultiHue",
460
+ "SequentialSingleHue",
461
+ "Shape",
462
+ "ShapeDatum",
463
+ "ShapeDef",
464
+ "ShapeValue",
465
+ "SharedEncoding",
466
+ "SingleDefUnitChannel",
467
+ "SingleTimeUnit",
468
+ "Size",
469
+ "SizeDatum",
470
+ "SizeValue",
471
+ "Sort",
472
+ "SortArray",
473
+ "SortByChannel",
474
+ "SortByChannelDesc",
475
+ "SortByEncoding",
476
+ "SortField",
477
+ "SortOrder",
478
+ "Spec",
479
+ "SphereGenerator",
480
+ "StackOffset",
481
+ "StackTransform",
482
+ "StandardType",
483
+ "Step",
484
+ "StepFor",
485
+ "Stream",
486
+ "StringFieldDef",
487
+ "StringFieldDefWithCondition",
488
+ "StringValueDefWithCondition",
489
+ "Stroke",
490
+ "StrokeCap",
491
+ "StrokeDash",
492
+ "StrokeDashDatum",
493
+ "StrokeDashValue",
494
+ "StrokeDatum",
495
+ "StrokeJoin",
496
+ "StrokeOpacity",
497
+ "StrokeOpacityDatum",
498
+ "StrokeOpacityValue",
499
+ "StrokeValue",
500
+ "StrokeWidth",
501
+ "StrokeWidthDatum",
502
+ "StrokeWidthValue",
503
+ "StyleConfigIndex",
504
+ "SymbolShape",
505
+ "Text",
506
+ "TextBaseline",
507
+ "TextDatum",
508
+ "TextDef",
509
+ "TextDirection",
510
+ "TextValue",
511
+ "Then",
512
+ "Theta",
513
+ "Theta2",
514
+ "Theta2Datum",
515
+ "Theta2Value",
516
+ "ThetaDatum",
517
+ "ThetaValue",
518
+ "TickConfig",
519
+ "TickCount",
520
+ "Time",
521
+ "TimeDef",
522
+ "TimeFieldDef",
523
+ "TimeFormatSpecifier",
524
+ "TimeInterval",
525
+ "TimeIntervalStep",
526
+ "TimeLocale",
527
+ "TimeUnit",
528
+ "TimeUnitParams",
529
+ "TimeUnitTransform",
530
+ "TimeUnitTransformParams",
531
+ "Title",
532
+ "TitleAnchor",
533
+ "TitleConfig",
534
+ "TitleFrame",
535
+ "TitleOrient",
536
+ "TitleParams",
537
+ "Tooltip",
538
+ "TooltipContent",
539
+ "TooltipValue",
540
+ "TopLevelConcatSpec",
541
+ "TopLevelFacetSpec",
542
+ "TopLevelHConcatSpec",
543
+ "TopLevelLayerSpec",
544
+ "TopLevelMixin",
545
+ "TopLevelParameter",
546
+ "TopLevelRepeatSpec",
547
+ "TopLevelSelectionParameter",
548
+ "TopLevelSpec",
549
+ "TopLevelUnitSpec",
550
+ "TopLevelVConcatSpec",
551
+ "TopoDataFormat",
552
+ "Transform",
553
+ "Type",
554
+ "TypeForShape",
555
+ "TypedFieldDef",
556
+ "UnitSpec",
557
+ "UnitSpecWithFrame",
558
+ "Url",
559
+ "UrlData",
560
+ "UrlValue",
561
+ "UtcMultiTimeUnit",
562
+ "UtcSingleTimeUnit",
563
+ "VConcatChart",
564
+ "VConcatSpecGenericSpec",
565
+ "ValueChannelMixin",
566
+ "ValueDefWithConditionMarkPropFieldOrDatumDefGradientstringnull",
567
+ "ValueDefWithConditionMarkPropFieldOrDatumDefTypeForShapestringnull",
568
+ "ValueDefWithConditionMarkPropFieldOrDatumDefnumber",
569
+ "ValueDefWithConditionMarkPropFieldOrDatumDefnumberArray",
570
+ "ValueDefWithConditionMarkPropFieldOrDatumDefstringnull",
571
+ "ValueDefWithConditionStringFieldDefText",
572
+ "ValueDefnumber",
573
+ "ValueDefnumberwidthheightExprRef",
574
+ "VariableParameter",
575
+ "Vector2DateTime",
576
+ "Vector2Vector2number",
577
+ "Vector2boolean",
578
+ "Vector2number",
579
+ "Vector2string",
580
+ "Vector3number",
581
+ "Vector7string",
582
+ "Vector10string",
583
+ "Vector12string",
584
+ "VegaLite",
585
+ "VegaLiteSchema",
586
+ "ViewBackground",
587
+ "ViewConfig",
588
+ "When",
589
+ "WindowEventType",
590
+ "WindowFieldDef",
591
+ "WindowOnlyOp",
592
+ "WindowTransform",
593
+ "X",
594
+ "X2Datum",
595
+ "X2Value",
596
+ "XDatum",
597
+ "XError",
598
+ "XError2",
599
+ "XError2Value",
600
+ "XErrorValue",
601
+ "XOffset",
602
+ "XOffsetDatum",
603
+ "XOffsetValue",
604
+ "XValue",
605
+ "Y",
606
+ "Y2Datum",
607
+ "Y2Value",
608
+ "YDatum",
609
+ "YError",
610
+ "YError2",
611
+ "YError2Value",
612
+ "YErrorValue",
613
+ "YOffset",
614
+ "YOffsetDatum",
615
+ "YOffsetValue",
616
+ "YValue",
617
+ "api",
618
+ "binding",
619
+ "binding_checkbox",
620
+ "binding_radio",
621
+ "binding_range",
622
+ "binding_select",
623
+ "channels",
624
+ "check_fields_and_encodings",
625
+ "compiler",
626
+ "concat",
627
+ "condition",
628
+ "core",
629
+ "data_transformers",
630
+ "datum",
631
+ "default_data_transformer",
632
+ "graticule",
633
+ "hconcat",
634
+ "layer",
635
+ "limit_rows",
636
+ "load_schema",
637
+ "mixins",
638
+ "param",
639
+ "renderers",
640
+ "repeat",
641
+ "sample",
642
+ "schema",
643
+ "selection",
644
+ "selection_interval",
645
+ "selection_multi",
646
+ "selection_point",
647
+ "selection_single",
648
+ "sequence",
649
+ "sphere",
650
+ "to_csv",
651
+ "to_json",
652
+ "to_values",
653
+ "topo_feature",
654
+ "value",
655
+ "vconcat",
656
+ "vegalite_compilers",
657
+ "when",
658
+ "with_property_setters",
659
+ ]
.venv/lib/python3.13/site-packages/altair/vegalite/v6/api.py ADDED
The diff for this file is too large to render. See raw diff