diff --git a/.gitattributes b/.gitattributes index 398da729bce4c7292b76723a0e9f2d86d96c5420..577cb4f8a35d6d5d903fa85a4e8ddc33e7e270de 100644 --- a/.gitattributes +++ b/.gitattributes @@ -605,3 +605,109 @@ py311/lib/python3.11/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBol. .venv/lib/python3.13/site-packages/jax/_src/lax/__pycache__/lax.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.13/site-packages/jax/_src/lax/__pycache__/parallel.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text .venv/lib/python3.13/site-packages/jax/_src/lax/__pycache__/slicing.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/_src/lax/__pycache__/linalg.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/_src/lax/control_flow/__pycache__/loops.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/_src/scipy/__pycache__/linalg.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/_src/scipy/__pycache__/special.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/_src/pallas/mosaic/__pycache__/pipeline.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/_src/pallas/mosaic_gpu/__pycache__/primitives.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/_src/pallas/mosaic_gpu/__pycache__/lowering.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/_src/pallas/fuser/__pycache__/block_spec.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/_src/export/__pycache__/shape_poly.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/_src/internal_test_util/__pycache__/test_harnesses.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/_src/pallas/triton/__pycache__/lowering.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/_src/pallas/mosaic/__pycache__/lowering.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/experimental/sparse/__pycache__/bcoo.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/experimental/mosaic/gpu/__pycache__/layout_inference.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/experimental/mosaic/gpu/__pycache__/utils.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/experimental/mosaic/gpu/__pycache__/dialect_lowering.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/jax/experimental/mosaic/gpu/__pycache__/fragmented_array.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/fft/_pocketfft_umath.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/_core/_multiarray_tests.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/imageio_ffmpeg/binaries/ffmpeg-linux-x86_64-v7.0.2 filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/_core/_simd.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/_core/_multiarray_umath.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/random/_generator.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/random/bit_generator.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/random/_philox.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/random/_mt19937.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/random/mtrand.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/random/_bounded_integers.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/random/_pcg64.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/random/_common.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/linalg/_umath_linalg.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/linalg/__pycache__/_linalg.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/f2py/__pycache__/crackfortran.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/_core/__pycache__/fromnumeric.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/_core/__pycache__/_add_newdocs.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/ma/__pycache__/core.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/testing/_private/__pycache__/utils.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.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 +.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 +.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 +.venv/lib/python3.13/site-packages/virtualenv/seed/wheels/embed/pip-25.3-py3-none-any.whl filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/numpy/lib/__pycache__/_function_base_impl.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/pyparsing/__pycache__/core.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/networkx/drawing/__pycache__/nx_pylab.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/networkx/drawing/tests/baseline/test_display_complex.png filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/idna/__pycache__/idnadata.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/PIL/__pycache__/Image.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/aiohttp/_websocket/mask.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/aiohttp/_websocket/reader_c.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/tree/_criterion.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/utils/_seq_dataset.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/tree/_splitter.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/utils/arrayfuncs.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/utils/_typedefs.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/utils/sparsefuncs_fast.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/utils/_cython_blas.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/utils/murmurhash.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/utils/_random.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.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 +.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 +.venv/lib/python3.13/site-packages/sklearn/metrics/_dist_metrics.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/metrics/_pairwise_fast.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/tree/_utils.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/tree/_partitioner.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/tree/_tree.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/utils/_fast_dict.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/utils/_vector_sentinel.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.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 +.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 +.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 +.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 +.venv/lib/python3.13/site-packages/sklearn/_loss/_loss.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/svm/_libsvm_sparse.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/svm/_liblinear.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/svm/_libsvm.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.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 +.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 +.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 +.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 +.venv/lib/python3.13/site-packages/sklearn/cluster/_hierarchical_fast.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.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 +.venv/lib/python3.13/site-packages/sklearn/ensemble/_gradient_boosting.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.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 +.venv/lib/python3.13/site-packages/sklearn/neighbors/_ball_tree.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/neighbors/_quad_tree.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/neighbors/_kd_tree.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/model_selection/__pycache__/_split.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.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 +.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 +.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 +.venv/lib/python3.13/site-packages/sklearn/cluster/_hdbscan/_reachability.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/cluster/_hdbscan/_tree.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/cluster/_hdbscan/_linkage.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/datasets/images/china.jpg filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/datasets/images/flower.jpg filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/linear_model/__pycache__/_coordinate_descent.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/linear_model/__pycache__/_ridge.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.venv/lib/python3.13/site-packages/sklearn/utils/__pycache__/validation.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.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 +.venv/lib/python3.13/site-packages/sklearn/preprocessing/__pycache__/_data.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text +.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 +.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 +.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 +.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 +.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 +.venv/lib/python3.13/site-packages/sklearn/metrics/__pycache__/_classification.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/.venv/lib/python3.13/site-packages/PIL/__pycache__/Image.cpython-313.pyc b/.venv/lib/python3.13/site-packages/PIL/__pycache__/Image.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78537c1817ca22148c787c9fcde6b1f250869696 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/PIL/__pycache__/Image.cpython-313.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0e24ba70bfb1277dca909aec7222b556d475a836f63a3d82c002c4909dd07875 +size 172221 diff --git a/.venv/lib/python3.13/site-packages/absl_py-2.4.0.dist-info/licenses/AUTHORS b/.venv/lib/python3.13/site-packages/absl_py-2.4.0.dist-info/licenses/AUTHORS new file mode 100644 index 0000000000000000000000000000000000000000..23b11ada16bb8e69695cf52e5994784d98054e0d --- /dev/null +++ b/.venv/lib/python3.13/site-packages/absl_py-2.4.0.dist-info/licenses/AUTHORS @@ -0,0 +1,7 @@ +# This is the list of Abseil authors for copyright purposes. +# +# This does not necessarily list everyone who has contributed code, since in +# some cases, their employer may be the copyright holder. To see the full list +# of contributors, see the revision history in source control. + +Google Inc. diff --git a/.venv/lib/python3.13/site-packages/absl_py-2.4.0.dist-info/licenses/LICENSE b/.venv/lib/python3.13/site-packages/absl_py-2.4.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/absl_py-2.4.0.dist-info/licenses/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/.venv/lib/python3.13/site-packages/aiohttp/_websocket/mask.cpython-313-x86_64-linux-gnu.so b/.venv/lib/python3.13/site-packages/aiohttp/_websocket/mask.cpython-313-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..75068afb251384b9969e132546aa33da16cd32dd --- /dev/null +++ b/.venv/lib/python3.13/site-packages/aiohttp/_websocket/mask.cpython-313-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b61199dcc3562746e2109fd3bff9e652a2c7607ba8b0a86d7c72475ea9dc759 +size 246592 diff --git a/.venv/lib/python3.13/site-packages/aiohttp/_websocket/reader_c.cpython-313-x86_64-linux-gnu.so b/.venv/lib/python3.13/site-packages/aiohttp/_websocket/reader_c.cpython-313-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..33647ffd3ce6ffb60c719d977445e88627387b1a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/aiohttp/_websocket/reader_c.cpython-313-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92acbf3628015c2543e35d47394766064bc45af765d887181b8802db8ba297c8 +size 1821608 diff --git a/.venv/lib/python3.13/site-packages/altair/datasets/__init__.py b/.venv/lib/python3.13/site-packages/altair/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..84a3c3ba63ce7c44d5f2d916a65ed78a423338b2 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/datasets/__init__.py @@ -0,0 +1,183 @@ +""" +Load example datasets *remotely* from `vega-datasets`_. + +Provides **70+** datasets, used throughout our `Example Gallery`_. + +You can learn more about each dataset at `datapackage.md`_. + +Examples +-------- +**Primary Interface - Data Object**:: + + from altair.datasets import data + + # Load with default engine (pandas) + cars_df = data.cars() + + # Load with specific engine + cars_polars = data.cars(engine="polars") + cars_pyarrow = data.cars(engine="pyarrow") + + # Get URL + cars_url = data.cars.url + + # Set default engine for all datasets + data.set_default_engine("polars") + movies_df = data.movies() # Uses polars engine + + # List available datasets + available_datasets = data.list_datasets() + +**Expert Interface - Loader**:: + + from altair.datasets import Loader + + load = Loader.from_backend("polars") + load("penguins") + load.url("penguins") + +This method also provides *precise* Tab completions on the returned object:: + + load("cars"). + # bottom_k + # drop + # drop_in_place + # drop_nans + # dtypes + # ... + +**Expert Interface - Direct Functions**:: + + from altair.datasets import load, url + + # Load a dataset + cars_df = load("cars", backend="polars") + + # Get dataset URL + cars_url = url("cars") + +.. note:: + Requires installation of either `polars`_, `pandas`_, or `pyarrow`_. + +.. _vega-datasets: + https://github.com/vega/vega-datasets +.. _Example Gallery: + https://altair-viz.github.io/gallery/index.html#example-gallery +.. _datapackage.md: + https://github.com/vega/vega-datasets/blob/main/datapackage.md +.. _polars: + https://docs.pola.rs/user-guide/installation/ +.. _pandas: + https://pandas.pydata.org/docs/getting_started/install.html +.. _pyarrow: + https://arrow.apache.org/docs/python/install.html +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from altair.datasets._loader import Loader as Loader + +if TYPE_CHECKING: + import sys + from typing import Any + + if sys.version_info >= (3, 11): + from typing import LiteralString + else: + from typing_extensions import LiteralString + + from altair.datasets._data import DataObject + from altair.datasets._loader import _Load + from altair.datasets._typing import Dataset, Extension + + +load: _Load[Any, Any] +""" +Get a remote dataset and load as tabular data. + +This is an expert interface. For most users, the data object interface is recommended:: + + from altair.datasets import data + cars = data.cars(engine="polars") + +For full Tab completions, instead use:: + + from altair.datasets import Loader + load = Loader.from_backend("polars") + cars = load("cars") + movies = load("movies") + +Alternatively, specify ``backend`` during a call:: + + from altair.datasets import load + cars = load("cars", backend="polars") + movies = load("movies", backend="polars") +""" + +data: DataObject + + +def url( + name: Dataset | LiteralString, + suffix: Extension | None = None, + /, +) -> str: + """ + Return the address of a remote dataset. + + This is an expert interface. For most users, the data object interface is recommended:: + + from altair.datasets import data + + cars_url = data.cars.url + + Parameters + ---------- + name + Name of the dataset/`Path.stem`_. + suffix + File extension/`Path.suffix`_. + + .. note:: + Only needed if ``name`` is available in multiple formats. + + Returns + ------- + ``str`` + + .. _Path.stem: + https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem + .. _Path.suffix: + https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.suffix + """ + from altair.datasets._exceptions import AltairDatasetsError + + try: + from altair.datasets._loader import load + + url = load.url(name, suffix) + except AltairDatasetsError: + from altair.datasets._cache import csv_cache + + url = csv_cache.url(name) + + return url + + +def __getattr__(name): + if name == "data": + from altair.datasets._data import data + + return data + elif name == "load": + from altair.datasets._loader import load + + return load + elif name == "__all__": + # Define __all__ dynamically to avoid ruff errors + return ["Loader", "data", "load", "url"] + else: + msg = f"module {__name__!r} has no attribute {name!r}" + raise AttributeError(msg) diff --git a/.venv/lib/python3.13/site-packages/altair/datasets/_cache.py b/.venv/lib/python3.13/site-packages/altair/datasets/_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..fa0c0708b12342d0001fa6727ab99cacea092bd7 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/datasets/_cache.py @@ -0,0 +1,460 @@ +from __future__ import annotations + +import os +import sys +from collections import defaultdict +from importlib.util import find_spec +from pathlib import Path +from typing import TYPE_CHECKING, ClassVar, TypeVar, cast + +import narwhals.stable.v1 as nw + +from altair.datasets._exceptions import AltairDatasetsError + +if sys.version_info >= (3, 12): + from typing import Protocol +else: + from typing_extensions import Protocol + +if TYPE_CHECKING: + from collections.abc import ( + Iterable, + Iterator, + Mapping, + MutableMapping, + MutableSequence, + Sequence, + ) + from io import IOBase + from typing import Any, Final + from urllib.request import OpenerDirector + + from _typeshed import StrPath + from narwhals.stable.v1.dtypes import DType + from narwhals.stable.v1.typing import IntoExpr + + from altair.datasets._typing import Dataset, Metadata + + if sys.version_info >= (3, 12): + from typing import Unpack + else: + from typing_extensions import Unpack + if sys.version_info >= (3, 11): + from typing import LiteralString + else: + from typing_extensions import LiteralString + if sys.version_info >= (3, 10): + from typing import TypeAlias + else: + from typing_extensions import TypeAlias + from altair.datasets._typing import FlFieldStr + from altair.vegalite.v6.schema._typing import OneOrSeq + + _Dataset: TypeAlias = "Dataset | LiteralString" + _FlSchema: TypeAlias = Mapping[str, FlFieldStr] + +__all__ = ["CsvCache", "DatasetCache", "SchemaCache", "csv_cache"] + + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_T = TypeVar("_T") + +_METADATA_DIR: Final[Path] = Path(__file__).parent / "_metadata" + +_DTYPE_TO_FIELD: Mapping[type[DType], FlFieldStr] = { + nw.Int64: "integer", + nw.Float64: "number", + nw.Boolean: "boolean", + nw.String: "string", + nw.Struct: "object", + nw.List: "array", + nw.Date: "date", + nw.Datetime: "datetime", + nw.Duration: "duration", + # nw.Time: "time" (Not Implemented, but we don't have any cases using it anyway) +} +""" +Similar to `pl.datatypes.convert.dtype_to_ffiname`_. + +But using `narwhals.dtypes`_ to the string repr of ``frictionless`` `Field Types`_. + +.. _pl.datatypes.convert.dtype_to_ffiname: + https://github.com/pola-rs/polars/blob/85d078c066860e012f5e7e611558e6382b811b82/py-polars/polars/datatypes/convert.py#L139-L165 +.. _Field Types: + https://datapackage.org/standard/table-schema/#field-types +.. _narwhals.dtypes: + https://narwhals-dev.github.io/narwhals/api-reference/dtypes/ +""" + +_FIELD_TO_DTYPE: Mapping[FlFieldStr, type[DType]] = { + v: k for k, v in _DTYPE_TO_FIELD.items() +} + + +def _iter_metadata(df: nw.DataFrame[Any], /) -> Iterator[Metadata]: + """ + Yield rows from ``df``, where each represents a dataset. + + See Also + -------- + ``altair.datasets._typing.Metadata`` + """ + yield from cast("Iterator[Metadata]", df.iter_rows(named=True)) + + +class CompressedCache(Protocol[_KT, _VT]): + fp: Path + _mapping: MutableMapping[_KT, _VT] + + def read(self) -> Any: ... + def __getitem__(self, key: _KT, /) -> _VT: ... + + def __enter__(self) -> IOBase: + import gzip + + return gzip.open(self.fp, mode="rb").__enter__() + + def __exit__(self, *args) -> None: + return + + def get(self, key: _KT, default: _T, /) -> _VT | _T: + return self.mapping.get(key, default) + + @property + def mapping(self) -> MutableMapping[_KT, _VT]: + if not self._mapping: + self._mapping.update(self.read()) + return self._mapping + + +class CsvCache(CompressedCache["_Dataset", "Metadata"]): + """ + `csv`_, `gzip`_ -based, lazy metadata lookup. + + Used as a fallback for 2 scenarios: + + 1. ``url(...)`` when no optional dependencies are installed. + 2. ``(Loader|load)(...)`` when the backend is missing* ``.parquet`` support. + + Notes + ----- + *All backends *can* support ``.parquet``, but ``pandas`` requires an optional dependency. + + .. _csv: + https://docs.python.org/3/library/csv.html + .. _gzip: + https://docs.python.org/3/library/gzip.html + """ + + fp = _METADATA_DIR / "metadata.csv.gz" + + def __init__( + self, + *, + tp: type[MutableMapping[_Dataset, Metadata]] = dict["_Dataset", "Metadata"], + ) -> None: + self._mapping: MutableMapping[_Dataset, Metadata] = tp() + self._rotated: MutableMapping[str, MutableSequence[Any]] = defaultdict(list) + + def read(self) -> Any: + import csv + + with self as f: + b_lines = f.readlines() + reader = csv.reader((bs.decode() for bs in b_lines), dialect=csv.unix_dialect) + header = tuple(next(reader)) + return {row[0]: dict(self._convert_row(header, row)) for row in reader} + + def _convert_row( + self, header: Iterable[str], row: Iterable[str], / + ) -> Iterator[tuple[str, Any]]: + map_tf = {"true": True, "false": False} + for col, value in zip(header, row): + if col.startswith(("is_", "has_")): + yield col, map_tf[value] + elif col == "bytes": + yield col, int(value) + else: + yield col, value + + @property + def rotated(self) -> Mapping[str, Sequence[Any]]: + """Columnar view.""" + if not self._rotated: + for record in self.mapping.values(): + for k, v in record.items(): + self._rotated[k].append(v) + return self._rotated + + def __getitem__(self, key: _Dataset, /) -> Metadata: + if meta := self.get(key, None): + return meta + msg = f"{key!r} does not refer to a known dataset." + raise TypeError(msg) + + def url(self, name: _Dataset, /) -> str: + meta = self[name] + if meta["suffix"] == ".parquet" and not find_spec("vegafusion"): + raise AltairDatasetsError.from_url(meta) + return meta["url"] + + def __repr__(self) -> str: + return f"<{type(self).__name__}: {'COLLECTED' if self._mapping else 'READY'}>" + + +class SchemaCache(CompressedCache["_Dataset", "_FlSchema"]): + """ + `json`_, `gzip`_ -based, lazy schema lookup. + + - Primarily benefits ``pandas``, which needs some help identifying **temporal** columns. + - Utilizes `data package`_ schema types. + - All methods return falsy containers instead of exceptions + + .. _json: + https://docs.python.org/3/library/json.html + .. _gzip: + https://docs.python.org/3/library/gzip.html + .. _data package: + https://github.com/vega/vega-datasets/pull/631 + """ + + fp = _METADATA_DIR / "schemas.json.gz" + + def __init__( + self, + *, + tp: type[MutableMapping[_Dataset, _FlSchema]] = dict["_Dataset", "_FlSchema"], + implementation: nw.Implementation = nw.Implementation.UNKNOWN, + ) -> None: + self._mapping: MutableMapping[_Dataset, _FlSchema] = tp() + self._implementation: nw.Implementation = implementation + + def read(self) -> Any: + import json + + with self as f: + return json.load(f) + + def __getitem__(self, key: _Dataset, /) -> _FlSchema: + return self.get(key, {}) + + def by_dtype(self, name: _Dataset, *dtypes: type[DType]) -> list[str]: + """ + Return column names specfied in ``name``'s schema. + + Parameters + ---------- + name + Dataset name. + *dtypes + Optionally, only return columns matching the given data type(s). + """ + if (match := self[name]) and dtypes: + include = {_DTYPE_TO_FIELD[tp] for tp in dtypes} + return [col for col, tp_str in match.items() if tp_str in include] + else: + return list(match) + + def is_active(self) -> bool: + return self._implementation in { + nw.Implementation.PANDAS, + nw.Implementation.PYARROW, + nw.Implementation.MODIN, + nw.Implementation.PYARROW, + } + + def schema(self, name: _Dataset, /) -> nw.Schema: + it = ((col, _FIELD_TO_DTYPE[tp_str]()) for col, tp_str in self[name].items()) + return nw.Schema(it) + + def schema_kwds(self, meta: Metadata, /) -> dict[str, Any]: + name: Any = meta["dataset_name"] + if self.is_active() and (self[name]): + suffix = meta["suffix"] + if self._implementation.is_pandas_like(): + if cols := self.by_dtype(name, nw.Date, nw.Datetime): + if suffix == ".json": + return {"convert_dates": cols} + elif suffix in {".csv", ".tsv"}: + return {"parse_dates": cols} + else: + schema = self.schema(name).to_arrow() + if suffix in {".csv", ".tsv"}: + from pyarrow.csv import ConvertOptions + + # For pyarrow CSV reading, use the schema as intended + # This will fail for non-ISO date formats, but that's the correct behavior + # Users can handle this by using a different backend or converting dates manually + return {"convert_options": ConvertOptions(column_types=schema)} # pyright: ignore[reportCallIssue] + elif suffix == ".parquet": + return {"schema": schema} + + return {} + + +class _SupportsScanMetadata(Protocol): + _opener: ClassVar[OpenerDirector] + + def _scan_metadata( + self, *predicates: OneOrSeq[IntoExpr], **constraints: Unpack[Metadata] + ) -> nw.LazyFrame[Any]: ... + + +class DatasetCache: + """Opt-out caching of remote dataset requests.""" + + _ENV_VAR: ClassVar[LiteralString] = "ALTAIR_DATASETS_DIR" + _XDG_CACHE: ClassVar[Path] = ( + Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "altair" + ).resolve() + + def __init__(self, reader: _SupportsScanMetadata, /) -> None: + self._rd: _SupportsScanMetadata = reader + + def clear(self) -> None: + """Delete all previously cached datasets.""" + self._ensure_active() + if self.is_empty(): + return None + ser = ( + self._rd._scan_metadata() + .select("sha", "suffix") + .unique("sha") + .select(nw.concat_str("sha", "suffix").alias("sha_suffix")) + .collect() + .get_column("sha_suffix") + ) + names = set[str](ser.to_list()) + for fp in self: + if fp.name in names: + fp.unlink() + + def download_all(self) -> None: + """ + Download any missing datasets for latest version. + + Requires **30-50MB** of disk-space. + """ + stems = tuple(fp.stem for fp in self) + predicates = (~(nw.col("sha").is_in(stems)),) if stems else () + frame = ( + self._rd._scan_metadata(*predicates, is_image=False) + .select("sha", "suffix", "url") + .unique("sha") + .collect() + ) + if frame.is_empty(): + print("Already downloaded all datasets") + return None + print(f"Downloading {len(frame)} missing datasets...") + for meta in _iter_metadata(frame): + self._download_one(meta["url"], self.path_meta(meta)) + print("Finished downloads") + return None + + def _maybe_download(self, meta: Metadata, /) -> Path: + fp = self.path_meta(meta) + return ( + fp + if (fp.exists() and fp.stat().st_size) + else self._download_one(meta["url"], fp) + ) + + def _download_one(self, url: str, fp: Path, /) -> Path: + with self._rd._opener.open(url) as f: + fp.touch() + fp.write_bytes(f.read()) + return fp + + @property + def path(self) -> Path: + """ + Returns path to datasets cache. + + Defaults to (`XDG_CACHE_HOME`_):: + + "$XDG_CACHE_HOME/altair/" + + But can be configured using the environment variable:: + + "$ALTAIR_DATASETS_DIR" + + You can set this for the current session via:: + + from pathlib import Path + from altair.datasets import load + + load.cache.path = Path.home() / ".altair_cache" + + load.cache.path.relative_to(Path.home()).as_posix() + ".altair_cache" + + You can *later* disable caching via:: + + load.cache.path = None + + .. _XDG_CACHE_HOME: + https://specifications.freedesktop.org/basedir-spec/latest/#variables + """ + self._ensure_active() + fp = Path(usr) if (usr := os.environ.get(self._ENV_VAR)) else self._XDG_CACHE + fp.mkdir(parents=True, exist_ok=True) + return fp + + @path.setter + def path(self, source: StrPath | None, /) -> None: + if source is not None: + os.environ[self._ENV_VAR] = str(Path(source).resolve()) + else: + os.environ[self._ENV_VAR] = "" + + def path_meta(self, meta: Metadata, /) -> Path: + return self.path / (meta["sha"] + meta["suffix"]) + + def __iter__(self) -> Iterator[Path]: + yield from self.path.iterdir() + + def __repr__(self) -> str: + name = type(self).__name__ + if self.is_not_active(): + return f"{name}" + else: + return f"{name}<{self.path.as_posix()!r}>" + + def is_active(self) -> bool: + return not self.is_not_active() + + def is_not_active(self) -> bool: + return os.environ.get(self._ENV_VAR) == "" + + def is_empty(self) -> bool: + """Cache is active, but no files are stored in ``self.path``.""" + return next(iter(self), None) is None + + def _ensure_active(self) -> None: + if self.is_not_active(): + msg = ( + f"Cache is unset.\n" + f"To enable dataset caching, set the environment variable:\n" + f" {self._ENV_VAR!r}\n\n" + f"You can set this for the current session via:\n" + f" from pathlib import Path\n" + f" from altair.datasets import load\n\n" + f" load.cache.path = Path.home() / '.altair_cache'" + ) + raise ValueError(msg) + + +csv_cache: CsvCache + + +def __getattr__(name): + if name == "csv_cache": + global csv_cache + csv_cache = CsvCache() + return csv_cache + + else: + msg = f"module {__name__!r} has no attribute {name!r}" + raise AttributeError(msg) diff --git a/.venv/lib/python3.13/site-packages/altair/datasets/_constraints.py b/.venv/lib/python3.13/site-packages/altair/datasets/_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..eccb570ba20356802275da97531f81c48dcedc11 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/datasets/_constraints.py @@ -0,0 +1,121 @@ +"""Set-like guards for matching metadata to an implementation.""" + +from __future__ import annotations + +from collections.abc import Set +from itertools import chain +from typing import TYPE_CHECKING, Any + +from narwhals.stable import v1 as nw + +if TYPE_CHECKING: + import sys + from collections.abc import Iterable, Iterator + + from altair.datasets._typing import Metadata + + if sys.version_info >= (3, 12): + from typing import Unpack + else: + from typing_extensions import Unpack + if sys.version_info >= (3, 10): + from typing import TypeAlias + else: + from typing_extensions import TypeAlias + +__all__ = [ + "Items", + "MetaIs", + "is_arrow", + "is_csv", + "is_json", + "is_meta", + "is_not_tabular", + "is_parquet", + "is_spatial", + "is_topo", + "is_tsv", +] + +Items: TypeAlias = Set[tuple[str, Any]] + + +class MetaIs(Set[tuple[str, Any]]): + _requires: frozenset[tuple[str, Any]] + + def __init__(self, kwds: frozenset[tuple[str, Any]], /) -> None: + object.__setattr__(self, "_requires", kwds) + + @classmethod + def from_metadata(cls, meta: Metadata, /) -> MetaIs: + return cls(frozenset(meta.items())) + + def to_metadata(self) -> Metadata: + if TYPE_CHECKING: + + def collect(**kwds: Unpack[Metadata]) -> Metadata: + return kwds + + return collect(**dict(self)) + return dict(self) + + def to_expr(self) -> nw.Expr: + """Convert constraint into a narwhals expression.""" + if not self: + msg = f"Unable to convert an empty set to an expression:\n\n{self!r}" + raise TypeError(msg) + return nw.all_horizontal(nw.col(name) == val for name, val in self) + + def isdisjoint(self, other: Iterable[Any]) -> bool: + return super().isdisjoint(other) + + def issubset(self, other: Iterable[Any]) -> bool: + return self._requires.issubset(other) + + def __call__(self, meta: Items, /) -> bool: + return self._requires <= meta + + def __hash__(self) -> int: + return hash(self._requires) + + def __contains__(self, x: object) -> bool: + return self._requires.__contains__(x) + + def __iter__(self) -> Iterator[tuple[str, Any]]: + yield from self._requires + + def __len__(self) -> int: + return self._requires.__len__() + + def __setattr__(self, name: str, value: Any): + msg = ( + f"{type(self).__name__!r} is immutable.\n" + f"Could not assign self.{name} = {value}" + ) + raise TypeError(msg) + + def __repr__(self) -> str: + items = dict(self) + if not items: + contents = "" + elif suffix := items.pop("suffix", None): + contents = ", ".join( + chain([f"'*{suffix}'"], (f"{k}={v!r}" for k, v in items.items())) + ) + else: + contents = ", ".join(f"{k}={v!r}" for k, v in items.items()) + return f"is_meta({contents})" + + +def is_meta(**kwds: Unpack[Metadata]) -> MetaIs: + return MetaIs.from_metadata(kwds) + + +is_csv = is_meta(suffix=".csv") +is_json = is_meta(suffix=".json") +is_tsv = is_meta(suffix=".tsv") +is_arrow = is_meta(suffix=".arrow") +is_parquet = is_meta(suffix=".parquet") +is_spatial = is_meta(is_spatial=True) +is_topo = is_meta(is_topo=True) +is_not_tabular = is_meta(is_tabular=False) diff --git a/.venv/lib/python3.13/site-packages/altair/datasets/_data.py b/.venv/lib/python3.13/site-packages/altair/datasets/_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c3c885989426e3196ee7367b6b9e3c6f37a262da --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/datasets/_data.py @@ -0,0 +1,358 @@ +""" +Data object interface for Altair datasets. + +This module provides a `data` object that allows accessing datasets as attributes +and calling them with backend options, similar to the vega_datasets interface. +""" + +from __future__ import annotations + +import typing as t + +from altair.datasets._loader import Loader + +if t.TYPE_CHECKING: + from typing_extensions import LiteralString + + import pandas as pd + import polars as pl + import pyarrow as pa + + from altair.datasets._reader import _Backend + from altair.datasets._typing import Dataset + + +class DatasetAccessor: + """ + Accessor for individual datasets that can be called with backend options. + + This object provides access to a specific dataset with support for + different backends and autocompletion. + + Call this object to load the dataset: + dataset_accessor(engine="polars", **kwds) + + Parameters for __call__: + engine : {"polars", "pandas", "pandas[pyarrow]", "pyarrow"}, optional + The backend to use for loading the dataset. + **kwds : Any + Additional arguments passed to the loader. + + Examples + -------- + >>> from altair.datasets import data + >>> + >>> # Load with default backend + >>> cars_df = data.cars() + >>> + >>> # Load with specific backend + >>> cars_polars = data.cars(engine="polars") + >>> cars_pandas = data.cars(engine="pandas") + >>> # Note: pandas[pyarrow] backend requires pyarrow package + >>> + >>> # Get URL + >>> url = data.cars.url + >>> + >>> # Use explicit load method + >>> cars_df = data.cars.load(engine="polars") + """ + + def __init__(self, name: Dataset, backend: _Backend = "pandas") -> None: + import inspect + + self._name: Dataset = name + self._backend: _Backend = backend + self._prev_loader: Loader[t.Any, t.Any] + self.__signature__ = inspect.signature(self._call_impl) + + docstring = f"""Load the '{name}' dataset. + +Parameters +---------- +engine : {{"polars", "pandas", "pandas[pyarrow]", "pyarrow"}}, optional + The backend to use for loading the dataset. +**kwds : Any + Additional arguments passed to the loader. + +Returns +------- +DataFrame or Table + The loaded dataset. + +Examples +-------- +>>> data.{name}() # Load with default backend +>>> data.{name}(engine="polars") # Load with specific backend +>>> data.{name}.url # Get dataset URL +>>> data.{name}.load(engine="polars") # Explicit load method +""" + + self.__doc__ = docstring + + def _call_impl( + self, + *, + engine: _Backend | None = None, + **kwds: t.Any, + ) -> t.Any: + load = Loader.from_backend(engine) if engine else self._loader + return load(self._name, **kwds) + + @property + def _loader(self) -> Loader[t.Any, t.Any]: + if hasattr(self, "_prev_loader"): + return self._prev_loader + self._prev_loader = Loader.from_backend(self._backend) + return self._prev_loader + + @_loader.setter + def _loader(self, value: Loader[t.Any, t.Any]) -> None: + self._prev_loader = value + + @property + def url(self) -> str: + """ + Get the URL for this dataset. + + Returns + ------- + str + The URL of the dataset. + + Examples + -------- + >>> from altair.datasets import data + >>> cars_url = data.cars.url + >>> print(cars_url) + https://cdn.jsdelivr.net/npm/vega-datasets@v3.2.1/data/cars.json + """ + return self._loader.url(self._name) + + def load(self, *, engine: _Backend | None = None, **kwds: t.Any) -> t.Any: + """ + Load the dataset with the specified engine. + + This method provides the same functionality as calling the accessor directly, + but with more explicit parameter autocompletion in some IDEs. + + Parameters + ---------- + engine : {"polars", "pandas", "pandas[pyarrow]", "pyarrow"}, optional + The backend to use for loading the dataset. + **kwds : Any + Additional arguments passed to the loader. + + Returns + ------- + DataFrame or Table + The loaded dataset. + + Examples + -------- + >>> from altair.datasets import data + >>> cars_df = data.cars.load(engine="polars") + >>> movies_df = data.movies.load(engine="pandas") + """ + return self._call_impl(engine=engine, **kwds) + + def __repr__(self) -> str: + return f"DatasetAccessor('{self._name}', default_engine='{self._backend}')" + + @t.overload + def __call__( + self, + *, + engine: t.Literal["polars"], + **kwds: t.Any, + ) -> pl.DataFrame: ... + + @t.overload + def __call__( + self, + *, + engine: t.Literal["pandas", "pandas[pyarrow]"], + **kwds: t.Any, + ) -> pd.DataFrame: ... + + @t.overload + def __call__( + self, + *, + engine: t.Literal["pyarrow"], + **kwds: t.Any, + ) -> pa.Table: ... + + @t.overload + def __call__( + self, + *, + engine: _Backend | None = None, + **kwds: t.Any, + ) -> t.Any: ... + + def __call__( + self, + *, + engine: _Backend | None = None, + **kwds: t.Any, + ) -> t.Any: + """ + Load the dataset with the specified engine. + + Parameters + ---------- + engine : {{"polars", "pandas", "pandas[pyarrow]", "pyarrow"}}, optional + The backend to use for loading the dataset. + **kwds + Additional arguments passed to the loader. + + Returns + ------- + The loaded dataset as a DataFrame/Table from the specified engine. + + Examples + -------- + >>> from altair.datasets import data + >>> + >>> # Load with default engine + >>> df = data.cars() + >>> + >>> # Load with specific engine + >>> df = data.cars(engine="polars") + """ + return self._call_impl(engine=engine, **kwds) + + +class DataObject: + """ + Main data object that provides access to all datasets as attributes. + + This is the primary interface for loading Altair datasets. It provides + a simple, intuitive way to access datasets with autocompletion support. + + Examples + -------- + >>> from altair.datasets import data + >>> + >>> # Access datasets as attributes with autocompletion + >>> cars_df = data.cars() + >>> movies_df = data.movies(engine="pandas") + >>> + >>> # Get URLs + >>> cars_url = data.cars.url + >>> movies_url = data.movies.url + >>> + >>> # Set default engine for all datasets + >>> data.set_default_engine("polars") + >>> penguins_df = data.penguins() # Uses polars engine + >>> + >>> # List available datasets + >>> available_datasets = data.list_datasets() + >>> print(f"Available datasets: {len(available_datasets)}") + Available datasets: 72 + """ + + def __init__(self, backend: _Backend = "pandas") -> None: + self._backend: _Backend = backend + self._accessors: dict[Dataset, DatasetAccessor] = {} + self._dataset_names: list[Dataset | LiteralString] | None = None + + def _get_dataset_names(self) -> list[Dataset | LiteralString]: + """Get the list of available dataset names from metadata.""" + if self._dataset_names is None: + try: + from altair.datasets._cache import CsvCache + + cache = CsvCache() + self._dataset_names = list(cache.mapping.keys()) + except Exception: + # Fallback if metadata is not available + self._dataset_names = [] + return self._dataset_names + + def __dir__(self) -> list[str]: + """Return list of available attributes for autocompletion.""" + standard_attrs = list(super().__dir__()) + dataset_names = self._get_dataset_names() + return standard_attrs + dataset_names + + def __getattr__(self, name: Dataset) -> DatasetAccessor: # type: ignore[misc] + dataset_names = self._get_dataset_names() + if name not in dataset_names: + available_datasets = dataset_names[:10] + error_msg = ( + f"Dataset '{name}' not found. Available datasets: {available_datasets}" + ) + raise AttributeError(error_msg) + + self._accessors[name] = DatasetAccessor(name, self._backend) + return self._accessors[name] + + def set_default_engine(self, engine: _Backend) -> None: + """ + Set the default engine for all datasets. + + Parameters + ---------- + engine : {"polars", "pandas", "pandas[pyarrow]", "pyarrow"} + The backend to use as default for all datasets. + + Examples + -------- + >>> from altair.datasets import data + >>> data.set_default_engine("polars") + >>> # Now all datasets will use polars by default + >>> cars_df = data.cars() # Uses polars + >>> movies_df = data.movies() # Uses polars + """ + self._backend = engine + # Clear cached accessors so they use the new default + self._accessors.clear() + + def list_datasets(self) -> list[Dataset | LiteralString]: + """ + Get a list of all available dataset names. + + Returns + ------- + list[str] + List of available dataset names. + + Examples + -------- + >>> from altair.datasets import data + >>> datasets = data.list_datasets() + >>> print(f"Available datasets: {len(datasets)}") + Available datasets: 72 + >>> print(datasets[:5]) # First 5 datasets + ['airports', 'annual_precip', 'anscombe', 'barley', 'birdstrikes'] + """ + return self._get_dataset_names() + + def get_default_engine(self) -> _Backend: + """ + Get the current default engine. + + Returns + ------- + str + The current default engine. + + Examples + -------- + >>> from altair.datasets import data + >>> data.set_default_engine("pandas") + >>> print(data.get_default_engine()) + pandas + >>> data.set_default_engine("polars") + >>> print(data.get_default_engine()) + polars + """ + return self._backend + + def __repr__(self) -> str: + dataset_count = len(self._get_dataset_names()) + return f"AltairDataObject(default_engine='{self._backend}', datasets={dataset_count})" + + +data = DataObject() diff --git a/.venv/lib/python3.13/site-packages/altair/datasets/_exceptions.py b/.venv/lib/python3.13/site-packages/altair/datasets/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..8d171e5aa44ca6dd133f82d48082fdeeeff3d26e --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/datasets/_exceptions.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Sequence + + from altair.datasets._reader import _Backend + from altair.datasets._typing import Metadata + + +class AltairDatasetsError(Exception): + @classmethod + def from_url(cls, meta: Metadata, /) -> AltairDatasetsError: + if meta["suffix"] == ".parquet": + msg = ( + f"{_failed_url(meta)}" + f"{meta['suffix']!r} datasets require `vegafusion`.\n" + "See upstream issue for details: https://github.com/vega/vega/issues/3961" + ) + else: + msg = ( + f"{cls.from_url.__qualname__}() called for " + f"unimplemented extension: {meta['suffix']}\n\n{meta!r}" + ) + raise NotImplementedError(msg) + return cls(msg) + + @classmethod + def from_tabular(cls, meta: Metadata, backend_name: str, /) -> AltairDatasetsError: + if meta["is_image"]: + reason = "Image data is non-tabular." + return cls(f"{_failed_tabular(meta)}{reason}{_suggest_url(meta)}") + elif not meta["is_tabular"] or meta["suffix"] in {".arrow", ".parquet"}: + if meta["suffix"] in {".arrow", ".parquet"}: + install: tuple[str, ...] = "pyarrow", "polars" + what = f"{meta['suffix']!r}" + else: + install = ("polars",) + if meta["is_spatial"]: + what = "Geospatial data" + elif meta["is_json"]: + what = "Non-tabular json" + else: + what = f"{meta['file_name']!r}" + reason = _why(what, backend_name) + return cls(f"{_failed_tabular(meta)}{reason}{_suggest_url(meta, *install)}") + else: + return cls(_implementation_not_found(meta)) + + @classmethod + def from_priority(cls, priority: Sequence[_Backend], /) -> AltairDatasetsError: + msg = f"Found no supported backend, searched:\n{priority!r}" + return cls(msg) + + +def module_not_found( + backend_name: str, reqs: Sequence[str], missing: str +) -> ModuleNotFoundError: + if len(reqs) == 1: + depends = f"{reqs[0]!r} package" + else: + depends = ", ".join(f"{req!r}" for req in reqs) + " packages" + msg = ( + f"Backend {backend_name!r} requires the {depends}, but {missing!r} could not be found.\n" + f"This can be installed with pip using:\n" + f" pip install {missing}\n" + f"Or with conda using:\n" + f" conda install -c conda-forge {missing}" + ) + return ModuleNotFoundError(msg, name=missing) + + +def _failed_url(meta: Metadata, /) -> str: + return f"Unable to load {meta['file_name']!r} via url.\n" + + +def _failed_tabular(meta: Metadata, /) -> str: + return f"Unable to load {meta['file_name']!r} as tabular data.\n" + + +def _why(what: str, backend_name: str, /) -> str: + return f"{what} is not supported natively by {backend_name!r}." + + +def _suggest_url(meta: Metadata, *install_other: str) -> str: + other = "" + if install_other: + others = " or ".join(f"`{other}`" for other in install_other) + other = f" installing {others}, or use" + return ( + f"\n\nInstead, try{other}:\n" + " from altair.datasets import data\n" + f" data.{meta['dataset_name']}.url" + ) + + +def _implementation_not_found(meta: Metadata, /) -> str: + """Search finished without finding a *declared* incompatibility.""" + INDENT = " " * 4 + record = f",\n{INDENT}".join( + f"{k}={v!r}" + for k, v in meta.items() + if not (k.startswith(("is_", "sha", "bytes", "has_"))) + or (v is True and k.startswith("is_")) + ) + return f"Found no implementation that supports:\n{INDENT}{record}" diff --git a/.venv/lib/python3.13/site-packages/altair/datasets/_loader.py b/.venv/lib/python3.13/site-packages/altair/datasets/_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..98472262324d36da72c546c6d12ca5ea8c2b953a --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/datasets/_loader.py @@ -0,0 +1,359 @@ +from __future__ import annotations + +import typing as t +from typing import Generic, final, overload + +from narwhals.stable.v1.typing import IntoDataFrameT + +from altair.datasets import _reader +from altair.datasets._reader import IntoFrameT + +if t.TYPE_CHECKING: + import sys + from typing import Any, Literal + + import pandas as pd + import polars as pl + import pyarrow as pa + + from altair.datasets._cache import DatasetCache + from altair.datasets._reader import Reader + + if sys.version_info >= (3, 11): + from typing import LiteralString, Self + else: + from typing_extensions import LiteralString, Self + from altair.datasets._reader import _Backend + from altair.datasets._typing import Dataset, Extension + + +__all__ = ["Loader", "load"] + + +class Loader(Generic[IntoDataFrameT, IntoFrameT]): + """ + Load example datasets *remotely* from `vega-datasets`_, with caching. + + A new ``Loader`` must be initialized by specifying a backend:: + + from altair.datasets import Loader + + load = Loader.from_backend("polars") + load + Loader[polars] + + .. _vega-datasets: + https://github.com/vega/vega-datasets + """ + + _reader: Reader[IntoDataFrameT, IntoFrameT] + + @overload + @classmethod + def from_backend( + cls, backend_name: Literal["polars"] = ..., / + ) -> Loader[pl.DataFrame, pl.LazyFrame]: ... + + @overload + @classmethod + def from_backend( + cls, backend_name: Literal["pandas", "pandas[pyarrow]"], / + ) -> Loader[pd.DataFrame, pd.DataFrame]: ... + + @overload + @classmethod + def from_backend( + cls, backend_name: Literal["pyarrow"], / + ) -> Loader[pa.Table, pa.Table]: ... + + @classmethod + def from_backend( + cls: type[Loader[Any, Any]], backend_name: _Backend = "polars", / + ) -> Loader[Any, Any]: + """ + Initialize a new loader, with the specified backend. + + Parameters + ---------- + backend_name + DataFrame package/config used to return data. + + * *polars*: Using `polars defaults`_ + * *pandas*: Using `pandas defaults`_. + * *pandas[pyarrow]*: Using ``dtype_backend="pyarrow"`` + * *pyarrow*: (*Experimental*) + + .. warning:: + Most datasets use a `JSON format not supported`_ by ``pyarrow`` + + Examples + -------- + Using ``polars``:: + + from altair.datasets import Loader + + load = Loader.from_backend("polars") + cars = load("cars") + + type(cars) + polars.dataframe.frame.DataFrame + + Using ``pandas``:: + + load = Loader.from_backend("pandas") + cars = load("cars") + + type(cars) + pandas.core.frame.DataFrame + + Using ``pandas``, backed by ``pyarrow`` dtypes:: + + load = Loader.from_backend("pandas[pyarrow]") + co2 = load("co2") + + type(co2) + pandas.core.frame.DataFrame + + co2.dtypes + Date datetime64[ns] + CO2 double[pyarrow] + adjusted CO2 double[pyarrow] + dtype: object + + .. _polars defaults: + https://docs.pola.rs/api/python/stable/reference/io.html + .. _pandas defaults: + https://pandas.pydata.org/docs/reference/io.html + .. _JSON format not supported: + https://arrow.apache.org/docs/python/json.html#reading-json-files + """ + return cls.from_reader(_reader._from_backend(backend_name)) + + @classmethod + def from_reader(cls, reader: Reader[IntoDataFrameT, IntoFrameT], /) -> Self: + obj = cls.__new__(cls) + obj._reader = reader + return obj + + def __call__( + self, + name: Dataset | LiteralString, + suffix: Extension | None = None, + /, + **kwds: Any, + ) -> IntoDataFrameT: + """ + Get a remote dataset and load as tabular data. + + Parameters + ---------- + name + Name of the dataset/`Path.stem`_. + suffix + File extension/`Path.suffix`_. + + .. note:: + Only needed if ``name`` is available in multiple formats. + **kwds + Arguments passed to the underlying read function. + + Examples + -------- + Using ``polars``:: + + from altair.datasets import Loader + + load = Loader.from_backend("polars") + source = load("iowa_electricity") + + source.columns + ['year', 'source', 'net_generation'] + + source.head(5) + shape: (5, 3) + ┌────────────┬──────────────┬────────────────┐ + │ year ┆ source ┆ net_generation │ + │ --- ┆ --- ┆ --- │ + │ date ┆ str ┆ i64 │ + ╞════════════╪══════════════╪════════════════╡ + │ 2001-01-01 ┆ Fossil Fuels ┆ 35361 │ + │ 2002-01-01 ┆ Fossil Fuels ┆ 35991 │ + │ 2003-01-01 ┆ Fossil Fuels ┆ 36234 │ + │ 2004-01-01 ┆ Fossil Fuels ┆ 36205 │ + │ 2005-01-01 ┆ Fossil Fuels ┆ 36883 │ + └────────────┴──────────────┴────────────────┘ + + Using ``pandas``:: + + load = Loader.from_backend("pandas") + source = load("iowa_electricity") + + source.columns + Index(['year', 'source', 'net_generation'], dtype='object') + + source.head(5) + year source net_generation + 0 2001-01-01 Fossil Fuels 35361 + 1 2002-01-01 Fossil Fuels 35991 + 2 2003-01-01 Fossil Fuels 36234 + 3 2004-01-01 Fossil Fuels 36205 + 4 2005-01-01 Fossil Fuels 36883 + + Using ``pyarrow``:: + + load = Loader.from_backend("pyarrow") + source = load("iowa_electricity") + + source.column_names + ['year', 'source', 'net_generation'] + + source.slice(0, 5) + pyarrow.Table + year: date32[day] + source: string + net_generation: int64 + ---- + year: [[2001-01-01,2002-01-01,2003-01-01,2004-01-01,2005-01-01]] + source: [["Fossil Fuels","Fossil Fuels","Fossil Fuels","Fossil Fuels","Fossil Fuels"]] + net_generation: [[35361,35991,36234,36205,36883]] + + .. _Path.stem: + https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem + .. _Path.suffix: + https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.suffix + """ + return self._reader.dataset(name, suffix, **kwds) + + def url( + self, + name: Dataset | LiteralString, + suffix: Extension | None = None, + /, + ) -> str: + """ + Return the address of a remote dataset. + + Parameters + ---------- + name + Name of the dataset/`Path.stem`_. + suffix + File extension/`Path.suffix`_. + + .. note:: + Only needed if ``name`` is available in multiple formats. + + .. _Path.stem: + https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem + .. _Path.suffix: + https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.suffix + + Examples + -------- + The returned url will always point to an accessible dataset:: + + import altair as alt + from altair.datasets import Loader + + load = Loader.from_backend("polars") + load.url("cars") + "https://cdn.jsdelivr.net/npm/vega-datasets@v2.11.0/data/cars.json" + + We can pass the result directly to a chart:: + + url = load.url("cars") + alt.Chart(url).mark_point().encode(x="Horsepower:Q", y="Miles_per_Gallon:Q") + """ + return self._reader.url(name, suffix) + + @property + def cache(self) -> DatasetCache: + """ + Caching of remote dataset requests. + + Configure cache path:: + + self.cache.path = "..." + + Download the latest datasets *ahead-of-time*:: + + self.cache.download_all() + + Remove all downloaded datasets:: + + self.cache.clear() + + Disable caching:: + + self.cache.path = None + """ + return self._reader.cache + + def __repr__(self) -> str: + return f"{type(self).__name__}[{self._reader._name}]" + + +@final +class _Load(Loader[IntoDataFrameT, IntoFrameT]): + @overload + def __call__( # pyright: ignore[reportOverlappingOverload] + self, + name: Dataset | LiteralString, + suffix: Extension | None = ..., + /, + backend: None = ..., + **kwds: Any, + ) -> IntoDataFrameT: ... + @overload + def __call__( + self, + name: Dataset | LiteralString, + suffix: Extension | None = ..., + /, + backend: Literal["polars"] = ..., + **kwds: Any, + ) -> pl.DataFrame: ... + @overload + def __call__( + self, + name: Dataset | LiteralString, + suffix: Extension | None = ..., + /, + backend: Literal["pandas", "pandas[pyarrow]"] = ..., + **kwds: Any, + ) -> pd.DataFrame: ... + @overload + def __call__( + self, + name: Dataset | LiteralString, + suffix: Extension | None = ..., + /, + backend: Literal["pyarrow"] = ..., + **kwds: Any, + ) -> pa.Table: ... + def __call__( + self, + name: Dataset | LiteralString, + suffix: Extension | None = None, + /, + backend: _Backend | None = None, + **kwds: Any, + ) -> IntoDataFrameT | pl.DataFrame | pd.DataFrame | pa.Table: + if backend is None: + return super().__call__(name, suffix, **kwds) + else: + return self.from_backend(backend)(name, suffix, **kwds) + + +load: _Load[Any, Any] + + +def __getattr__(name): + if name == "load": + reader = _reader.infer_backend() + global load + load = _Load.from_reader(reader) + return load + else: + msg = f"module {__name__!r} has no attribute {name!r}" + raise AttributeError(msg) diff --git a/.venv/lib/python3.13/site-packages/altair/datasets/_reader.py b/.venv/lib/python3.13/site-packages/altair/datasets/_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..07c5453995e6e51cee1e673ccc1c3160980993a7 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/datasets/_reader.py @@ -0,0 +1,572 @@ +""" +Backend for ``alt.datasets.Loader``. + +Notes +----- +Extending would be more ergonomic if `read`, `scan`, `_constraints` were available under a single export:: + + from altair.datasets import ext, reader + import polars as pl + + impls = ( + ext.read(pl.read_parquet, ext.is_parquet), + ext.read(pl.read_csv, ext.is_csv), + ext.read(pl.read_json, ext.is_json), + ) + user_reader = reader(impls) + user_reader.dataset("airports") +""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Mapping +from importlib import import_module +from importlib.util import find_spec +from itertools import chain +from pathlib import Path +from typing import TYPE_CHECKING, Any, ClassVar, Generic, Literal, cast, overload +from urllib.request import build_opener as _build_opener + +from narwhals.stable import v1 as nw +from narwhals.stable.v1.typing import IntoDataFrameT, IntoExpr +from packaging.requirements import Requirement + +from altair.datasets import _readimpl +from altair.datasets._cache import CsvCache, DatasetCache, SchemaCache, _iter_metadata +from altair.datasets._constraints import is_parquet +from altair.datasets._exceptions import AltairDatasetsError, module_not_found +from altair.datasets._readimpl import IntoFrameT, is_available + +if TYPE_CHECKING: + import sys + from collections.abc import Callable, Sequence + from urllib.request import OpenerDirector + + import pandas as pd + import polars as pl + import pyarrow as pa + + from altair.datasets._readimpl import BaseImpl, R, Read, Scan + from altair.datasets._typing import Dataset, Extension, Metadata + from altair.vegalite.v6.schema._typing import OneOrSeq + + if sys.version_info >= (3, 13): + from typing import TypeIs, TypeVar + else: + from typing_extensions import TypeIs, TypeVar + if sys.version_info >= (3, 12): + from typing import Unpack + else: + from typing_extensions import Unpack + if sys.version_info >= (3, 11): + from typing import LiteralString + else: + from typing_extensions import LiteralString + if sys.version_info >= (3, 10): + from typing import TypeAlias + else: + from typing_extensions import TypeAlias + _Polars: TypeAlias = Literal["polars"] + _Pandas: TypeAlias = Literal["pandas"] + _PyArrow: TypeAlias = Literal["pyarrow"] + _PandasAny: TypeAlias = Literal[_Pandas, "pandas[pyarrow]"] + _Backend: TypeAlias = Literal[_Polars, _PandasAny, _PyArrow] + _CuDF: TypeAlias = Literal["cudf"] + _Dask: TypeAlias = Literal["dask"] + _DuckDB: TypeAlias = Literal["duckdb"] + _Ibis: TypeAlias = Literal["ibis"] + _PySpark: TypeAlias = Literal["pyspark"] + _NwSupport: TypeAlias = Literal[ + _Polars, _Pandas, _PyArrow, _CuDF, _Dask, _DuckDB, _Ibis, _PySpark + ] + _NwSupportT = TypeVar( + "_NwSupportT", + _Polars, + _Pandas, + _PyArrow, + _CuDF, + _Dask, + _DuckDB, + _Ibis, + _PySpark, + ) + +_SupportProfile: TypeAlias = Mapping[ + Literal["supported", "unsupported"], "Sequence[Dataset]" +] +""" +Dataset support varies between backends and available dependencies. + +Any name listed in ``"unsupported"`` will raise an error on:: + + from altair.datasets import load + + load("7zip") + +Instead, they can be loaded via:: + + import altair as alt + from altair.datasets import url + + alt.Chart(url("7zip")) +""" + + +class Reader(Generic[IntoDataFrameT, IntoFrameT]): + """ + Modular file reader, targeting remote & local tabular resources. + + .. warning:: + Use ``reader(...)`` instead of instantiating ``Reader`` directly. + """ + + _read: Sequence[Read[IntoDataFrameT]] + """Eager file read functions.""" + + _scan: Sequence[Scan[IntoFrameT]] + """Lazy file read functions.""" + + _name: str + """ + Used in error messages, repr and matching ``@overload``(s). + + Otherwise, has no concrete meaning. + """ + + _implementation: nw.Implementation + """ + Corresponding `narwhals implementation`_. + + .. _narwhals implementation: + https://github.com/narwhals-dev/narwhals/blob/9b6a355530ea46c590d5a6d1d0567be59c0b5742/narwhals/utils.py#L61-L290 + """ + + _opener: ClassVar[OpenerDirector] = _build_opener() + _metadata_path: ClassVar[Path] = ( + Path(__file__).parent / "_metadata" / "metadata.parquet" + ) + + def __init__( + self, + read: Sequence[Read[IntoDataFrameT]], + scan: Sequence[Scan[IntoFrameT]], + name: str, + implementation: nw.Implementation, + ) -> None: + self._read = read + self._scan = scan + self._name = name + self._implementation = implementation + self._schema_cache = SchemaCache(implementation=implementation) + + def __repr__(self) -> str: + from textwrap import indent + + PREFIX = " " * 4 + NL = "\n" + body = f"read\n{indent(NL.join(str(el) for el in self._read), PREFIX)}" + if self._scan: + body += f"\nscan\n{indent(NL.join(str(el) for el in self._scan), PREFIX)}" + return f"Reader[{self._name}] {self._implementation!r}\n{body}" + + def read_fn(self, meta: Metadata, /) -> Callable[..., IntoDataFrameT]: + return self._solve(meta, self._read) + + def scan_fn(self, meta: Metadata | Path | str, /) -> Callable[..., IntoFrameT]: + meta = meta if isinstance(meta, Mapping) else {"suffix": _into_suffix(meta)} + return self._solve(meta, self._scan) + + @property + def cache(self) -> DatasetCache: + return DatasetCache(self) + + def _handle_pyarrow_date_error(self, e: Exception, name: str) -> None: + """Handle PyArrow date parsing errors with informative error messages, see https://github.com/apache/arrow/issues/41488.""" + if "CSV conversion error to date" in str(e) and "pyarrow" in str( + type(e).__module__ + ): + message = ( + f"PyArrow cannot parse date format in dataset '{name}'. " + f"This is a known limitation of PyArrow's CSV reader for non-ISO date formats.\n\n" + f"Alternatives:\n" + f"1. Use a different backend: data.{name}(engine='pandas') or data.{name}(engine='polars')\n" + f"2. Convert dates manually after loading as strings\n\n" + f"Original error: {e}" + ) + raise AltairDatasetsError(message) from e + raise e + + def dataset( + self, + name: Dataset | LiteralString, + suffix: Extension | None = None, + /, + **kwds: Any, + ) -> IntoDataFrameT: + frame = self._query(name, suffix) + meta = next(_iter_metadata(frame)) + fn = self.read_fn(meta) + fn_kwds = self._merge_kwds(meta, kwds) + if self.cache.is_active(): + fp = self.cache._maybe_download(meta) + try: + return fn(fp, **fn_kwds) + except Exception as e: + self._handle_pyarrow_date_error(e, name) + raise + else: + with self._opener.open(meta["url"]) as f: + try: + return fn(f, **fn_kwds) + except Exception as e: + self._handle_pyarrow_date_error(e, name) + raise + + def url( + self, name: Dataset | LiteralString, suffix: Extension | None = None, / + ) -> str: + frame = self._query(name, suffix) + meta = next(_iter_metadata(frame)) + if is_parquet(meta.items()) and not is_available("vegafusion"): + raise AltairDatasetsError.from_url(meta) + url = meta["url"] + if isinstance(url, str): + return url + else: + msg = f"Expected 'str' but got {type(url).__name__!r}\nfrom {url!r}." + raise TypeError(msg) + + # TODO: (Multiple) + # - Settle on a better name + # - Add method to `Loader` + # - Move docs to `Loader.{new name}` + def open_markdown(self, name: Dataset, /) -> None: + """ + Learn more about a dataset, opening `vega-datasets/datapackage.md`_ with the default browser. + + Additional info *may* include: `description`_, `schema`_, `sources`_, `licenses`_. + + .. _vega-datasets/datapackage.md: + https://github.com/vega/vega-datasets/blob/main/datapackage.md + .. _description: + https://datapackage.org/standard/data-resource/#description + .. _schema: + https://datapackage.org/standard/table-schema/#schema + .. _sources: + https://datapackage.org/standard/data-package/#sources + .. _licenses: + https://datapackage.org/standard/data-package/#licenses + """ + import webbrowser + + from altair.utils import VERSIONS + + ref = self._query(name).get_column("file_name").item(0).replace(".", "") + tag = VERSIONS["vega-datasets"] + url = f"https://github.com/vega/vega-datasets/blob/v{tag}/datapackage.md#{ref}" + webbrowser.open(url) + + @overload + def profile(self, *, show: Literal[False] = ...) -> _SupportProfile: ... + + @overload + def profile(self, *, show: Literal[True]) -> None: ... + + def profile(self, *, show: bool = False) -> _SupportProfile | None: + """ + Describe which datasets can be loaded as tabular data. + + Parameters + ---------- + show + Print a densely formatted repr *instead of* returning a mapping. + """ + relevant_columns = set( + chain.from_iterable(impl._relevant_columns for impl in self._read) + ) + frame = self._scan_metadata().select("dataset_name", *relevant_columns) + inc_expr = nw.any_horizontal(impl._include_expr for impl in self._read) + result: _SupportProfile = { + "unsupported": _dataset_names(frame, ~inc_expr), + "supported": _dataset_names(frame, inc_expr), + } + if show: + import pprint + + pprint.pprint(result, compact=True, sort_dicts=False) + return None + return result + + def _query( + self, name: Dataset | LiteralString, suffix: Extension | None = None, / + ) -> nw.DataFrame[IntoDataFrameT]: + """ + Query a tabular version of `vega-datasets/datapackage.json`_. + + Applies a filter, erroring out when no results would be returned. + + .. _vega-datasets/datapackage.json: + https://github.com/vega/vega-datasets/blob/main/datapackage.json + """ + constraints = _into_constraints(name, suffix) + frame = self._scan_metadata(**constraints).collect() + if not frame.is_empty(): + return frame + else: + msg = f"Found no results for:\n {constraints!r}" + raise ValueError(msg) + + def _merge_kwds(self, meta: Metadata, kwds: dict[str, Any], /) -> Mapping[str, Any]: + """ + Extend user-provided arguments with dataset & library-specfic defaults. + + .. important:: User-provided arguments have a higher precedence. + """ + if self._schema_cache.is_active() and ( + schema := self._schema_cache.schema_kwds(meta) + ): + kwds = schema | kwds if kwds else schema + return kwds + + @property + def _metadata_frame(self) -> nw.LazyFrame[IntoFrameT]: + fp = self._metadata_path + return nw.from_native(self.scan_fn(fp)(fp)).lazy() + + def _scan_metadata( + self, *predicates: OneOrSeq[IntoExpr], **constraints: Unpack[Metadata] + ) -> nw.LazyFrame[IntoFrameT]: + if predicates or constraints: + return self._metadata_frame.filter(*predicates, **constraints) + return self._metadata_frame + + def _solve( + self, meta: Metadata, impls: Sequence[BaseImpl[R]], / + ) -> Callable[..., R]: + """ + Return the first function that satisfies dataset constraints. + + See Also + -------- + ``altair.datasets._readimpl.BaseImpl.unwrap_or_skip`` + """ + items = meta.items() + it = (some for impl in impls if (some := impl.unwrap_or_skip(items))) + if fn_or_err := next(it, None): + if _is_err(fn_or_err): + raise fn_or_err.from_tabular(meta, self._name) + return fn_or_err + raise AltairDatasetsError.from_tabular(meta, self._name) + + +def _dataset_names( + frame: nw.LazyFrame, *predicates: OneOrSeq[IntoExpr] +) -> Sequence[Dataset]: + # NOTE: helper function for `Reader.profile` + return ( + frame.filter(*predicates) + .select("dataset_name") + .collect() + .get_column("dataset_name") + .to_list() + ) + + +class _NoParquetReader(Reader[IntoDataFrameT, IntoFrameT]): + def __repr__(self) -> str: + return f"{super().__repr__()}\ncsv_cache\n {self.csv_cache!r}" + + @property + def csv_cache(self) -> CsvCache: + if not hasattr(self, "_csv_cache"): + self._csv_cache = CsvCache() + return self._csv_cache + + @property + def _metadata_frame(self) -> nw.LazyFrame[IntoFrameT]: + data = cast("dict[str, Any]", self.csv_cache.rotated) + impl = self._implementation + return nw.maybe_convert_dtypes(nw.from_dict(data, backend=impl)).lazy() + + +@overload +def reader( + read_fns: Sequence[Read[IntoDataFrameT]], + scan_fns: tuple[()] = ..., + *, + name: str | None = ..., + implementation: nw.Implementation = ..., +) -> Reader[IntoDataFrameT, nw.LazyFrame[IntoDataFrameT]]: ... + + +@overload +def reader( + read_fns: Sequence[Read[IntoDataFrameT]], + scan_fns: Sequence[Scan[IntoFrameT]], + *, + name: str | None = ..., + implementation: nw.Implementation = ..., +) -> Reader[IntoDataFrameT, IntoFrameT]: ... + + +def reader( + read_fns: Sequence[Read[IntoDataFrameT]], + scan_fns: Sequence[Scan[IntoFrameT]] = (), + *, + name: str | None = None, + implementation: nw.Implementation = nw.Implementation.UNKNOWN, +) -> ( + Reader[IntoDataFrameT, IntoFrameT] + | Reader[IntoDataFrameT, nw.LazyFrame[IntoDataFrameT]] +): + name = name or Counter(el._inferred_package for el in read_fns).most_common(1)[0][0] + if implementation is nw.Implementation.UNKNOWN: + implementation = _into_implementation(Requirement(name)) + if scan_fns: + return Reader(read_fns, scan_fns, name, implementation) + if stolen := _steal_eager_parquet(read_fns): + return Reader(read_fns, stolen, name, implementation) + else: + return _NoParquetReader[IntoDataFrameT](read_fns, (), name, implementation) + + +def infer_backend( + *, priority: Sequence[_Backend] = ("polars", "pandas[pyarrow]", "pandas", "pyarrow") +) -> Reader[Any, Any]: + """ + Return the first available reader in order of `priority`. + + Notes + ----- + - ``"polars"``: can natively load every dataset (including ``(Geo|Topo)JSON``) + - ``"pandas[pyarrow]"``: can load *most* datasets, guarantees ``.parquet`` support + - ``"pandas"``: supports ``.parquet``, if `fastparquet`_ is installed + - ``"pyarrow"``: least reliable + + .. _fastparquet: + https://github.com/dask/fastparquet + """ + it = (_from_backend(name) for name in priority if is_available(_requirements(name))) + if reader := next(it, None): + return reader + raise AltairDatasetsError.from_priority(priority) + + +@overload +def _from_backend(name: _Polars, /) -> Reader[pl.DataFrame, pl.LazyFrame]: ... +@overload +def _from_backend(name: _PandasAny, /) -> Reader[pd.DataFrame, pd.DataFrame]: ... +@overload +def _from_backend(name: _PyArrow, /) -> Reader[pa.Table, pa.Table]: ... + + +# FIXME: The order this is defined in makes splitting the module complicated +# - Can't use a classmethod, since some result in a subclass used +def _from_backend(name: _Backend, /) -> Reader[Any, Any]: + """ + Reader initialization dispatcher. + + FIXME: Works, but defining these in mixed shape functions seems off. + """ + if not _is_backend(name): + msg = f"Unknown backend {name!r}" + raise TypeError(msg) + implementation = _into_implementation(name) + if name == "polars": + rd, sc = _readimpl.pl_only() + return reader(rd, sc, name=name, implementation=implementation) + elif name == "pandas[pyarrow]": + return reader(_readimpl.pd_pyarrow(), name=name, implementation=implementation) + elif name == "pandas": + return reader(_readimpl.pd_only(), name=name, implementation=implementation) + elif name == "pyarrow": + return reader(_readimpl.pa_any(), name=name, implementation=implementation) + + +def _is_backend(obj: Any) -> TypeIs[_Backend]: + return obj in {"polars", "pandas", "pandas[pyarrow]", "pyarrow"} + + +def _is_err(obj: Any) -> TypeIs[type[AltairDatasetsError]]: + return obj is AltairDatasetsError + + +def _into_constraints( + name: Dataset | LiteralString, suffix: Extension | None, / +) -> Metadata: + """Transform args into a mapping to column names.""" + m: Metadata = {} + if "." in name: + m["file_name"] = name + elif suffix is None: + m["dataset_name"] = name + elif suffix.startswith("."): + m = {"dataset_name": name, "suffix": suffix} + else: + from typing import get_args + + from altair.datasets._typing import Extension + + msg = ( + f"Expected 'suffix' to be one of {get_args(Extension)!r},\n" + f"but got: {suffix!r}" + ) + raise TypeError(msg) + return m + + +def _into_implementation( + backend: _NwSupport | _PandasAny | Requirement, / +) -> nw.Implementation: + primary = _import_guarded(backend) + impl = nw.Implementation.from_backend(primary) + if impl is not nw.Implementation.UNKNOWN: + return impl + msg = f"Package {primary!r} is not supported by `narwhals`." + raise ValueError(msg) + + +def _into_suffix(obj: Path | str, /) -> Any: + if isinstance(obj, Path): + return obj.suffix + elif isinstance(obj, str): + return obj + else: + msg = f"Unexpected type {type(obj).__name__!r}" + raise TypeError(msg) + + +def _steal_eager_parquet( + read_fns: Sequence[Read[IntoDataFrameT]], / +) -> Sequence[Scan[nw.LazyFrame[IntoDataFrameT]]] | None: + if convertable := next((rd for rd in read_fns if rd.include <= is_parquet), None): + return (_readimpl.into_scan(convertable),) + return None + + +@overload +def _import_guarded(req: _PandasAny, /) -> _Pandas: ... + + +@overload +def _import_guarded(req: _NwSupportT, /) -> _NwSupportT: ... + + +@overload +def _import_guarded(req: Requirement, /) -> LiteralString: ... + + +def _import_guarded(req: Any, /) -> LiteralString: + requires = _requirements(req) + for name in requires: + if spec := find_spec(name): + import_module(spec.name) + else: + raise module_not_found(str(req), requires, missing=name) + return requires[0] + + +def _requirements(req: Requirement | str, /) -> tuple[Any, ...]: + req = Requirement(req) if isinstance(req, str) else req + return (req.name, *req.extras) diff --git a/.venv/lib/python3.13/site-packages/altair/datasets/_readimpl.py b/.venv/lib/python3.13/site-packages/altair/datasets/_readimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..34b31070a52be7ebad5bf8c8fcfa964153dc2d27 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/datasets/_readimpl.py @@ -0,0 +1,511 @@ +"""Individual read functions and siuations they support.""" + +from __future__ import annotations + +import sys +from enum import Enum +from functools import partial, wraps +from importlib.util import find_spec +from itertools import chain +from operator import itemgetter +from pathlib import Path +from typing import TYPE_CHECKING, Any, Generic, Literal + +from narwhals.stable import v1 as nw +from narwhals.stable.v1.dependencies import get_pandas, get_polars +from narwhals.stable.v1.typing import IntoDataFrameT + +from altair.datasets._constraints import ( + is_arrow, + is_csv, + is_json, + is_meta, + is_not_tabular, + is_parquet, + is_spatial, + is_topo, + is_tsv, +) +from altair.datasets._exceptions import AltairDatasetsError + +if sys.version_info >= (3, 13): + from typing import TypeVar +else: + from typing_extensions import TypeVar +if sys.version_info >= (3, 12): + from typing import TypeAliasType +else: + from typing_extensions import TypeAliasType + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Iterator, Sequence + from io import IOBase + from types import ModuleType + + import pandas as pd + import polars as pl + import pyarrow as pa + from narwhals.stable.v1 import typing as nwt + + from altair.datasets._constraints import Items, MetaIs + +__all__ = ["is_available", "pa_any", "pd_only", "pd_pyarrow", "pl_only", "read", "scan"] + +R = TypeVar("R", bound="nwt.IntoFrame", covariant=True) +IntoFrameT = TypeVar( + "IntoFrameT", + bound="nwt.NativeFrame | nw.DataFrame[Any] | nw.LazyFrame[Any] | nwt.DataFrameLike", + default=nw.LazyFrame[Any], +) +Read = TypeAliasType("Read", "BaseImpl[IntoDataFrameT]", type_params=(IntoDataFrameT,)) +"""An *eager* file read function.""" + +Scan = TypeAliasType("Scan", "BaseImpl[IntoFrameT]", type_params=(IntoFrameT,)) +"""A *lazy* file read function.""" + + +class Skip(Enum): + """Falsy sentinel.""" + + skip = 0 + + def __bool__(self) -> Literal[False]: + return False + + def __repr__(self) -> Literal[""]: + return "" + + +class BaseImpl(Generic[R]): + """ + A function wrapped with dataset support constraints. + + The ``include``, ``exclude`` properties form a `NIMPLY gate`_ (`Material nonimplication`_). + + Examples + -------- + For some dataset ``D``, we can use ``fn`` if:: + + impl: BaseImpl + impl.include(D) and not impl.exclude(D) + + + .. _NIMPLY gate: + https://en.m.wikipedia.org/wiki/NIMPLY_gate + .. _Material nonimplication: + https://en.m.wikipedia.org/wiki/Material_nonimplication#Truth_table + """ + + fn: Callable[..., R] + """Wrapped read/scan function.""" + + include: MetaIs + """Constraint indicating ``fn`` **supports** reading a dataset.""" + + exclude: MetaIs + """Constraint *subsetting* ``include`` to mark **non-support**.""" + + def __init__( + self, + fn: Callable[..., R], + include: MetaIs, + exclude: MetaIs | None, + kwds: dict[str, Any], + /, + ) -> None: + exclude = exclude or self._exclude_none() + if not include.isdisjoint(exclude): + intersection = ", ".join(f"{k}={v!r}" for k, v in include & exclude) + msg = f"Constraints overlap at: `{intersection}`\ninclude={include!r}\nexclude={exclude!r}" + raise TypeError(msg) + object.__setattr__(self, "fn", partial(fn, **kwds) if kwds else fn) + object.__setattr__(self, "include", include) + object.__setattr__(self, "exclude", exclude) + + def unwrap_or_skip( + self, meta: Items, / + ) -> Callable[..., R] | type[AltairDatasetsError] | Skip: + """ + Indicate an action to take for a dataset. + + **Supports** dataset, use this function:: + + Callable[..., R] + + Has explicitly marked as **not supported**:: + + type[AltairDatasetsError] + + No relevant constraints overlap, safe to check others:: + + Skip + """ + if self.include.issubset(meta): + return self.fn if self.exclude.isdisjoint(meta) else AltairDatasetsError + return Skip.skip + + @classmethod + def _exclude_none(cls) -> MetaIs: + """Represents the empty set.""" + return is_meta() + + def __setattr__(self, name: str, value: Any): + msg = ( + f"{type(self).__name__!r} is immutable.\n" + f"Could not assign self.{name} = {value}" + ) + raise TypeError(msg) + + @property + def _inferred_package(self) -> str: + return _root_package_name(_unwrap_partial(self.fn), "UNKNOWN") + + def __repr__(self) -> str: + tp_name = f"{type(self).__name__}[{self._inferred_package}?]" + return f"{tp_name}({self})" + + def __str__(self) -> str: + if isinstance(self.fn, partial): + fn = _unwrap_partial(self.fn) + kwds = self.fn.keywords.items() + fn_repr = f"{fn.__name__}(..., {', '.join(f'{k}={v!r}' for k, v in kwds)})" + else: + fn_repr = f"{self.fn.__name__}(...)" + inc, exc = self.include, self.exclude + return f"{fn_repr}, {f'include={inc!r}, exclude={exc!r}' if exc else repr(inc)}" + + @property + def _relevant_columns(self) -> Iterator[str]: + name = itemgetter(0) + yield from (name(obj) for obj in chain(self.include, self.exclude)) + + @property + def _include_expr(self) -> nw.Expr: + return ( + self.include.to_expr() & ~self.exclude.to_expr() + if self.exclude + else self.include.to_expr() + ) + + @property + def _exclude_expr(self) -> nw.Expr: + if self.exclude: + return self.include.to_expr() & self.exclude.to_expr() + msg = f"Unable to generate an exclude expression without setting exclude\n\n{self!r}" + raise TypeError(msg) + + +def read( + fn: Callable[..., IntoDataFrameT], + /, + include: MetaIs, + exclude: MetaIs | None = None, + **kwds: Any, +) -> Read[IntoDataFrameT]: + return BaseImpl(fn, include, exclude, kwds) + + +def scan( + fn: Callable[..., IntoFrameT], + /, + include: MetaIs, + exclude: MetaIs | None = None, + **kwds: Any, +) -> Scan[IntoFrameT]: + return BaseImpl(fn, include, exclude, kwds) + + +def into_scan(impl: Read[IntoDataFrameT], /) -> Scan[nw.LazyFrame[IntoDataFrameT]]: + def scan_fn( + fn: Callable[..., IntoDataFrameT], / + ) -> Callable[..., nw.LazyFrame[IntoDataFrameT]]: + @wraps(_unwrap_partial(fn)) + def wrapper(*args: Any, **kwds: Any) -> nw.LazyFrame[IntoDataFrameT]: + return nw.from_native(fn(*args, **kwds)).lazy() + + return wrapper + + return scan(scan_fn(impl.fn), impl.include, impl.exclude) + + +def is_available( + pkg_names: str | Iterable[str], *more_pkg_names: str, require_all: bool = True +) -> bool: + """ + Check for importable package(s), without raising on failure. + + Parameters + ---------- + pkg_names, more_pkg_names + One or more packages. + require_all + * ``True`` every package. + * ``False`` at least one package. + """ + if not more_pkg_names and isinstance(pkg_names, str): + return find_spec(pkg_names) is not None + pkgs_names = pkg_names if not isinstance(pkg_names, str) else (pkg_names,) + names = chain(pkgs_names, more_pkg_names) + fn = all if require_all else any + return fn(find_spec(name) is not None for name in names) + + +def _root_package_name(obj: Any, default: str, /) -> str: + # NOTE: Defers importing `inspect`, if we can get the module name + if hasattr(obj, "__module__"): + return obj.__module__.split(".")[0] + else: + from inspect import getmodule + + module = getmodule(obj) + if module and (pkg := module.__package__): + return pkg.split(".")[0] + return default + + +def _unwrap_partial(fn: Any, /) -> Any: + # NOTE: ``functools._unwrap_partial`` + func = fn + while isinstance(func, partial): + func = func.func + return func + + +def pl_only() -> tuple[Sequence[Read[pl.DataFrame]], Sequence[Scan[pl.LazyFrame]]]: + import polars as pl + + pl_read_json = read(_pl_read_json_roundtrip(get_polars()), is_json) + if is_available("polars_st"): + fn_json: Sequence[Read[pl.DataFrame]] = ( + _pl_read_json_polars_st_topo_impl(), # TopoJSON files first + _pl_read_json_polars_st_impl(), # Then other spatial JSON + pl_read_json, + ) + else: + fn_json = (pl_read_json,) + + read_fns = ( + read(pl.read_csv, is_csv, try_parse_dates=True), + *fn_json, + read(pl.read_csv, is_tsv, separator="\t", try_parse_dates=True), + read(pl.read_ipc, is_arrow), + read(pl.read_parquet, is_parquet), + ) + scan_fns = (scan(pl.scan_parquet, is_parquet),) + return read_fns, scan_fns + + +def pd_only() -> Sequence[Read[pd.DataFrame]]: + import pandas as pd + + opt: Sequence[Read[pd.DataFrame]] + if is_available("pyarrow"): + opt = read(pd.read_feather, is_arrow), read(pd.read_parquet, is_parquet) + elif is_available("fastparquet"): + opt = (read(pd.read_parquet, is_parquet),) + else: + opt = () + pd_read_json = read(_pd_read_json(get_pandas()), is_json, exclude=is_spatial) + if is_available("geopandas"): + fn_json: Sequence[Read[pd.DataFrame]] = ( + _pd_read_json_geopandas_impl(), + pd_read_json, + ) + else: + fn_json = (pd_read_json,) + return ( + read(pd.read_csv, is_csv), + *fn_json, + read(pd.read_csv, is_tsv, sep="\t"), + *opt, + ) + + +def pd_pyarrow() -> Sequence[Read[pd.DataFrame]]: + import pandas as pd + + kwds: dict[str, Any] = {"dtype_backend": "pyarrow"} + pd_read_json = read( + _pd_read_json(get_pandas()), is_json, exclude=is_spatial, **kwds + ) + if is_available("geopandas"): + fn_json: Sequence[Read[pd.DataFrame]] = ( + _pd_read_json_geopandas_impl(), + pd_read_json, + ) + else: + fn_json = (pd_read_json,) + return ( + read(pd.read_csv, is_csv, **kwds), + *fn_json, + read(pd.read_csv, is_tsv, sep="\t", **kwds), + read(pd.read_feather, is_arrow, **kwds), + read(pd.read_parquet, is_parquet, **kwds), + ) + + +def pa_any() -> Sequence[Read[pa.Table]]: + from pyarrow import csv, feather, parquet + + return ( + read(csv.read_csv, is_csv), + _pa_read_json_impl(), + read(csv.read_csv, is_tsv, parse_options=csv.ParseOptions(delimiter="\t")), # pyright: ignore[reportCallIssue] + read(feather.read_table, is_arrow), + read(parquet.read_table, is_parquet), + ) + + +def _pa_read_json_impl() -> Read[pa.Table]: + """ + Mitigating ``pyarrow``'s `line-delimited`_ JSON requirement. + + .. _line-delimited: + https://arrow.apache.org/docs/python/json.html#reading-json-files + """ + if is_available("polars"): + polars_ns = get_polars() + if polars_ns is not None: + return read(_pl_read_json_roundtrip_to_arrow(polars_ns), is_json) + if is_available("pandas"): + pandas_ns = get_pandas() + if pandas_ns is not None: + return read(_pd_read_json_to_arrow(pandas_ns), is_json, exclude=is_spatial) + return read(_stdlib_read_json_to_arrow, is_json, exclude=is_not_tabular) + + +def _pd_read_json(ns: ModuleType, /) -> Callable[..., pd.DataFrame]: + @wraps(ns.read_json) + def fn(source: Path | Any, /, **kwds: Any) -> pd.DataFrame: + return _pd_fix_dtypes_nw(ns.read_json(source, **kwds), **kwds).to_native() + + return fn + + +def _pd_read_json_geopandas_impl() -> Read[pd.DataFrame]: + import geopandas + + @wraps(geopandas.read_file) + def fn(source: Path | Any, /, schema: Any = None, **kwds: Any) -> pd.DataFrame: + return geopandas.read_file(source, **kwds) + + return read(fn, is_meta(is_spatial=True, suffix=".json")) + + +def _pd_fix_dtypes_nw( + df: pd.DataFrame, /, *, dtype_backend: Any = None, **kwds: Any +) -> nw.DataFrame[pd.DataFrame]: + kwds = {"dtype_backend": dtype_backend} if dtype_backend else {} + return ( + df.convert_dtypes(**kwds) + .pipe(nw.from_native, eager_only=True) + .with_columns(nw.selectors.by_dtype(nw.Object).cast(nw.String)) + ) + + +def _pd_read_json_to_arrow(ns: ModuleType, /) -> Callable[..., pa.Table]: + @wraps(ns.read_json) + def fn(source: Path | Any, /, *, schema: Any = None, **kwds: Any) -> pa.Table: + """``schema`` is only here to swallow the ``SchemaCache`` if used.""" + return ( + ns.read_json(source, **kwds) + .pipe(_pd_fix_dtypes_nw, dtype_backend="pyarrow") + .to_arrow() + ) + + return fn + + +def _pl_read_json_polars_st_impl() -> Read[pl.DataFrame]: + import polars_st as st + + @wraps(st.read_file) + def fn(source: Path | Any, /, schema: Any = None, **kwds: Any) -> pl.DataFrame: + return st.read_file(source, **kwds) + + return read(fn, is_meta(is_spatial=True, suffix=".json")) + + +def _pl_read_json_polars_st_topo_impl() -> Read[pl.DataFrame]: + import polars_st as st + + @wraps(st.read_file) + def fn(source: Path | Any, /, schema: Any = None, **kwds: Any) -> pl.DataFrame: + # Add TopoJSON driver prefix for URLs + if isinstance(source, str) and source.startswith("http"): + source = f"TopoJSON:{source}" + return st.read_file(source, **kwds) + + return read(fn, is_topo) + + +def _pl_read_json_roundtrip(ns: ModuleType, /) -> Callable[..., pl.DataFrame]: + """ + Try to utilize better date parsing available in `pl.read_csv`_. + + `pl.read_json`_ has few options when compared to `pl.read_csv`_. + + Chaining the two together - *where possible* - is still usually faster than `pandas.read_json`_. + + .. _pl.read_json: + https://docs.pola.rs/api/python/stable/reference/api/polars.read_json.html + .. _pl.read_csv: + https://docs.pola.rs/api/python/stable/reference/api/polars.read_csv.html + .. _pandas.read_json: + https://pandas.pydata.org/docs/reference/api/pandas.read_json.html + """ + from io import BytesIO + + @wraps(ns.read_json) + def fn(source: Path | IOBase, /, **kwds: Any) -> pl.DataFrame: + df = ns.read_json(source, **kwds) + if any(tp.is_nested() for tp in df.schema.dtypes()): + return df + buf = BytesIO() + df.write_csv(buf) + if kwds: + SHARED_KWDS = {"schema", "schema_overrides", "infer_schema_length"} + kwds = {k: v for k, v in kwds.items() if k in SHARED_KWDS} + return ns.read_csv(buf, try_parse_dates=True, **kwds) + + return fn + + +def _pl_read_json_roundtrip_to_arrow(ns: ModuleType, /) -> Callable[..., pa.Table]: + eager = _pl_read_json_roundtrip(ns) + + @wraps(ns.read_json) + def fn(source: Path | IOBase, /, **kwds: Any) -> pa.Table: + return eager(source).to_arrow() + + return fn + + +def _stdlib_read_json(source: Path | Any, /) -> Any: + import json + + if not isinstance(source, Path): + return json.load(source) + else: + with Path(source).open(encoding="utf-8") as f: + return json.load(f) + + +def _stdlib_read_json_to_arrow(source: Path | Any, /, **kwds: Any) -> pa.Table: + import pyarrow as pa + + rows: list[dict[str, Any]] = _stdlib_read_json(source) + try: + return pa.Table.from_pylist(rows, **kwds) + except TypeError: + import csv + import io + + from pyarrow import csv as pa_csv + + with io.StringIO() as f: + writer = csv.DictWriter(f, rows[0].keys(), dialect=csv.unix_dialect) + writer.writeheader() + writer.writerows(rows) + with io.BytesIO(f.getvalue().encode()) as f2: + return pa_csv.read_csv(f2) diff --git a/.venv/lib/python3.13/site-packages/altair/datasets/_typing.py b/.venv/lib/python3.13/site-packages/altair/datasets/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..70c89e879d67c8b5b5c923ff4fa09cb492d13824 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/datasets/_typing.py @@ -0,0 +1,225 @@ +# The contents of this file are automatically written by +# tools/datasets.__init__.py. Do not modify directly. + +from __future__ import annotations + +import sys +from typing import Literal + +if sys.version_info >= (3, 15): + from typing import TypedDict +else: + from typing_extensions import TypedDict + +if sys.version_info >= (3, 11): + from typing import LiteralString +else: + from typing_extensions import LiteralString + +if sys.version_info >= (3, 10): + from typing import TypeAlias +else: + from typing_extensions import TypeAlias + + +__all__ = ["Dataset", "Extension", "Metadata"] + +Dataset: TypeAlias = Literal[ + "airports", + "annual_precip", + "anscombe", + "barley", + "birdstrikes", + "budget", + "budgets", + "burtin", + "cars", + "co2_concentration", + "countries", + "crimea", + "disasters", + "driving", + "earthquakes", + "ffox", + "flare", + "flare_dependencies", + "flights_10k", + "flights_200k_arrow", + "flights_200k_json", + "flights_20k", + "flights_2k", + "flights_3m", + "flights_5k", + "flights_airport", + "football", + "gapminder", + "gapminder_health_income", + "gimp", + "github", + "global_temp", + "icon_7zip", + "income", + "iowa_electricity", + "jobs", + "la_riots", + "london_boroughs", + "london_centroids", + "london_tube_lines", + "lookup_groups", + "lookup_people", + "miserables", + "monarchs", + "movies", + "normal_2d", + "obesity", + "ohlc", + "penguins", + "platformer_terrain", + "political_contributions", + "population", + "population_engineers_hurricanes", + "seattle_weather", + "seattle_weather_hourly_normals", + "sp500", + "sp500_2000", + "species", + "stocks", + "udistrict", + "unemployment", + "unemployment_across_industries", + "uniform_2d", + "us_10m", + "us_employment", + "us_state_capitals", + "volcano", + "weather", + "weekly_weather", + "wheat", + "windvectors", + "world_110m", + "zipcodes", +] +Extension: TypeAlias = Literal[".arrow", ".csv", ".json", ".parquet", ".png", ".tsv"] + + +class Metadata(TypedDict, total=False): + """ + Full schema for ``metadata.parquet``. + + Parameters + ---------- + dataset_name + Name of the dataset from the resource name field. + suffix + File extension/`Path.suffix`_. + file_name + Equivalent to `Path.name`_. + bytes + File size in *bytes*. + is_image + Only accessible via url. + is_tabular + Can be read as tabular data. + is_geo + `GeoJSON`_ format. + is_topo + `TopoJSON`_ format. + is_spatial + Any geospatial format. Only natively supported by ``polars``. + is_json + Not supported natively by ``pyarrow``. + has_schema + Data types available for improved ``pandas`` parsing. + sha + Unique hash for the dataset. + + .. note:: + E.g. if the dataset did *not* change between ``v1.0.0``-``v2.0.0``; + + then this value would remain stable. + url + Remote url used to access dataset. + + .. _Path.stem: + https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem + .. _Path.name: + https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.name + .. _Path.suffix: + https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.suffix + .. _GeoJSON: + https://en.wikipedia.org/wiki/GeoJSON + .. _TopoJSON: + https://en.wikipedia.org/wiki/GeoJSON#TopoJSON + + + Examples + -------- + ``Metadata`` keywords form constraints to filter a table like the below sample: + + ``` + shape: (73, 13) + ┌────────────────┬────────┬────────────────┬───┬───────────────┬───────────────┐ + │ dataset_name ┆ suffix ┆ file_name ┆ … ┆ sha ┆ url │ + │ --- ┆ --- ┆ --- ┆ ┆ --- ┆ --- │ + │ str ┆ str ┆ str ┆ ┆ str ┆ str │ + ╞════════════════╪════════╪════════════════╪═══╪═══════════════╪═══════════════╡ + │ airports ┆ .csv ┆ airports.csv ┆ … ┆ 608ba6d51fa70 ┆ https://cdn.j │ + │ ┆ ┆ ┆ ┆ 584c3fa1d31e… ┆ sdelivr.net/… │ + │ annual_precip ┆ .json ┆ annual-precip. ┆ … ┆ 719e73406cfc0 ┆ https://cdn.j │ + │ ┆ ┆ json ┆ ┆ 8f16dda65151… ┆ sdelivr.net/… │ + │ anscombe ┆ .json ┆ anscombe.json ┆ … ┆ 11ae97090b626 ┆ https://cdn.j │ + │ ┆ ┆ ┆ ┆ 3bdf0c866115… ┆ sdelivr.net/… │ + │ barley ┆ .json ┆ barley.json ┆ … ┆ 8dc50de2509b6 ┆ https://cdn.j │ + │ ┆ ┆ ┆ ┆ e197ce95c24c… ┆ sdelivr.net/… │ + │ birdstrikes ┆ .csv ┆ birdstrikes.cs ┆ … ┆ 1b8b190c9bc02 ┆ https://cdn.j │ + │ ┆ ┆ v ┆ ┆ ef7bcbfe5a8a… ┆ sdelivr.net/… │ + │ … ┆ … ┆ … ┆ … ┆ … ┆ … │ + │ weekly_weather ┆ .json ┆ weekly-weather ┆ … ┆ bd42a3e2403e7 ┆ https://cdn.j │ + │ ┆ ┆ .json ┆ ┆ ccd6baaa89f9… ┆ sdelivr.net/… │ + │ wheat ┆ .json ┆ wheat.json ┆ … ┆ cde46b43fc82f ┆ https://cdn.j │ + │ ┆ ┆ ┆ ┆ 4c3c2a37ddcf… ┆ sdelivr.net/… │ + │ windvectors ┆ .csv ┆ windvectors.cs ┆ … ┆ ed686b0ba613a ┆ https://cdn.j │ + │ ┆ ┆ v ┆ ┆ bd59d09fcd94… ┆ sdelivr.net/… │ + │ world_110m ┆ .json ┆ world-110m.jso ┆ … ┆ a1ce852de6f27 ┆ https://cdn.j │ + │ ┆ ┆ n ┆ ┆ 13c94c0c2840… ┆ sdelivr.net/… │ + │ zipcodes ┆ .csv ┆ zipcodes.csv ┆ … ┆ d3df33e12be0d ┆ https://cdn.j │ + │ ┆ ┆ ┆ ┆ 0544c95f1bd4… ┆ sdelivr.net/… │ + └────────────────┴────────┴────────────────┴───┴───────────────┴───────────────┘ + ``` + """ + + dataset_name: Dataset | LiteralString + suffix: Extension + file_name: str + bytes: int + is_image: bool + is_tabular: bool + is_geo: bool + is_topo: bool + is_spatial: bool + is_json: bool + has_schema: bool + sha: str + url: str + + +FlFieldStr: TypeAlias = Literal[ + "integer", + "number", + "boolean", + "string", + "object", + "array", + "date", + "datetime", + "time", + "duration", +] +""" +String representation of `frictionless`_ `Field Types`_. + +.. _frictionless: + https://github.com/frictionlessdata/frictionless-py +.. _Field Types: + https://datapackage.org/standard/table-schema/#field-types +""" diff --git a/.venv/lib/python3.13/site-packages/altair/expr/__init__.py b/.venv/lib/python3.13/site-packages/altair/expr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ce3bc19057e9d83451927a461ab4b9cf25487061 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/expr/__init__.py @@ -0,0 +1,2086 @@ +# The contents of this file are automatically written by +# tools/generate_schema_wrapper.py. Do not modify directly. + +"""Tools for creating transform & filter expressions with a python syntax.""" + +from __future__ import annotations + +import sys +from typing import TYPE_CHECKING, Any + +from altair.expr.core import ConstExpression, FunctionExpression +from altair.vegalite.v6.schema.core import ExprRef as _ExprRef + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + +if TYPE_CHECKING: + from altair.expr.core import Expression, IntoExpression + + +class _ExprMeta(type): + """ + Metaclass for :class:`expr`. + + Currently providing read-only class properties, representing JavaScript constants. + """ + + @property + def NaN(cls) -> Expression: + """Not a number (same as JavaScript literal NaN).""" + return ConstExpression("NaN") + + @property + def LN10(cls) -> Expression: + """The natural log of 10 (alias to Math.LN10).""" + return ConstExpression("LN10") + + @property + def E(cls) -> Expression: + """The transcendental number e (alias to Math.E).""" + return ConstExpression("E") + + @property + def LOG10E(cls) -> Expression: + """The base 10 logarithm e (alias to Math.LOG10E).""" + return ConstExpression("LOG10E") + + @property + def LOG2E(cls) -> Expression: + """The base 2 logarithm of e (alias to Math.LOG2E).""" + return ConstExpression("LOG2E") + + @property + def SQRT1_2(cls) -> Expression: + """The square root of 0.5 (alias to Math.SQRT1_2).""" + return ConstExpression("SQRT1_2") + + @property + def LN2(cls) -> Expression: + """The natural log of 2 (alias to Math.LN2).""" + return ConstExpression("LN2") + + @property + def SQRT2(cls) -> Expression: + """The square root of 2 (alias to Math.SQRT1_2).""" + return ConstExpression("SQRT2") + + @property + def PI(cls) -> Expression: + """The transcendental number pi (alias to Math.PI).""" + return ConstExpression("PI") + + +class expr(_ExprRef, metaclass=_ExprMeta): + """ + Utility providing *constants* and *classmethods* to construct expressions. + + `Expressions`_ can be used to write basic formulas that enable custom interactions. + + Alternatively, an `inline expression`_ may be defined via :class:`expr()`. + + Parameters + ---------- + expr: str + A `vega expression`_ string. + + Returns + ------- + ``ExprRef`` + + .. _Expressions: + https://altair-viz.github.io/user_guide/interactions/expressions.html + .. _inline expression: + https://altair-viz.github.io/user_guide/interactions/expressions.html#inline-expressions + .. _vega expression: + https://vega.github.io/vega/docs/expressions/ + + Examples + -------- + >>> import altair as alt + + >>> bind_range = alt.binding_range(min=100, max=300, name="Slider value: ") + >>> param_width = alt.param(bind=bind_range, name="param_width") + >>> param_color = alt.param( + ... expr=alt.expr.if_(param_width < 200, "red", "black"), + ... name="param_color", + ... ) + >>> y = alt.Y("yval").axis(titleColor=param_color) + + >>> y + Y({ + axis: {'titleColor': Parameter('param_color', VariableParameter({ + expr: if((param_width < 200),'red','black'), + name: 'param_color' + }))}, + shorthand: 'yval' + }) + + .. _Number.isNaN: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNan + .. _Number.isFinite: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite + .. _Math.abs: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs + .. _Math.acos: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/acos + .. _Math.asin: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/asin + .. _Math.atan: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan + .. _Math.atan2: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2 + .. _Math.ceil: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil + .. _Math.cos: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cos + .. _Math.exp: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/exp + .. _Math.floor: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor + .. _Math.hypot: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot + .. _Math.log: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log + .. _Math.max: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max + .. _Math.min: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min + .. _Math.pow: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow + .. _Math.random: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random + .. _Math.round: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round + .. _Math.sin: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sin + .. _Math.sqrt: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt + .. _Math.tan: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/tan + .. _normal (Gaussian) probability distribution: + https://en.wikipedia.org/wiki/Normal_distribution + .. _cumulative distribution function: + https://en.wikipedia.org/wiki/Cumulative_distribution_function + .. _probability density function: + https://en.wikipedia.org/wiki/Probability_density_function + .. _log-normal probability distribution: + https://en.wikipedia.org/wiki/Log-normal_distribution + .. _continuous uniform probability distribution: + https://en.wikipedia.org/wiki/Continuous_uniform_distribution + .. _*unit*: + https://vega.github.io/vega/docs/api/time/#time-units + .. _ascending from Vega Utils: + https://vega.github.io/vega/docs/api/util/#ascending + .. _JavaScript's String.replace: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace + .. _Base64: + https://developer.mozilla.org/en-US/docs/Glossary/Base64 + .. _ASCII: + https://developer.mozilla.org/en-US/docs/Glossary/ASCII + .. _Window.btoa(): + https://developer.mozilla.org/en-US/docs/Web/API/Window/btoa + .. _Window.atob(): + https://developer.mozilla.org/en-US/docs/Web/API/Window/atob + .. _d3-format specifier: + https://github.com/d3/d3-format/ + .. _*units*: + https://vega.github.io/vega/docs/api/time/#time-units + .. _timeUnitSpecifier API documentation: + https://vega.github.io/vega/docs/api/time/#timeUnitSpecifier + .. _timeFormat: + https://vega.github.io/vega/docs/expressions/#timeFormat + .. _utcFormat: + https://vega.github.io/vega/docs/expressions/#utcFormat + .. _d3-time-format specifier: + https://github.com/d3/d3-time-format/ + .. _TimeMultiFormat object: + https://vega.github.io/vega/docs/types/#TimeMultiFormat + .. _UTC: + https://en.wikipedia.org/wiki/Coordinated_Universal_Time + .. _JavaScript's RegExp: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp + .. _RGB: + https://en.wikipedia.org/wiki/RGB_color_model + .. _d3-color's rgb function: + https://github.com/d3/d3-color#rgb + .. _HSL: + https://en.wikipedia.org/wiki/HSL_and_HSV + .. _d3-color's hsl function: + https://github.com/d3/d3-color#hsl + .. _CIE LAB: + https://en.wikipedia.org/wiki/Lab_color_space#CIELAB + .. _d3-color's lab function: + https://github.com/d3/d3-color#lab + .. _HCL: + https://en.wikipedia.org/wiki/Lab_color_space#CIELAB + .. _d3-color's hcl function: + https://github.com/d3/d3-color#hcl + .. _W3C Web Content Accessibility Guidelines: + https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef + .. _continuous color scheme: + https://vega.github.io/vega/docs/schemes + .. _geoArea: + https://github.com/d3/d3-geo#geoArea + .. _path.area: + https://github.com/d3/d3-geo#path_area + .. _geoBounds: + https://github.com/d3/d3-geo#geoBounds + .. _path.bounds: + https://github.com/d3/d3-geo#path_bounds + .. _geoCentroid: + https://github.com/d3/d3-geo#geoCentroid + .. _path.centroid: + https://github.com/d3/d3-geo#path_centroid + .. _window.screen: + https://developer.mozilla.org/en-US/docs/Web/API/Window/screen + """ + + @override + def __new__(cls: type[_ExprRef], expr: str) -> _ExprRef: # type: ignore[misc] + return _ExprRef(expr=expr) + + @classmethod + def isArray(cls, value: IntoExpression, /) -> Expression: + """Returns true if ``value`` is an array, false otherwise.""" + return FunctionExpression("isArray", (value,)) + + @classmethod + def isBoolean(cls, value: IntoExpression, /) -> Expression: + """Returns true if ``value`` is a boolean (``true`` or ``false``), false otherwise.""" + return FunctionExpression("isBoolean", (value,)) + + @classmethod + def isDate(cls, value: IntoExpression, /) -> Expression: + """ + 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. + """ + return FunctionExpression("isDate", (value,)) + + @classmethod + def isDefined(cls, value: IntoExpression, /) -> Expression: + """ + Returns true if ``value`` is a defined value, false if ``value`` equals ``undefined``. + + This method will return true for ``null`` and ``NaN`` values. + """ + return FunctionExpression("isDefined", (value,)) + + @classmethod + def isNumber(cls, value: IntoExpression, /) -> Expression: + """ + Returns true if ``value`` is a number, false otherwise. + + ``NaN`` and ``Infinity`` are considered numbers. + """ + return FunctionExpression("isNumber", (value,)) + + @classmethod + def isObject(cls, value: IntoExpression, /) -> Expression: + """Returns true if ``value`` is an object (including arrays and Dates), false otherwise.""" + return FunctionExpression("isObject", (value,)) + + @classmethod + def isRegExp(cls, value: IntoExpression, /) -> Expression: + """Returns true if ``value`` is a RegExp (regular expression) object, false otherwise.""" + return FunctionExpression("isRegExp", (value,)) + + @classmethod + def isString(cls, value: IntoExpression, /) -> Expression: + """Returns true if ``value`` is a string, false otherwise.""" + return FunctionExpression("isString", (value,)) + + @classmethod + def isValid(cls, value: IntoExpression, /) -> Expression: + """Returns true if ``value`` is not ``null``, ``undefined``, or ``NaN``, false otherwise.""" + return FunctionExpression("isValid", (value,)) + + @classmethod + def toBoolean(cls, value: IntoExpression, /) -> Expression: + """ + Coerces the input ``value`` to a string. + + Null values and empty strings are mapped to ``null``. + """ + return FunctionExpression("toBoolean", (value,)) + + @classmethod + def toDate(cls, value: IntoExpression, /) -> Expression: + """ + 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! + """ + return FunctionExpression("toDate", (value,)) + + @classmethod + def toNumber(cls, value: IntoExpression, /) -> Expression: + """ + Coerces the input ``value`` to a number. + + Null values and empty strings are mapped to ``null``. + """ + return FunctionExpression("toNumber", (value,)) + + @classmethod + def toString(cls, value: IntoExpression, /) -> Expression: + """ + Coerces the input ``value`` to a string. + + Null values and empty strings are mapped to ``null``. + """ + return FunctionExpression("toString", (value,)) + + @classmethod + def if_( + cls, + test: IntoExpression, + thenValue: IntoExpression, + elseValue: IntoExpression, + /, + ) -> Expression: + """ + If ``test`` is truthy, returns ``thenValue``. + + Otherwise, returns ``elseValue``. The *if* function is equivalent to the ternary operator + ``a ? b : c``. + """ + return FunctionExpression("if", (test, thenValue, elseValue)) + + @classmethod + def isNaN(cls, value: IntoExpression, /) -> Expression: + """ + Returns true if ``value`` is not a number. + + Same as JavaScript's `Number.isNaN`_. + + .. _Number.isNaN: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNan + """ + return FunctionExpression("isNaN", (value,)) + + @classmethod + def isFinite(cls, value: IntoExpression, /) -> Expression: + """ + Returns true if ``value`` is a finite number. + + Same as JavaScript's `Number.isFinite`_. + + .. _Number.isFinite: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite + """ + return FunctionExpression("isFinite", (value,)) + + @classmethod + def abs(cls, value: IntoExpression, /) -> Expression: + """ + Returns the absolute value of ``value``. + + Same as JavaScript's `Math.abs`_. + + .. _Math.abs: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs + """ + return FunctionExpression("abs", (value,)) + + @classmethod + def acos(cls, value: IntoExpression, /) -> Expression: + """ + Trigonometric arccosine. + + Same as JavaScript's `Math.acos`_. + + .. _Math.acos: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/acos + """ + return FunctionExpression("acos", (value,)) + + @classmethod + def asin(cls, value: IntoExpression, /) -> Expression: + """ + Trigonometric arcsine. + + Same as JavaScript's `Math.asin`_. + + .. _Math.asin: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/asin + """ + return FunctionExpression("asin", (value,)) + + @classmethod + def atan(cls, value: IntoExpression, /) -> Expression: + """ + Trigonometric arctangent. + + Same as JavaScript's `Math.atan`_. + + .. _Math.atan: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan + """ + return FunctionExpression("atan", (value,)) + + @classmethod + def atan2(cls, dy: IntoExpression, dx: IntoExpression, /) -> Expression: + """ + Returns the arctangent of *dy / dx*. + + Same as JavaScript's `Math.atan2`_. + + .. _Math.atan2: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2 + """ + return FunctionExpression("atan2", (dy, dx)) + + @classmethod + def ceil(cls, value: IntoExpression, /) -> Expression: + """ + Rounds ``value`` to the nearest integer of equal or greater value. + + Same as JavaScript's `Math.ceil`_. + + .. _Math.ceil: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil + """ + return FunctionExpression("ceil", (value,)) + + @classmethod + def clamp( + cls, value: IntoExpression, min: IntoExpression, max: IntoExpression, / + ) -> Expression: + """Restricts ``value`` to be between the specified ``min`` and ``max``.""" + return FunctionExpression("clamp", (value, min, max)) + + @classmethod + def cos(cls, value: IntoExpression, /) -> Expression: + """ + Trigonometric cosine. + + Same as JavaScript's `Math.cos`_. + + .. _Math.cos: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cos + """ + return FunctionExpression("cos", (value,)) + + @classmethod + def exp(cls, exponent: IntoExpression, /) -> Expression: + """ + Returns the value of *e* raised to the provided ``exponent``. + + Same as JavaScript's `Math.exp`_. + + .. _Math.exp: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/exp + """ + return FunctionExpression("exp", (exponent,)) + + @classmethod + def floor(cls, value: IntoExpression, /) -> Expression: + """ + Rounds ``value`` to the nearest integer of equal or lower value. + + Same as JavaScript's `Math.floor`_. + + .. _Math.floor: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor + """ + return FunctionExpression("floor", (value,)) + + @classmethod + def hypot(cls, value: IntoExpression, /) -> Expression: + """ + Returns the square root of the sum of squares of its arguments. + + Same as JavaScript's `Math.hypot`_. + + .. _Math.hypot: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot + """ + return FunctionExpression("hypot", (value,)) + + @classmethod + def log(cls, value: IntoExpression, /) -> Expression: + """ + Returns the natural logarithm of ``value``. + + Same as JavaScript's `Math.log`_. + + .. _Math.log: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log + """ + return FunctionExpression("log", (value,)) + + @classmethod + def max( + cls, value1: IntoExpression, value2: IntoExpression, *args: Any + ) -> Expression: + """ + Returns the maximum argument value. + + Same as JavaScript's `Math.max`_. + + .. _Math.max: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max + """ + return FunctionExpression("max", (value1, value2, *args)) + + @classmethod + def min( + cls, value1: IntoExpression, value2: IntoExpression, *args: Any + ) -> Expression: + """ + Returns the minimum argument value. + + Same as JavaScript's `Math.min`_. + + .. _Math.min: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min + """ + return FunctionExpression("min", (value1, value2, *args)) + + @classmethod + def pow(cls, value: IntoExpression, exponent: IntoExpression, /) -> Expression: + """ + Returns ``value`` raised to the given ``exponent``. + + Same as JavaScript's `Math.pow`_. + + .. _Math.pow: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow + """ + return FunctionExpression("pow", (value, exponent)) + + @classmethod + def random(cls) -> Expression: + """ + Returns a pseudo-random number in the range [0,1). + + Same as JavaScript's `Math.random`_. + + .. _Math.random: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random + """ + return FunctionExpression("random", ()) + + @classmethod + def round(cls, value: IntoExpression, /) -> Expression: + """ + Rounds ``value`` to the nearest integer. + + Same as JavaScript's `Math.round`_. + + .. _Math.round: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round + """ + return FunctionExpression("round", (value,)) + + @classmethod + def sin(cls, value: IntoExpression, /) -> Expression: + """ + Trigonometric sine. + + Same as JavaScript's `Math.sin`_. + + .. _Math.sin: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sin + """ + return FunctionExpression("sin", (value,)) + + @classmethod + def sqrt(cls, value: IntoExpression, /) -> Expression: + """ + Square root function. + + Same as JavaScript's `Math.sqrt`_. + + .. _Math.sqrt: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt + """ + return FunctionExpression("sqrt", (value,)) + + @classmethod + def tan(cls, value: IntoExpression, /) -> Expression: + """ + Trigonometric tangent. + + Same as JavaScript's `Math.tan`_. + + .. _Math.tan: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/tan + """ + return FunctionExpression("tan", (value,)) + + @classmethod + def sampleNormal( + cls, mean: IntoExpression = None, stdev: IntoExpression = None, / + ) -> Expression: + """ + Returns a sample from a univariate `normal (Gaussian) probability distribution`_ with specified ``mean`` and standard deviation ``stdev``. + + If unspecified, the mean defaults to ``0`` and the standard deviation defaults to ``1``. + + .. _normal (Gaussian) probability distribution: + https://en.wikipedia.org/wiki/Normal_distribution + """ + return FunctionExpression("sampleNormal", (mean, stdev)) + + @classmethod + def cumulativeNormal( + cls, + value: IntoExpression, + mean: IntoExpression = None, + stdev: IntoExpression = None, + /, + ) -> Expression: + """ + 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``. + + If unspecified, the mean defaults to ``0`` and the standard deviation defaults to ``1``. + + .. _cumulative distribution function: + https://en.wikipedia.org/wiki/Cumulative_distribution_function + """ + return FunctionExpression("cumulativeNormal", (value, mean, stdev)) + + @classmethod + def densityNormal( + cls, + value: IntoExpression, + mean: IntoExpression = None, + stdev: IntoExpression = None, + /, + ) -> Expression: + """ + 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``. + + If unspecified, the mean defaults to ``0`` and the standard deviation defaults to ``1``. + + .. _probability density function: + https://en.wikipedia.org/wiki/Probability_density_function + """ + return FunctionExpression("densityNormal", (value, mean, stdev)) + + @classmethod + def quantileNormal( + cls, + probability: IntoExpression, + mean: IntoExpression = None, + stdev: IntoExpression = None, + /, + ) -> Expression: + """ + 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``. + + If unspecified, the mean defaults to ``0`` and the standard deviation defaults to ``1``. + + .. _cumulative distribution function: + https://en.wikipedia.org/wiki/Cumulative_distribution_function + """ + return FunctionExpression("quantileNormal", (probability, mean, stdev)) + + @classmethod + def sampleLogNormal( + cls, mean: IntoExpression = None, stdev: IntoExpression = None, / + ) -> Expression: + """ + Returns a sample from a univariate `log-normal probability 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``. + + .. _log-normal probability distribution: + https://en.wikipedia.org/wiki/Log-normal_distribution + """ + return FunctionExpression("sampleLogNormal", (mean, stdev)) + + @classmethod + def cumulativeLogNormal( + cls, + value: IntoExpression, + mean: IntoExpression = None, + stdev: IntoExpression = None, + /, + ) -> Expression: + """ + 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``. + + If unspecified, the log mean defaults to ``0`` and the log standard deviation defaults to + ``1``. + + .. _cumulative distribution function: + https://en.wikipedia.org/wiki/Cumulative_distribution_function + """ + return FunctionExpression("cumulativeLogNormal", (value, mean, stdev)) + + @classmethod + def densityLogNormal( + cls, + value: IntoExpression, + mean: IntoExpression = None, + stdev: IntoExpression = None, + /, + ) -> Expression: + """ + 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``. + + If unspecified, the log mean defaults to ``0`` and the log standard deviation defaults to + ``1``. + + .. _probability density function: + https://en.wikipedia.org/wiki/Probability_density_function + """ + return FunctionExpression("densityLogNormal", (value, mean, stdev)) + + @classmethod + def quantileLogNormal( + cls, + probability: IntoExpression, + mean: IntoExpression = None, + stdev: IntoExpression = None, + /, + ) -> Expression: + """ + 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``. + + If unspecified, the log mean defaults to ``0`` and the log standard deviation defaults to + ``1``. + + .. _cumulative distribution function: + https://en.wikipedia.org/wiki/Cumulative_distribution_function + """ + return FunctionExpression("quantileLogNormal", (probability, mean, stdev)) + + @classmethod + def sampleUniform( + cls, min: IntoExpression = None, max: IntoExpression = None, / + ) -> Expression: + """ + Returns a sample from a univariate `continuous uniform probability 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. + + .. _continuous uniform probability distribution: + https://en.wikipedia.org/wiki/Continuous_uniform_distribution + """ + return FunctionExpression("sampleUniform", (min, max)) + + @classmethod + def cumulativeUniform( + cls, + value: IntoExpression, + min: IntoExpression = None, + max: IntoExpression = None, + /, + ) -> Expression: + """ + Returns the value of the `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. + + .. _cumulative distribution function: + https://en.wikipedia.org/wiki/Cumulative_distribution_function + """ + return FunctionExpression("cumulativeUniform", (value, min, max)) + + @classmethod + def densityUniform( + cls, + value: IntoExpression, + min: IntoExpression = None, + max: IntoExpression = None, + /, + ) -> Expression: + """ + Returns the value of the `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. + + .. _probability density function: + https://en.wikipedia.org/wiki/Probability_density_function + """ + return FunctionExpression("densityUniform", (value, min, max)) + + @classmethod + def quantileUniform( + cls, + probability: IntoExpression, + min: IntoExpression = None, + max: IntoExpression = None, + /, + ) -> Expression: + """ + 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``). + + If unspecified, ``min`` defaults to ``0`` and ``max`` defaults to ``1``. If only one + argument is provided, it is interpreted as the ``max`` value. + + .. _cumulative distribution function: + https://en.wikipedia.org/wiki/Cumulative_distribution_function + """ + return FunctionExpression("quantileUniform", (probability, min, max)) + + @classmethod + def now(cls) -> Expression: + """Returns the timestamp for the current time.""" + return FunctionExpression("now", ()) + + @classmethod + def datetime( + cls, + year: IntoExpression, + month: IntoExpression, + day: IntoExpression = None, + hour: IntoExpression = None, + min: IntoExpression = None, + sec: IntoExpression = None, + millisec: IntoExpression = None, + /, + ) -> Expression: + """ + Returns a new ``Date`` instance. + + The ``month`` is 0-based, such that ``1`` represents February. + """ + return FunctionExpression( + "datetime", (year, month, day, hour, min, sec, millisec) + ) + + @classmethod + def date(cls, datetime: IntoExpression, /) -> Expression: + """Returns the day of the month for the given ``datetime`` value, in local time.""" + return FunctionExpression("date", (datetime,)) + + @classmethod + def day(cls, datetime: IntoExpression, /) -> Expression: + """Returns the day of the week for the given ``datetime`` value, in local time.""" + return FunctionExpression("day", (datetime,)) + + @classmethod + def dayofyear(cls, datetime: IntoExpression, /) -> Expression: + """Returns the one-based day of the year for the given ``datetime`` value, in local time.""" + return FunctionExpression("dayofyear", (datetime,)) + + @classmethod + def year(cls, datetime: IntoExpression, /) -> Expression: + """Returns the year for the given ``datetime`` value, in local time.""" + return FunctionExpression("year", (datetime,)) + + @classmethod + def quarter(cls, datetime: IntoExpression, /) -> Expression: + """Returns the quarter of the year (0-3) for the given ``datetime`` value, in local time.""" + return FunctionExpression("quarter", (datetime,)) + + @classmethod + def month(cls, datetime: IntoExpression, /) -> Expression: + """Returns the (zero-based) month for the given ``datetime`` value, in local time.""" + return FunctionExpression("month", (datetime,)) + + @classmethod + def week(cls, date: IntoExpression, /) -> Expression: + """ + 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.*. + """ + return FunctionExpression("week", (date,)) + + @classmethod + def hours(cls, datetime: IntoExpression, /) -> Expression: + """Returns the hours component for the given ``datetime`` value, in local time.""" + return FunctionExpression("hours", (datetime,)) + + @classmethod + def minutes(cls, datetime: IntoExpression, /) -> Expression: + """Returns the minutes component for the given ``datetime`` value, in local time.""" + return FunctionExpression("minutes", (datetime,)) + + @classmethod + def seconds(cls, datetime: IntoExpression, /) -> Expression: + """Returns the seconds component for the given ``datetime`` value, in local time.""" + return FunctionExpression("seconds", (datetime,)) + + @classmethod + def milliseconds(cls, datetime: IntoExpression, /) -> Expression: + """Returns the milliseconds component for the given ``datetime`` value, in local time.""" + return FunctionExpression("milliseconds", (datetime,)) + + @classmethod + def time(cls, datetime: IntoExpression, /) -> Expression: + """Returns the epoch-based timestamp for the given ``datetime`` value.""" + return FunctionExpression("time", (datetime,)) + + @classmethod + def timezoneoffset(cls, datetime: IntoExpression, /) -> Expression: + """Returns the timezone offset from the local timezone to UTC for the given ``datetime`` value.""" + return FunctionExpression("timezoneoffset", (datetime,)) + + @classmethod + def timeOffset( + cls, unit: IntoExpression, date: IntoExpression, step: IntoExpression = None, / + ) -> Expression: + """ + Returns a new ``Date`` instance that offsets the given ``date`` by the specified time `*unit*`_ in the local timezone. + + The optional ``step`` argument indicates the number of time unit steps to offset by (default + 1). + + .. _*unit*: + https://vega.github.io/vega/docs/api/time/#time-units + """ + return FunctionExpression("timeOffset", (unit, date, step)) + + @classmethod + def timeSequence( + cls, + unit: IntoExpression, + start: IntoExpression, + stop: IntoExpression, + step: IntoExpression = None, + /, + ) -> Expression: + """ + 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. + + The optional ``step`` argument indicates the number of time unit steps to take between each + sequence entry (default 1). + + .. _*unit*: + https://vega.github.io/vega/docs/api/time/#time-units + """ + return FunctionExpression("timeSequence", (unit, start, stop, step)) + + @classmethod + def utc( + cls, + year: IntoExpression, + month: IntoExpression, + day: IntoExpression = None, + hour: IntoExpression = None, + min: IntoExpression = None, + sec: IntoExpression = None, + millisec: IntoExpression = None, + /, + ) -> Expression: + """ + Returns a timestamp for the given UTC date. + + The ``month`` is 0-based, such that ``1`` represents February. + """ + return FunctionExpression("utc", (year, month, day, hour, min, sec, millisec)) + + @classmethod + def utcdate(cls, datetime: IntoExpression, /) -> Expression: + """Returns the day of the month for the given ``datetime`` value, in UTC time.""" + return FunctionExpression("utcdate", (datetime,)) + + @classmethod + def utcday(cls, datetime: IntoExpression, /) -> Expression: + """Returns the day of the week for the given ``datetime`` value, in UTC time.""" + return FunctionExpression("utcday", (datetime,)) + + @classmethod + def utcdayofyear(cls, datetime: IntoExpression, /) -> Expression: + """Returns the one-based day of the year for the given ``datetime`` value, in UTC time.""" + return FunctionExpression("utcdayofyear", (datetime,)) + + @classmethod + def utcyear(cls, datetime: IntoExpression, /) -> Expression: + """Returns the year for the given ``datetime`` value, in UTC time.""" + return FunctionExpression("utcyear", (datetime,)) + + @classmethod + def utcquarter(cls, datetime: IntoExpression, /) -> Expression: + """Returns the quarter of the year (0-3) for the given ``datetime`` value, in UTC time.""" + return FunctionExpression("utcquarter", (datetime,)) + + @classmethod + def utcmonth(cls, datetime: IntoExpression, /) -> Expression: + """Returns the (zero-based) month for the given ``datetime`` value, in UTC time.""" + return FunctionExpression("utcmonth", (datetime,)) + + @classmethod + def utcweek(cls, date: IntoExpression, /) -> Expression: + """ + 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.*. + """ + return FunctionExpression("utcweek", (date,)) + + @classmethod + def utchours(cls, datetime: IntoExpression, /) -> Expression: + """Returns the hours component for the given ``datetime`` value, in UTC time.""" + return FunctionExpression("utchours", (datetime,)) + + @classmethod + def utcminutes(cls, datetime: IntoExpression, /) -> Expression: + """Returns the minutes component for the given ``datetime`` value, in UTC time.""" + return FunctionExpression("utcminutes", (datetime,)) + + @classmethod + def utcseconds(cls, datetime: IntoExpression, /) -> Expression: + """Returns the seconds component for the given ``datetime`` value, in UTC time.""" + return FunctionExpression("utcseconds", (datetime,)) + + @classmethod + def utcmilliseconds(cls, datetime: IntoExpression, /) -> Expression: + """Returns the milliseconds component for the given ``datetime`` value, in UTC time.""" + return FunctionExpression("utcmilliseconds", (datetime,)) + + @classmethod + def utcOffset( + cls, unit: IntoExpression, date: IntoExpression, step: IntoExpression = None, / + ) -> Expression: + """ + Returns a new ``Date`` instance that offsets the given ``date`` by the specified time `*unit*`_ in UTC time. + + The optional ``step`` argument indicates the number of time unit steps to offset by (default + 1). + + .. _*unit*: + https://vega.github.io/vega/docs/api/time/#time-units + """ + return FunctionExpression("utcOffset", (unit, date, step)) + + @classmethod + def utcSequence( + cls, + unit: IntoExpression, + start: IntoExpression, + stop: IntoExpression, + step: IntoExpression = None, + /, + ) -> Expression: + """ + Returns an array of ``Date`` instances from ``start`` (inclusive) to ``stop`` (exclusive), with each entry separated by the given time `*unit*`_ in UTC time. + + The optional ``step`` argument indicates the number of time unit steps to take between each + sequence entry (default 1). + + .. _*unit*: + https://vega.github.io/vega/docs/api/time/#time-units + """ + return FunctionExpression("utcSequence", (unit, start, stop, step)) + + @classmethod + def extent(cls, array: IntoExpression, /) -> Expression: + """Returns a new *[min, max]* array with the minimum and maximum values of the input array, ignoring ``null``, ``undefined``, and ``NaN`` values.""" + return FunctionExpression("extent", (array,)) + + @classmethod + def clampRange( + cls, range: IntoExpression, min: IntoExpression, max: IntoExpression, / + ) -> Expression: + """ + 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. + """ + return FunctionExpression("clampRange", (range, min, max)) + + @classmethod + def indexof(cls, array: IntoExpression, value: IntoExpression, /) -> Expression: + """Returns the first index of ``value`` in the input ``array``.""" + return FunctionExpression("indexof", (array, value)) + + @classmethod + def inrange(cls, value: IntoExpression, range: IntoExpression, /) -> Expression: + """Tests whether ``value`` lies within (or is equal to either) the first and last values of the ``range`` array.""" + return FunctionExpression("inrange", (value, range)) + + @classmethod + def join( + cls, array: IntoExpression, separator: IntoExpression = None, / + ) -> Expression: + """Returns a new string by concatenating all of the elements of the input ``array``, separated by commas or a specified ``separator`` string.""" + return FunctionExpression("join", (array, separator)) + + @classmethod + def lastindexof(cls, array: IntoExpression, value: IntoExpression, /) -> Expression: + """Returns the last index of ``value`` in the input ``array``.""" + return FunctionExpression("lastindexof", (array, value)) + + @classmethod + def length(cls, array: IntoExpression, /) -> Expression: + """Returns the length of the input ``array``.""" + return FunctionExpression("length", (array,)) + + @classmethod + def lerp(cls, array: IntoExpression, fraction: IntoExpression, /) -> Expression: + """ + 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, ``alt.expr.lerp([0, 50], 0.5)`` returns 25. + """ + return FunctionExpression("lerp", (array, fraction)) + + @classmethod + def peek(cls, array: IntoExpression, /) -> Expression: + """ + 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]``. + """ + return FunctionExpression("peek", (array,)) + + @classmethod + def pluck(cls, array: IntoExpression, field: IntoExpression, /) -> Expression: + """ + 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``). + """ + return FunctionExpression("pluck", (array, field)) + + @classmethod + def reverse(cls, array: IntoExpression, /) -> Expression: + """ + 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. + """ + return FunctionExpression("reverse", (array,)) + + @classmethod + def sequence(cls, *args: Any) -> Expression: + """ + 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. + """ + return FunctionExpression("sequence", args) + + @classmethod + def slice( + cls, array: IntoExpression, start: IntoExpression, end: IntoExpression = None, / + ) -> Expression: + """ + 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 + (*alt.expr.length(array) + end*). + """ + return FunctionExpression("slice", (array, start, end)) + + @classmethod + def sort(cls, array: IntoExpression, /) -> Expression: + """ + Sorts the array in natural order using `ascending from Vega Utils`_. + + .. _ascending from Vega Utils: + https://vega.github.io/vega/docs/api/util/#ascending + """ + return FunctionExpression("sort", (array,)) + + @classmethod + def span(cls, array: IntoExpression, /) -> Expression: + """Returns the span of ``array``: the difference between the last and first elements, or *array[array.length-1] - array[0]*.""" + return FunctionExpression("span", (array,)) + + @classmethod + def lower(cls, string: IntoExpression, /) -> Expression: + """Transforms ``string`` to lower-case letters.""" + return FunctionExpression("lower", (string,)) + + @classmethod + def pad( + cls, + string: IntoExpression, + length: IntoExpression, + character: IntoExpression = None, + align: IntoExpression = None, + /, + ) -> Expression: + """ + 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. + """ + return FunctionExpression("pad", (string, length, character, align)) + + @classmethod + def parseFloat(cls, string: IntoExpression, /) -> Expression: + """ + Parses the input ``string`` to a floating-point value. + + Same as JavaScript's ``parseFloat``. + """ + return FunctionExpression("parseFloat", (string,)) + + @classmethod + def parseInt(cls, string: IntoExpression, /) -> Expression: + """ + Parses the input ``string`` to an integer value. + + Same as JavaScript's ``parseInt``. + """ + return FunctionExpression("parseInt", (string,)) + + @classmethod + def replace( + cls, + string: IntoExpression, + pattern: IntoExpression, + replacement: IntoExpression, + /, + ) -> Expression: + """ + 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`_. + + .. _JavaScript's String.replace: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace + """ + return FunctionExpression("replace", (string, pattern, replacement)) + + @classmethod + def substring( + cls, + string: IntoExpression, + start: IntoExpression, + end: IntoExpression = None, + /, + ) -> Expression: + """Returns a section of ``string`` between the ``start`` and ``end`` indices.""" + return FunctionExpression("substring", (string, start, end)) + + @classmethod + def trim(cls, string: IntoExpression, /) -> Expression: + """Returns a trimmed string with preceding and trailing whitespace removed.""" + return FunctionExpression("trim", (string,)) + + @classmethod + def truncate( + cls, + string: IntoExpression, + length: IntoExpression, + align: IntoExpression = None, + ellipsis: IntoExpression = None, + /, + ) -> Expression: + """ + 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. + """ + return FunctionExpression("truncate", (string, length, align, ellipsis)) + + @classmethod + def upper(cls, string: IntoExpression, /) -> Expression: + """Transforms ``string`` to upper-case letters.""" + return FunctionExpression("upper", (string,)) + + @classmethod + def btoa(cls, string: IntoExpression, /) -> Expression: + """ + Creates a `Base64`_-encoded `ASCII`_ string. + + Same as JavaScript's `Window.alt.expr.btoa()`_. + + .. _Base64: + https://developer.mozilla.org/en-US/docs/Glossary/Base64 + .. _ASCII: + https://developer.mozilla.org/en-US/docs/Glossary/ASCII + .. _Window.alt.expr.btoa(): + https://developer.mozilla.org/en-US/docs/Web/API/Window/btoa + """ + return FunctionExpression("btoa", (string,)) + + @classmethod + def atob(cls, string: IntoExpression, /) -> Expression: + """ + Decodes an `ASCII`_ string that was encoded with `Base64`_. + + Same as JavaScript's `Window.alt.expr.atob()`_. + + .. _ASCII: + https://developer.mozilla.org/en-US/docs/Glossary/ASCII + .. _Base64: + https://developer.mozilla.org/en-US/docs/Glossary/Base64 + .. _Window.alt.expr.atob(): + https://developer.mozilla.org/en-US/docs/Web/API/Window/atob + """ + return FunctionExpression("atob", (string,)) + + @classmethod + def merge( + cls, object1: IntoExpression, object2: IntoExpression = None, *args: Any + ) -> Expression: + """ + 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: ``alt.expr.merge({a:1, b:2}, {a:3}) -> + {a:3, b:2}``. + """ + return FunctionExpression("merge", (object1, object2, *args)) + + @classmethod + def dayFormat(cls, day: IntoExpression, /) -> Expression: + """ + Formats a (0-6) *weekday* number as a full week day name, according to the current locale. + + For example: ``alt.expr.dayFormat(0) -> "Sunday"``. + """ + return FunctionExpression("dayFormat", (day,)) + + @classmethod + def dayAbbrevFormat(cls, day: IntoExpression, /) -> Expression: + """ + Formats a (0-6) *weekday* number as an abbreviated week day name, according to the current locale. + + For example: ``alt.expr.dayAbbrevFormat(0) -> "Sun"``. + """ + return FunctionExpression("dayAbbrevFormat", (day,)) + + @classmethod + def format(cls, value: IntoExpression, specifier: IntoExpression, /) -> Expression: + """ + Formats a numeric ``value`` as a string. + + The ``specifier`` must be a valid `d3-format specifier`_ (e.g., ``alt.expr.format(value, + ',.2f')``. Null values are formatted as ``"null"``. + + .. _d3-format specifier: + https://github.com/d3/d3-format/ + """ + return FunctionExpression("format", (value, specifier)) + + @classmethod + def monthFormat(cls, month: IntoExpression, /) -> Expression: + """ + Formats a (zero-based) ``month`` number as a full month name, according to the current locale. + + For example: ``alt.expr.monthFormat(0) -> "January"``. + """ + return FunctionExpression("monthFormat", (month,)) + + @classmethod + def monthAbbrevFormat(cls, month: IntoExpression, /) -> Expression: + """ + Formats a (zero-based) ``month`` number as an abbreviated month name, according to the current locale. + + For example: ``alt.expr.monthAbbrevFormat(0) -> "Jan"``. + """ + return FunctionExpression("monthAbbrevFormat", (month,)) + + @classmethod + def timeUnitSpecifier( + cls, units: IntoExpression, specifiers: IntoExpression = None, / + ) -> Expression: + """ + Returns a time format specifier string for the given time `*units*`_. + + The optional ``specifiers`` object provides a set of specifier sub-strings for customizing + the format; for more, see the `timeUnitSpecifier API documentation`_. The resulting + specifier string can then be used as input to the `timeFormat`_ or `utcFormat`_ functions, + or as the *format* parameter of an axis or legend. For example: ``alt.expr.timeFormat(date, + alt.expr.timeUnitSpecifier('year'))`` or ``alt.expr.timeFormat(date, + alt.expr.timeUnitSpecifier(['hours', 'minutes']))``. + + .. _*units*: + https://vega.github.io/vega/docs/api/time/#time-units + .. _timeUnitSpecifier API documentation: + https://vega.github.io/vega/docs/api/time/#timeUnitSpecifier + .. _timeFormat: + https://vega.github.io/vega/docs/expressions/#timeFormat + .. _utcFormat: + https://vega.github.io/vega/docs/expressions/#utcFormat + """ + return FunctionExpression("timeUnitSpecifier", (units, specifiers)) + + @classmethod + def timeFormat( + cls, value: IntoExpression, specifier: IntoExpression, / + ) -> Expression: + """ + 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`_ or `TimeMultiFormat object`_. + For example: ``alt.expr.timeFormat(timestamp, '%A')``. Null values are formatted as + ``"null"``. + + .. _d3-time-format specifier: + https://github.com/d3/d3-time-format/ + .. _TimeMultiFormat object: + https://vega.github.io/vega/docs/types/#TimeMultiFormat + """ + return FunctionExpression("timeFormat", (value, specifier)) + + @classmethod + def timeParse( + cls, string: IntoExpression, specifier: IntoExpression, / + ) -> Expression: + """ + Parses a ``string`` value to a Date object, according to the local time. + + The ``specifier`` must be a valid `d3-time-format specifier`_. For example: + ``alt.expr.timeParse('June 30, 2015', '%B %d, %Y')``. + + .. _d3-time-format specifier: + https://github.com/d3/d3-time-format/ + """ + return FunctionExpression("timeParse", (string, specifier)) + + @classmethod + def utcFormat( + cls, value: IntoExpression, specifier: IntoExpression, / + ) -> Expression: + """ + Formats a datetime ``value`` (either a ``Date`` object or timestamp) as a string, according to `UTC`_ time. + + The ``specifier`` must be a valid `d3-time-format specifier`_ or `TimeMultiFormat object`_. + For example: ``alt.expr.utcFormat(timestamp, '%A')``. Null values are formatted as + ``"null"``. + + .. _UTC: + https://en.wikipedia.org/wiki/Coordinated_Universal_Time + .. _d3-time-format specifier: + https://github.com/d3/d3-time-format/ + .. _TimeMultiFormat object: + https://vega.github.io/vega/docs/types/#TimeMultiFormat + """ + return FunctionExpression("utcFormat", (value, specifier)) + + @classmethod + def utcParse( + cls, value: IntoExpression, specifier: IntoExpression, / + ) -> Expression: + """ + Parses a *string* value to a Date object, according to `UTC`_ time. + + The ``specifier`` must be a valid `d3-time-format specifier`_. For example: + ``alt.expr.utcParse('June 30, 2015', '%B %d, %Y')``. + + .. _UTC: + https://en.wikipedia.org/wiki/Coordinated_Universal_Time + .. _d3-time-format specifier: + https://github.com/d3/d3-time-format/ + """ + return FunctionExpression("utcParse", (value, specifier)) + + @classmethod + def regexp( + cls, pattern: IntoExpression, flags: IntoExpression = None, / + ) -> Expression: + """ + Creates a regular expression instance from an input ``pattern`` string and optional ``flags``. + + Same as `JavaScript's RegExp`_. + + .. _JavaScript's RegExp: + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp + """ + return FunctionExpression("regexp", (pattern, flags)) + + @classmethod + def test( + cls, regexp: IntoExpression, string: IntoExpression = None, / + ) -> Expression: + r""" + Evaluates a regular expression ``regexp`` against the input ``string``, returning ``true`` if the string matches the pattern, ``false`` otherwise. + + For example: ``alt.expr.test(/\\d{3}/, "32-21-9483") -> true``. + """ + return FunctionExpression("test", (regexp, string)) + + @classmethod + def rgb(cls, *args: Any) -> Expression: + """ + Constructs a new `RGB`_ 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`_. + + .. _RGB: + https://en.wikipedia.org/wiki/RGB_color_model + .. _d3-color's rgb function: + https://github.com/d3/d3-color#rgb + """ + return FunctionExpression("rgb", args) + + @classmethod + def hsl(cls, *args: Any) -> Expression: + """ + Constructs a new `HSL`_ 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`_. + + .. _HSL: + https://en.wikipedia.org/wiki/HSL_and_HSV + .. _d3-color's hsl function: + https://github.com/d3/d3-color#hsl + """ + return FunctionExpression("hsl", args) + + @classmethod + def lab(cls, *args: Any) -> Expression: + """ + Constructs a new `CIE LAB`_ 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`_. + + .. _CIE LAB: + https://en.wikipedia.org/wiki/Lab_color_space#CIELAB + .. _d3-color's lab function: + https://github.com/d3/d3-color#lab + """ + return FunctionExpression("lab", args) + + @classmethod + def hcl(cls, *args: Any) -> Expression: + """ + Constructs a new `HCL`_ (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`_. + + .. _HCL: + https://en.wikipedia.org/wiki/Lab_color_space#CIELAB + .. _d3-color's hcl function: + https://github.com/d3/d3-color#hcl + """ + return FunctionExpression("hcl", args) + + @classmethod + def luminance(cls, specifier: IntoExpression, /) -> Expression: + """ + Returns the luminance for the given color ``specifier`` (compatible with `d3-color's rgb function`_). + + The luminance is calculated according to the `W3C Web Content Accessibility Guidelines`_. + + .. _d3-color's rgb function: + https://github.com/d3/d3-color#rgb + .. _W3C Web Content Accessibility Guidelines: + https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef + """ + return FunctionExpression("luminance", (specifier,)) + + @classmethod + def contrast( + cls, specifier1: IntoExpression, specifier2: IntoExpression, / + ) -> Expression: + """ + 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`_. + + .. _W3C Web Content Accessibility Guidelines: + https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef + """ + return FunctionExpression("contrast", (specifier1, specifier2)) + + @classmethod + def item(cls) -> Expression: + """Returns the current scenegraph item that is the target of the event.""" + return FunctionExpression("item", ()) + + @classmethod + def group(cls, name: IntoExpression = None, /) -> Expression: + """ + 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. + """ + return FunctionExpression("group", (name,)) + + @classmethod + def xy(cls, item: IntoExpression = None, /) -> Expression: + """ + 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. + """ + return FunctionExpression("xy", (item,)) + + @classmethod + def x(cls, item: IntoExpression = None, /) -> Expression: + """ + 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. + """ + return FunctionExpression("x", (item,)) + + @classmethod + def y(cls, item: IntoExpression = None, /) -> Expression: + """ + 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. + """ + return FunctionExpression("y", (item,)) + + @classmethod + def pinchDistance(cls, event: IntoExpression, /) -> Expression: + """Returns the pixel distance between the first two touch points of a multi-touch event.""" + return FunctionExpression("pinchDistance", (event,)) + + @classmethod + def pinchAngle(cls, event: IntoExpression, /) -> Expression: + """Returns the angle of the line connecting the first two touch points of a multi-touch event.""" + return FunctionExpression("pinchAngle", (event,)) + + @classmethod + def inScope(cls, item: IntoExpression, /) -> Expression: + """Returns true if the given scenegraph ``item`` is a descendant of the group mark in which the event handler was defined, false otherwise.""" + return FunctionExpression("inScope", (item,)) + + @classmethod + def data(cls, name: IntoExpression, /) -> Expression: + """ + 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. + """ + return FunctionExpression("data", (name,)) + + @classmethod + def indata( + cls, name: IntoExpression, field: IntoExpression, value: IntoExpression, / + ) -> Expression: + """ + Tests if the data set with a given ``name`` contains a datum with a ``field`` value that matches the input ``value``. + + For example: ``alt.expr.indata('table', 'category', value)``. + """ + return FunctionExpression("indata", (name, field, value)) + + @classmethod + def scale( + cls, + name: IntoExpression, + value: IntoExpression, + group: IntoExpression = None, + /, + ) -> Expression: + """ + 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. + """ + return FunctionExpression("scale", (name, value, group)) + + @classmethod + def invert( + cls, + name: IntoExpression, + value: IntoExpression, + group: IntoExpression = None, + /, + ) -> Expression: + """ + 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. + """ + return FunctionExpression("invert", (name, value, group)) + + @classmethod + def copy(cls, name: IntoExpression, group: IntoExpression = None, /) -> Expression: # type: ignore[override] + """ + 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. + """ + return FunctionExpression("copy", (name, group)) + + @classmethod + def domain( + cls, name: IntoExpression, group: IntoExpression = None, / + ) -> Expression: + """ + 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. + """ + return FunctionExpression("domain", (name, group)) + + @classmethod + def range(cls, name: IntoExpression, group: IntoExpression = None, /) -> Expression: + """ + 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. + """ + return FunctionExpression("range", (name, group)) + + @classmethod + def bandwidth( + cls, name: IntoExpression, group: IntoExpression = None, / + ) -> Expression: + """ + 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. + """ + return FunctionExpression("bandwidth", (name, group)) + + @classmethod + def bandspace( + cls, + count: IntoExpression, + paddingInner: IntoExpression = None, + paddingOuter: IntoExpression = None, + /, + ) -> Expression: + """ + 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. + """ + return FunctionExpression("bandspace", (count, paddingInner, paddingOuter)) + + @classmethod + def gradient( + cls, + scale: IntoExpression, + p0: IntoExpression, + p1: IntoExpression, + count: IntoExpression = None, + /, + ) -> Expression: + """ + 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. + + 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. + + .. _continuous color scheme: + https://vega.github.io/vega/docs/schemes + """ + return FunctionExpression("gradient", (scale, p0, p1, count)) + + @classmethod + def panLinear(cls, domain: IntoExpression, delta: IntoExpression, /) -> Expression: + """ + 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. + """ + return FunctionExpression("panLinear", (domain, delta)) + + @classmethod + def panLog(cls, domain: IntoExpression, delta: IntoExpression, /) -> Expression: + """ + 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. + """ + return FunctionExpression("panLog", (domain, delta)) + + @classmethod + def panPow( + cls, domain: IntoExpression, delta: IntoExpression, exponent: IntoExpression, / + ) -> Expression: + """ + 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. + """ + return FunctionExpression("panPow", (domain, delta, exponent)) + + @classmethod + def panSymlog( + cls, domain: IntoExpression, delta: IntoExpression, constant: IntoExpression, / + ) -> Expression: + """ + 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. + """ + return FunctionExpression("panSymlog", (domain, delta, constant)) + + @classmethod + def zoomLinear( + cls, + domain: IntoExpression, + anchor: IntoExpression, + scaleFactor: IntoExpression, + /, + ) -> Expression: + """ + 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. + """ + return FunctionExpression("zoomLinear", (domain, anchor, scaleFactor)) + + @classmethod + def zoomLog( + cls, + domain: IntoExpression, + anchor: IntoExpression, + scaleFactor: IntoExpression, + /, + ) -> Expression: + """ + 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. + """ + return FunctionExpression("zoomLog", (domain, anchor, scaleFactor)) + + @classmethod + def zoomPow( + cls, + domain: IntoExpression, + anchor: IntoExpression, + scaleFactor: IntoExpression, + exponent: IntoExpression, + /, + ) -> Expression: + """ + 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. + """ + return FunctionExpression("zoomPow", (domain, anchor, scaleFactor, exponent)) + + @classmethod + def zoomSymlog( + cls, + domain: IntoExpression, + anchor: IntoExpression, + scaleFactor: IntoExpression, + constant: IntoExpression, + /, + ) -> Expression: + """ + 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. + """ + return FunctionExpression("zoomSymlog", (domain, anchor, scaleFactor, constant)) + + @classmethod + def geoArea( + cls, + projection: IntoExpression, + feature: IntoExpression, + group: IntoExpression = None, + /, + ) -> Expression: + """ + 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`_ and `path.area`_ methods. + + .. _geoArea: + https://github.com/d3/d3-geo#geoArea + .. _path.area: + https://github.com/d3/d3-geo#path_area + """ + return FunctionExpression("geoArea", (projection, feature, group)) + + @classmethod + def geoBounds( + cls, + projection: IntoExpression, + feature: IntoExpression, + group: IntoExpression = None, + /, + ) -> Expression: + """ + 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: [[*x₀*, *y₀*], [*x₁*, *y₁*]], + where *x₀* is the minimum x-coordinate, *y₀* is the minimum y-coordinate, *x₁* is the + maximum x-coordinate, and *y₁* 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`_ and + `path.bounds`_ methods. + + .. _geoBounds: + https://github.com/d3/d3-geo#geoBounds + .. _path.bounds: + https://github.com/d3/d3-geo#path_bounds + """ + return FunctionExpression("geoBounds", (projection, feature, group)) + + @classmethod + def geoCentroid( + cls, + projection: IntoExpression, + feature: IntoExpression, + group: IntoExpression = None, + /, + ) -> Expression: + """ + 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`_ and `path.centroid`_ methods. + + .. _geoCentroid: + https://github.com/d3/d3-geo#geoCentroid + .. _path.centroid: + https://github.com/d3/d3-geo#path_centroid + """ + return FunctionExpression("geoCentroid", (projection, feature, group)) + + @classmethod + def geoScale( + cls, projection: IntoExpression, group: IntoExpression = None, / + ) -> Expression: + """ + Returns the scale value for the named ``projection``. + + The optional ``group`` argument takes a scenegraph group mark item to indicate the specific + scope in which to look up the projection. + """ + return FunctionExpression("geoScale", (projection, group)) + + @classmethod + def treePath( + cls, name: IntoExpression, source: IntoExpression, target: IntoExpression, / + ) -> Expression: + """ + 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. + """ + return FunctionExpression("treePath", (name, source, target)) + + @classmethod + def treeAncestors(cls, name: IntoExpression, node: IntoExpression, /) -> Expression: + """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.""" + return FunctionExpression("treeAncestors", (name, node)) + + @classmethod + def containerSize(cls) -> Expression: + """ + 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]``. + """ + return FunctionExpression("containerSize", ()) + + @classmethod + def screen(cls) -> Expression: + """ + Returns the `window.screen`_ object, or ``{}`` if Vega is not running in a browser environment. + + .. _window.screen: + https://developer.mozilla.org/en-US/docs/Web/API/Window/screen + """ + return FunctionExpression("screen", ()) + + @classmethod + def windowSize(cls) -> Expression: + """Returns the current window size (``[window.innerWidth, window.innerHeight]``) or ``[undefined, undefined]`` if Vega is not running in a browser environment.""" + return FunctionExpression("windowSize", ()) + + @classmethod + def warn( + cls, value1: IntoExpression, value2: IntoExpression = None, *args: Any + ) -> Expression: + """ + 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. + """ + return FunctionExpression("warn", (value1, value2, *args)) + + @classmethod + def info( + cls, value1: IntoExpression, value2: IntoExpression = None, *args: Any + ) -> Expression: + """ + 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. + """ + return FunctionExpression("info", (value1, value2, *args)) + + @classmethod + def debug( + cls, value1: IntoExpression, value2: IntoExpression = None, *args: Any + ) -> Expression: + """ + 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. + """ + return FunctionExpression("debug", (value1, value2, *args)) + + +_ExprType = expr +# NOTE: Compatibility alias for previous type of `alt.expr`. +# `_ExprType` was not referenced in any internal imports/tests. diff --git a/.venv/lib/python3.13/site-packages/altair/expr/consts.py b/.venv/lib/python3.13/site-packages/altair/expr/consts.py new file mode 100644 index 0000000000000000000000000000000000000000..8cb4a57c432ce2d8612a82af4a4166b210b8efdb --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/expr/consts.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +CONST_LISTING = { + "NaN": "not a number (same as JavaScript literal NaN)", + "LN10": "the natural log of 10 (alias to Math.LN10)", + "E": "the transcendental number e (alias to Math.E)", + "LOG10E": "the base 10 logarithm e (alias to Math.LOG10E)", + "LOG2E": "the base 2 logarithm of e (alias to Math.LOG2E)", + "SQRT1_2": "the square root of 0.5 (alias to Math.SQRT1_2)", + "LN2": "the natural log of 2 (alias to Math.LN2)", + "SQRT2": "the square root of 2 (alias to Math.SQRT1_2)", + "PI": "the transcendental number pi (alias to Math.PI)", +} diff --git a/.venv/lib/python3.13/site-packages/altair/expr/core.py b/.venv/lib/python3.13/site-packages/altair/expr/core.py new file mode 100644 index 0000000000000000000000000000000000000000..13ca921f13c3af2636dad93499f92a5626b74393 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/expr/core.py @@ -0,0 +1,292 @@ +from __future__ import annotations + +import datetime as dt +import sys +from typing import TYPE_CHECKING, Any, Literal, Union + +from altair.utils import SchemaBase + +if TYPE_CHECKING: + from altair.vegalite.v6.schema._typing import Map, PrimitiveValue_T + + if sys.version_info >= (3, 10): + from typing import TypeAlias + else: + from typing_extensions import TypeAlias + + +class DatumType: + """An object to assist in building Vega-Lite Expressions.""" + + def __repr__(self) -> str: + return "datum" + + def __getattr__(self, attr) -> GetAttrExpression: + if attr.startswith("__") and attr.endswith("__"): + raise AttributeError(attr) + return GetAttrExpression("datum", attr) + + def __getitem__(self, attr) -> GetItemExpression: + return GetItemExpression("datum", attr) + + def __call__(self, datum, **kwargs) -> dict[str, Any]: + """Specify a datum for use in an encoding.""" + return dict(datum=datum, **kwargs) + + +datum = DatumType() + + +def _js_repr(val) -> str: + """Return a javascript-safe string representation of val.""" + if val is True: + return "true" + elif val is False: + return "false" + elif val is None: + return "null" + elif isinstance(val, OperatorMixin): + return val._to_expr() + elif isinstance(val, dt.date): + return _from_date_datetime(val) + elif _is_numpy_generic(val): + return repr(val.item()) + else: + return repr(val) + + +def _from_date_datetime(obj: dt.date | dt.datetime, /) -> str: + """ + Parse native `datetime.(date|datetime)` into a `datetime expression`_ string. + + **Month is 0-based** + + .. _datetime expression: + https://vega.github.io/vega/docs/expressions/#datetime + """ + fn_name: Literal["datetime", "utc"] = "datetime" + args: tuple[int, ...] = obj.year, obj.month - 1, obj.day + if isinstance(obj, dt.datetime): + if tzinfo := obj.tzinfo: + if tzinfo is dt.timezone.utc: + fn_name = "utc" + else: + msg = ( + f"Unsupported timezone {tzinfo!r}.\n" + "Only `'UTC'` or naive (local) datetimes are permitted.\n" + "See https://altair-viz.github.io/user_guide/generated/core/altair.DateTime.html" + ) + raise TypeError(msg) + us = obj.microsecond + ms = us if us == 0 else us // 1_000 + args = *args, obj.hour, obj.minute, obj.second, ms + return FunctionExpression(fn_name, args)._to_expr() + + +def _is_numpy_generic(obj: Any) -> bool: + """ + Check if an object is a numpy generic (scalar) type. + + This function can be used without importing numpy when it is not available. + """ + return (np := sys.modules.get("numpy")) is not None and isinstance(obj, np.generic) + + +# Designed to work with Expression and VariableParameter +class OperatorMixin: + def _to_expr(self) -> str: + return repr(self) + + def _from_expr(self, expr) -> Any: + return expr + + def __add__(self, other): + comp_value = BinaryExpression("+", self, other) + return self._from_expr(comp_value) + + def __radd__(self, other): + comp_value = BinaryExpression("+", other, self) + return self._from_expr(comp_value) + + def __sub__(self, other): + comp_value = BinaryExpression("-", self, other) + return self._from_expr(comp_value) + + def __rsub__(self, other): + comp_value = BinaryExpression("-", other, self) + return self._from_expr(comp_value) + + def __mul__(self, other): + comp_value = BinaryExpression("*", self, other) + return self._from_expr(comp_value) + + def __rmul__(self, other): + comp_value = BinaryExpression("*", other, self) + return self._from_expr(comp_value) + + def __truediv__(self, other): + comp_value = BinaryExpression("/", self, other) + return self._from_expr(comp_value) + + def __rtruediv__(self, other): + comp_value = BinaryExpression("/", other, self) + return self._from_expr(comp_value) + + __div__ = __truediv__ + + __rdiv__ = __rtruediv__ + + def __mod__(self, other): + comp_value = BinaryExpression("%", self, other) + return self._from_expr(comp_value) + + def __rmod__(self, other): + comp_value = BinaryExpression("%", other, self) + return self._from_expr(comp_value) + + def __pow__(self, other): + # "**" Javascript operator is not supported in all browsers + comp_value = FunctionExpression("pow", (self, other)) + return self._from_expr(comp_value) + + def __rpow__(self, other): + # "**" Javascript operator is not supported in all browsers + comp_value = FunctionExpression("pow", (other, self)) + return self._from_expr(comp_value) + + def __neg__(self): + comp_value = UnaryExpression("-", self) + return self._from_expr(comp_value) + + def __pos__(self): + comp_value = UnaryExpression("+", self) + return self._from_expr(comp_value) + + # comparison operators + + def __eq__(self, other): + comp_value = BinaryExpression("===", self, other) + return self._from_expr(comp_value) + + def __ne__(self, other): + comp_value = BinaryExpression("!==", self, other) + return self._from_expr(comp_value) + + def __gt__(self, other): + comp_value = BinaryExpression(">", self, other) + return self._from_expr(comp_value) + + def __lt__(self, other): + comp_value = BinaryExpression("<", self, other) + return self._from_expr(comp_value) + + def __ge__(self, other): + comp_value = BinaryExpression(">=", self, other) + return self._from_expr(comp_value) + + def __le__(self, other): + comp_value = BinaryExpression("<=", self, other) + return self._from_expr(comp_value) + + def __abs__(self): + comp_value = FunctionExpression("abs", (self,)) + return self._from_expr(comp_value) + + # logical operators + + def __and__(self, other): + comp_value = BinaryExpression("&&", self, other) + return self._from_expr(comp_value) + + def __rand__(self, other): + comp_value = BinaryExpression("&&", other, self) + return self._from_expr(comp_value) + + def __or__(self, other): + comp_value = BinaryExpression("||", self, other) + return self._from_expr(comp_value) + + def __ror__(self, other): + comp_value = BinaryExpression("||", other, self) + return self._from_expr(comp_value) + + def __invert__(self): + comp_value = UnaryExpression("!", self) + return self._from_expr(comp_value) + + +class Expression(OperatorMixin, SchemaBase): + """ + Expression. + + Base object for enabling build-up of Javascript expressions using + a Python syntax. Calling ``repr(obj)`` will return a Javascript + representation of the object and the operations it encodes. + """ + + _schema = {"type": "string"} + + def to_dict(self, *args, **kwargs): + return repr(self) + + def __setattr__(self, attr, val) -> None: + # We don't need the setattr magic defined in SchemaBase + return object.__setattr__(self, attr, val) + + # item access + def __getitem__(self, val): + return GetItemExpression(self, val) + + +class UnaryExpression(Expression): + def __init__(self, op, val) -> None: + super().__init__(op=op, val=val) + + def __repr__(self): + return f"({self.op}{_js_repr(self.val)})" + + +class BinaryExpression(Expression): + def __init__(self, op, lhs, rhs) -> None: + super().__init__(op=op, lhs=lhs, rhs=rhs) + + def __repr__(self): + return f"({_js_repr(self.lhs)} {self.op} {_js_repr(self.rhs)})" + + +class FunctionExpression(Expression): + def __init__(self, name, args) -> None: + super().__init__(name=name, args=args) + + def __repr__(self): + args = ",".join(_js_repr(arg) for arg in self.args) + return f"{self.name}({args})" + + +class ConstExpression(Expression): + def __init__(self, name) -> None: + super().__init__(name=name) + + def __repr__(self) -> str: + return str(self.name) + + +class GetAttrExpression(Expression): + def __init__(self, group, name) -> None: + super().__init__(group=group, name=name) + + def __repr__(self): + return f"{self.group}.{self.name}" + + +class GetItemExpression(Expression): + def __init__(self, group, name) -> None: + super().__init__(group=group, name=name) + + def __repr__(self) -> str: + return f"{self.group}[{self.name!r}]" + + +IntoExpression: TypeAlias = Union[ + "PrimitiveValue_T", dt.date, dt.datetime, OperatorMixin, "Map" +] diff --git a/.venv/lib/python3.13/site-packages/altair/expr/funcs.py b/.venv/lib/python3.13/site-packages/altair/expr/funcs.py new file mode 100644 index 0000000000000000000000000000000000000000..d8a96d465981d80f2fe36d68f5e5788b7d5ac74d --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/expr/funcs.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +FUNCTION_LISTING = { + "isArray": r"Returns true if _value_ is an array, false otherwise.", + "isBoolean": r"Returns true if _value_ is a boolean (`true` or `false`), false otherwise.", + "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.", + "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.", + "isNumber": r"Returns true if _value_ is a number, false otherwise. `NaN` and `Infinity` are considered numbers.", + "isObject": r"Returns true if _value_ is an object (including arrays and Dates), false otherwise.", + "isRegExp": r"Returns true if _value_ is a RegExp (regular expression) object, false otherwise.", + "isString": r"Returns true if _value_ is a string, false otherwise.", + "isValid": r"Returns true if _value_ is not `null`, `undefined`, or `NaN`, false otherwise.", + "toBoolean": r"Coerces the input _value_ to a string. Null values and empty strings are mapped to `null`.", + "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!", + "toNumber": r"Coerces the input _value_ to a number. Null values and empty strings are mapped to `null`.", + "toString": r"Coerces the input _value_ to a string. Null values and empty strings are mapped to `null`.", + "if": r"If _test_ is truthy, returns _thenValue_. Otherwise, returns _elseValue_. The _if_ function is equivalent to the ternary operator `a ? b : c`.", + "isNaN": r"Returns true if _value_ is not a number. Same as JavaScript's `isNaN`.", + "isFinite": r"Returns true if _value_ is a finite number. Same as JavaScript's `isFinite`.", + "abs": r"Returns the absolute value of _value_. Same as JavaScript's `Math.abs`.", + "acos": r"Trigonometric arccosine. Same as JavaScript's `Math.acos`.", + "asin": r"Trigonometric arcsine. Same as JavaScript's `Math.asin`.", + "atan": r"Trigonometric arctangent. Same as JavaScript's `Math.atan`.", + "atan2": r"Returns the arctangent of _dy / dx_. Same as JavaScript's `Math.atan2`.", + "ceil": r"Rounds _value_ to the nearest integer of equal or greater value. Same as JavaScript's `Math.ceil`.", + "clamp": r"Restricts _value_ to be between the specified _min_ and _max_.", + "cos": r"Trigonometric cosine. Same as JavaScript's `Math.cos`.", + "exp": r"Returns the value of _e_ raised to the provided _exponent_. Same as JavaScript's `Math.exp`.", + "floor": r"Rounds _value_ to the nearest integer of equal or lower value. Same as JavaScript's `Math.floor`.", + "hypot": r"Returns the square root of the sum of squares of its arguments. Same as JavaScript's `Math.hypot`.", + "log": r"Returns the natural logarithm of _value_. Same as JavaScript's `Math.log`.", + "max": r"Returns the maximum argument value. Same as JavaScript's `Math.max`.", + "min": r"Returns the minimum argument value. Same as JavaScript's `Math.min`.", + "pow": r"Returns _value_ raised to the given _exponent_. Same as JavaScript's `Math.pow`.", + "random": r"Returns a pseudo-random number in the range [0,1). Same as JavaScript's `Math.random`.", + "round": r"Rounds _value_ to the nearest integer. Same as JavaScript's `Math.round`.", + "sin": r"Trigonometric sine. Same as JavaScript's `Math.sin`.", + "sqrt": r"Square root function. Same as JavaScript's `Math.sqrt`.", + "tan": r"Trigonometric tangent. Same as JavaScript's `Math.tan`.", + "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`.", + "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`.", + "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`.", + "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`.", + "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`.", + "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`.", + "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`.", + "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`.", + "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.", + "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.", + "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.", + "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.", + "now": r"Returns the timestamp for the current time.", + "datetime": r"Returns a new `Date` instance. The _month_ is 0-based, such that `1` represents February.", + "date": r"Returns the day of the month for the given _datetime_ value, in local time.", + "day": r"Returns the day of the week for the given _datetime_ value, in local time.", + "dayofyear": r"Returns the one-based day of the year for the given _datetime_ value, in local time.", + "year": r"Returns the year for the given _datetime_ value, in local time.", + "quarter": r"Returns the quarter of the year (0-3) for the given _datetime_ value, in local time.", + "month": r"Returns the (zero-based) month for the given _datetime_ value, in local time.", + "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._.", + "hours": r"Returns the hours component for the given _datetime_ value, in local time.", + "minutes": r"Returns the minutes component for the given _datetime_ value, in local time.", + "seconds": r"Returns the seconds component for the given _datetime_ value, in local time.", + "milliseconds": r"Returns the milliseconds component for the given _datetime_ value, in local time.", + "time": r"Returns the epoch-based timestamp for the given _datetime_ value.", + "timezoneoffset": r"Returns the timezone offset from the local timezone to UTC for the given _datetime_ value.", + "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).", + "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).", + "utc": r"Returns a timestamp for the given UTC date. The _month_ is 0-based, such that `1` represents February.", + "utcdate": r"Returns the day of the month for the given _datetime_ value, in UTC time.", + "utcday": r"Returns the day of the week for the given _datetime_ value, in UTC time.", + "utcdayofyear": r"Returns the one-based day of the year for the given _datetime_ value, in UTC time.", + "utcyear": r"Returns the year for the given _datetime_ value, in UTC time.", + "utcquarter": r"Returns the quarter of the year (0-3) for the given _datetime_ value, in UTC time.", + "utcmonth": r"Returns the (zero-based) month for the given _datetime_ value, in UTC time.", + "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._.", + "utchours": r"Returns the hours component for the given _datetime_ value, in UTC time.", + "utcminutes": r"Returns the minutes component for the given _datetime_ value, in UTC time.", + "utcseconds": r"Returns the seconds component for the given _datetime_ value, in UTC time.", + "utcmilliseconds": r"Returns the milliseconds component for the given _datetime_ value, in UTC time.", + "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).", + "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).", + "extent": r"Returns a new _[min, max]_ array with the minimum and maximum values of the input array, ignoring `null`, `undefined`, and `NaN` values.", + "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.", + "indexof": r"Returns the first index of _value_ in the input _array_, or the first index of _substring_ in the input _string_..", + "inrange": r"Tests whether _value_ lies within (or is equal to either) the first and last values of the _range_ array.", + "join": r"Returns a new string by concatenating all of the elements of the input _array_, separated by commas or a specified _separator_ string.", + "lastindexof": r"Returns the last index of _value_ in the input _array_, or the last index of _substring_ in the input _string_..", + "length": r"Returns the length of the input _array_, or the length of the input _string_.", + "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.", + "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]`.", + "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`).", + "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.", + "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.", + "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_).", + "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_)..", + "lower": r"Transforms _string_ to lower-case letters.", + "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.", + "parseFloat": r"Parses the input _string_ to a floating-point value. Same as JavaScript's `parseFloat`.", + "parseInt": r"Parses the input _string_ to an integer value. Same as JavaScript's `parseInt`.", + "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).", + "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.", + "substring": r"Returns a section of _string_ between the _start_ and _end_ indices.", + "trim": r"Returns a trimmed string with preceding and trailing whitespace removed.", + "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.", + "upper": r"Transforms _string_ to upper-case letters.", + "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}`.", + "dayFormat": r"Formats a (0-6) _weekday_ number as a full week day name, according to the current locale. For example: `dayFormat(0) -> \"Sunday\"`.", + "dayAbbrevFormat": r"Formats a (0-6) _weekday_ number as an abbreviated week day name, according to the current locale. For example: `dayAbbrevFormat(0) -> \"Sun\"`.", + "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')`.", + "monthFormat": r"Formats a (zero-based) _month_ number as a full month name, according to the current locale. For example: `monthFormat(0) -> \"January\"`.", + "monthAbbrevFormat": r"Formats a (zero-based) _month_ number as an abbreviated month name, according to the current locale. For example: `monthAbbrevFormat(0) -> \"Jan\"`.", + "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']))`.", + "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')`.", + "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')`.", + "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')`.", + "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')`.", + "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).", + "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`.", + "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).", + "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).", + "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).", + "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).", + "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).", + "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).", + "item": r"Returns the current scenegraph item that is the target of the event.", + "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.", + "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.", + "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.", + "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.", + "pinchDistance": r"Returns the pixel distance between the first two touch points of a multi-touch event.", + "pinchAngle": r"Returns the angle of the line connecting the first two touch points of a multi-touch event.", + "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.", + "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.", + "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)`.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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.", + "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]`.", + "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.", + "windowSize": r"Returns the current window size (`[window.innerWidth, window.innerHeight]`) or `[undefined, undefined]` if Vega is not running in a browser environment.", + "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.", + "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.", + "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.", +} + + +# This maps vega expression function names to the Python name +NAME_MAP = {"if": "if_"} diff --git a/.venv/lib/python3.13/site-packages/altair/jupyter/__init__.py b/.venv/lib/python3.13/site-packages/altair/jupyter/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c57815a2f1325efaf1a02970fe287e646cdac9c3 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/jupyter/__init__.py @@ -0,0 +1,21 @@ +try: + import anywidget # noqa: F401 +except ImportError: + # When anywidget isn't available, create stand-in JupyterChart class + # that raises an informative import error on construction. This + # way we can make JupyterChart available in the altair namespace + # when anywidget is not installed + class JupyterChart: + def __init__(self, *args, **kwargs): + msg = ( + "The Altair JupyterChart requires the anywidget \n" + "Python package which may be installed using pip with\n" + " pip install anywidget\n" + "or using conda with\n" + " conda install -c conda-forge anywidget\n" + "Afterwards, you will need to restart your Python kernel." + ) + raise ImportError(msg) + +else: + from .jupyter_chart import JupyterChart # noqa: F401 diff --git a/.venv/lib/python3.13/site-packages/altair/jupyter/js/README.md b/.venv/lib/python3.13/site-packages/altair/jupyter/js/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f1ec545894f60fea2a2096b4ac4b588c890b5192 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/jupyter/js/README.md @@ -0,0 +1,2 @@ +# JupyterChart +This directory contains the JavaScript portion of the Altair `JupyterChart`. The `JupyterChart` is based on the [AnyWidget](https://anywidget.dev/) project. diff --git a/.venv/lib/python3.13/site-packages/altair/jupyter/js/index.js b/.venv/lib/python3.13/site-packages/altair/jupyter/js/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a6677b49364b4def12a696bedd1a4f2cde4c6162 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/jupyter/js/index.js @@ -0,0 +1,231 @@ +import vegaEmbed from "https://esm.sh/vega-embed@v7?deps=vega@6&deps=vega-lite@6.1.0"; +import lodashDebounce from "https://esm.sh/lodash-es@4.17.21/debounce"; + +// Note: For offline support, the import lines above are removed and the remaining script +// is bundled using vl-convert's javascript_bundle function. See the documentation of +// the javascript_bundle function for details on the available imports and their names. +// If an additional import is required in the future, it will need to be added to vl-convert +// in order to preserve offline support. +async function render({ model, el }) { + let finalize; + + function showError(error){ + el.innerHTML = ( + '
' + + '

JavaScript Error: ' + error.message + '

' + + "

This usually means there's a typo in your chart specification. " + + "See the javascript console for the full traceback.

" + + '
' + ); + } + + const reembed = async () => { + if (finalize != null) { + finalize(); + } + + model.set("local_tz", Intl.DateTimeFormat().resolvedOptions().timeZone); + + let spec = structuredClone(model.get("spec")); + if (spec == null) { + // Remove any existing chart and return + while (el.firstChild) { + el.removeChild(el.lastChild); + } + model.save_changes(); + return; + } + let embedOptions = structuredClone(model.get("embed_options")) ?? undefined; + + let api; + try { + api = await vegaEmbed(el, spec, embedOptions); + } catch (error) { + showError(error) + return; + } + + finalize = api.finalize; + + // Debounce config + const wait = model.get("debounce_wait") ?? 10; + const debounceOpts = {leading: false, trailing: true}; + if (model.get("max_wait") ?? true) { + debounceOpts["maxWait"] = wait; + } + + const initialSelections = {}; + for (const selectionName of Object.keys(model.get("_vl_selections"))) { + const storeName = `${selectionName}_store`; + const selectionHandler = (_, value) => { + const newSelections = cleanJson(model.get("_vl_selections") ?? {}); + const store = cleanJson(api.view.data(storeName) ?? []); + + newSelections[selectionName] = {value, store}; + model.set("_vl_selections", newSelections); + model.save_changes(); + }; + api.view.addSignalListener(selectionName, lodashDebounce(selectionHandler, wait, debounceOpts)); + + initialSelections[selectionName] = { + value: cleanJson(api.view.signal(selectionName) ?? {}), + store: cleanJson(api.view.data(storeName) ?? []) + } + } + model.set("_vl_selections", initialSelections); + + const initialParams = {}; + for (const paramName of Object.keys(model.get("_params"))) { + const paramHandler = (_, value) => { + const newParams = JSON.parse(JSON.stringify(model.get("_params"))) || {}; + newParams[paramName] = value; + model.set("_params", newParams); + model.save_changes(); + }; + api.view.addSignalListener(paramName, lodashDebounce(paramHandler, wait, debounceOpts)); + + initialParams[paramName] = api.view.signal(paramName) ?? null + } + model.set("_params", initialParams); + model.save_changes(); + + // Param change callback + model.on('change:_params', async (new_params) => { + for (const [param, value] of Object.entries(new_params.changed ? new_params.changed._params : new_params)) { + api.view.signal(param, value); + } + await api.view.runAsync(); + }); + + // Add signal/data listeners + for (const watch of model.get("_js_watch_plan") ?? []) { + if (watch.namespace === "data") { + const dataHandler = (_, value) => { + model.set("_js_to_py_updates", [{ + namespace: "data", + name: watch.name, + scope: watch.scope, + value: cleanJson(value) + }]); + model.save_changes(); + }; + addDataListener(api.view, watch.name, watch.scope, lodashDebounce(dataHandler, wait, debounceOpts)) + + } else if (watch.namespace === "signal") { + const signalHandler = (_, value) => { + model.set("_js_to_py_updates", [{ + namespace: "signal", + name: watch.name, + scope: watch.scope, + value: cleanJson(value) + }]); + model.save_changes(); + }; + + addSignalListener(api.view, watch.name, watch.scope, lodashDebounce(signalHandler, wait, debounceOpts)) + } + } + + // Add signal/data updaters + model.on('change:_py_to_js_updates', async (updates) => { + const py_to_js_updates = updates.changed ? updates.changed._py_to_js_updates : updates; + for (const update of py_to_js_updates ?? []) { + if (update.namespace === "signal") { + setSignalValue(api.view, update.name, update.scope, update.value); + } else if (update.namespace === "data") { + setDataValue(api.view, update.name, update.scope, update.value); + } + } + await api.view.runAsync(); + }); + } + + model.on('change:spec', reembed); + model.on('change:embed_options', reembed); + model.on('change:debounce_wait', reembed); + model.on('change:max_wait', reembed); + await reembed(); +} + +function cleanJson(data) { + return JSON.parse(JSON.stringify(data)) +} + +function getNestedRuntime(view, scope) { + var runtime = view._runtime; + for (const index of scope) { + runtime = runtime.subcontext[index]; + } + return runtime +} + +function lookupSignalOp(view, name, scope) { + let parent_runtime = getNestedRuntime(view, scope); + return parent_runtime.signals[name] ?? null; +} + +function dataRef(view, name, scope) { + let parent_runtime = getNestedRuntime(view, scope); + return parent_runtime.data[name]; +} + +export function setSignalValue(view, name, scope, value) { + let signal_op = lookupSignalOp(view, name, scope); + view.update(signal_op, value); +} + +export function setDataValue(view, name, scope, value) { + let dataset = dataRef(view, name, scope); + let changeset = view.changeset().remove(() => true).insert(value) + dataset.modified = true; + view.pulse(dataset.input, changeset); +} + +export function addSignalListener(view, name, scope, handler) { + let signal_op = lookupSignalOp(view, name, scope); + return addOperatorListener( + view, + name, + signal_op, + handler, + ); +} + +export function addDataListener(view, name, scope, handler) { + let dataset = dataRef(view, name, scope).values; + return addOperatorListener( + view, + name, + dataset, + handler, + ); +} + +// Private helpers from Vega for dealing with nested signals/data +function findOperatorHandler(op, handler) { + const h = (op._targets || []) + .filter(op => op._update && op._update.handler === handler); + return h.length ? h[0] : null; +} + +function addOperatorListener(view, name, op, handler) { + let h = findOperatorHandler(op, handler); + if (!h) { + h = trap(view, () => handler(name, op.value)); + h.handler = handler; + view.on(op, null, h); + } + return view; +} + +function trap(view, fn) { + return !fn ? null : function() { + try { + fn.apply(this, arguments); + } catch (error) { + view.error(error); + } + }; +} + +export default { render } diff --git a/.venv/lib/python3.13/site-packages/altair/jupyter/jupyter_chart.py b/.venv/lib/python3.13/site-packages/altair/jupyter/jupyter_chart.py new file mode 100644 index 0000000000000000000000000000000000000000..675cce15fbb3510889ca44ec7eada299eea9d554 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/jupyter/jupyter_chart.py @@ -0,0 +1,404 @@ +from __future__ import annotations + +import json +import pathlib +from typing import Any + +import anywidget +import traitlets + +import altair as alt +from altair import TopLevelSpec +from altair.utils._vegafusion_data import ( + compile_to_vegafusion_chart_state, + using_vegafusion, +) +from altair.utils.selection import IndexSelection, IntervalSelection, PointSelection + +_here = pathlib.Path(__file__).parent + + +class Params(traitlets.HasTraits): + """Traitlet class storing a JupyterChart's params.""" + + def __init__(self, trait_values): + super().__init__() + + for key, value in trait_values.items(): + if isinstance(value, (int, float)): + traitlet_type = traitlets.Float() + elif isinstance(value, str): + traitlet_type = traitlets.Unicode() + elif isinstance(value, list): + traitlet_type = traitlets.List() + elif isinstance(value, dict): + traitlet_type = traitlets.Dict() + else: + traitlet_type = traitlets.Any() + + # Add the new trait. + self.add_traits(**{key: traitlet_type}) + + # Set the trait's value. + setattr(self, key, value) + + def __repr__(self): + return f"Params({self.trait_values()})" + + +class Selections(traitlets.HasTraits): + """Traitlet class storing a JupyterChart's selections.""" + + def __init__(self, trait_values): + super().__init__() + + for key, value in trait_values.items(): + if isinstance(value, IndexSelection): + traitlet_type = traitlets.Instance(IndexSelection) + elif isinstance(value, PointSelection): + traitlet_type = traitlets.Instance(PointSelection) + elif isinstance(value, IntervalSelection): + traitlet_type = traitlets.Instance(IntervalSelection) + else: + msg = f"Unexpected selection type: {type(value)}" + raise ValueError(msg) + + # Add the new trait. + self.add_traits(**{key: traitlet_type}) + + # Set the trait's value. + setattr(self, key, value) + + # Make read-only + self.observe(self._make_read_only, names=key) + + def __repr__(self): + return f"Selections({self.trait_values()})" + + def _make_read_only(self, change): + """Work around to make traits read-only, but still allow us to change them internally.""" + if change["name"] in self.traits() and change["old"] != change["new"]: + self._set_value(change["name"], change["old"]) + msg = ( + "Selections may not be set from Python.\n" + f"Attempted to set select: {change['name']}" + ) + raise ValueError(msg) + + def _set_value(self, key, value): + self.unobserve(self._make_read_only, names=key) + setattr(self, key, value) + self.observe(self._make_read_only, names=key) + + +def load_js_src() -> str: + return (_here / "js" / "index.js").read_text() + + +class JupyterChart(anywidget.AnyWidget): + _esm = load_js_src() + _css = r""" + .vega-embed { + /* Make sure action menu isn't cut off */ + overflow: visible; + } + """ + + # Public traitlets + chart = traitlets.Instance(TopLevelSpec, allow_none=True) + spec = traitlets.Dict(allow_none=True).tag(sync=True) + debounce_wait = traitlets.Float(default_value=10).tag(sync=True) + max_wait = traitlets.Bool(default_value=True).tag(sync=True) + local_tz = traitlets.Unicode(default_value=None, allow_none=True).tag(sync=True) + debug = traitlets.Bool(default_value=False) + embed_options = traitlets.Dict(default_value=None, allow_none=True).tag(sync=True) + + # Internal selection traitlets + _selection_types = traitlets.Dict() + _vl_selections = traitlets.Dict().tag(sync=True) + + # Internal param traitlets + _params = traitlets.Dict().tag(sync=True) + + # Internal comm traitlets for VegaFusion support + _chart_state = traitlets.Any(allow_none=True) + _js_watch_plan = traitlets.Any(allow_none=True).tag(sync=True) + _js_to_py_updates = traitlets.Any(allow_none=True).tag(sync=True) + _py_to_js_updates = traitlets.Any(allow_none=True).tag(sync=True) + + # Track whether charts are configured for offline use + _is_offline = False + + @classmethod + def enable_offline(cls, offline: bool = True): + """ + Configure JupyterChart's offline behavior. + + Parameters + ---------- + offline: bool + If True, configure JupyterChart to operate in offline mode where JavaScript + dependencies are loaded from vl-convert. + If False, configure it to operate in online mode where JavaScript dependencies + are loaded from CDN dynamically. This is the default behavior. + """ + from altair.utils._importers import import_vl_convert, vl_version_for_vl_convert + + if offline: + if cls._is_offline: + # Already offline + return + + vlc = import_vl_convert() + + src_lines = load_js_src().split("\n") + + # Remove leading lines with only whitespace, comments, or imports + while src_lines and ( + len(src_lines[0].strip()) == 0 + or src_lines[0].startswith("import") + or src_lines[0].startswith("//") + ): + src_lines.pop(0) + + src = "\n".join(src_lines) + + # vl-convert's javascript_bundle function creates a self-contained JavaScript bundle + # for JavaScript snippets that import from a small set of dependencies that + # vl-convert includes. To see the available imports and their imported names, run + # import vl_convert as vlc + # help(vlc.javascript_bundle) + bundled_src = vlc.javascript_bundle( + src, vl_version=vl_version_for_vl_convert() + ) + cls._esm = bundled_src + cls._is_offline = True + else: + cls._esm = load_js_src() + cls._is_offline = False + + def __init__( + self, + chart: TopLevelSpec, + debounce_wait: int = 10, + max_wait: bool = True, + debug: bool = False, + embed_options: dict | None = None, + **kwargs: Any, + ): + """ + Jupyter Widget for displaying and updating Altair Charts, and retrieving selection and parameter values. + + Parameters + ---------- + chart: Chart + Altair Chart instance + debounce_wait: int + Debouncing wait time in milliseconds. Updates will be sent from the client to the kernel + after debounce_wait milliseconds of no chart interactions. + max_wait: bool + If True (default), updates will be sent from the client to the kernel every debounce_wait + milliseconds even if there are ongoing chart interactions. If False, updates will not be + sent until chart interactions have completed. + debug: bool + If True, debug messages will be printed + embed_options: dict + Options to pass to vega-embed. + See https://github.com/vega/vega-embed?tab=readme-ov-file#options + """ + self.params = Params({}) + self.selections = Selections({}) + super().__init__( + chart=chart, + debounce_wait=debounce_wait, + max_wait=max_wait, + debug=debug, + embed_options=embed_options, + **kwargs, + ) + + @traitlets.observe("chart") + def _on_change_chart(self, change): # noqa: C901 + """Updates the JupyterChart's internal state when the wrapped Chart instance changes.""" + new_chart = change.new + selection_watches = [] + selection_types = {} + initial_params = {} + initial_vl_selections = {} + empty_selections = {} + + if new_chart is None: + with self.hold_sync(): + self.spec = None + self._selection_types = selection_types + self._vl_selections = initial_vl_selections + self._params = initial_params + return + + params = getattr(new_chart, "params", []) + + if params is not alt.Undefined: + for param in new_chart.params: + if isinstance(param.name, alt.ParameterName): + clean_name = param.name.to_json().strip('"') + else: + clean_name = param.name + + select = getattr(param, "select", alt.Undefined) + + if select != alt.Undefined: + if not isinstance(select, dict): + select = select.to_dict() + + select_type = select["type"] + if select_type == "point": + if not ( + select.get("fields", None) or select.get("encodings", None) + ): + # Point selection with no associated fields or encodings specified. + # This is an index-based selection + selection_types[clean_name] = "index" + empty_selections[clean_name] = IndexSelection( + name=clean_name, value=[], store=[] + ) + else: + selection_types[clean_name] = "point" + empty_selections[clean_name] = PointSelection( + name=clean_name, value=[], store=[] + ) + elif select_type == "interval": + selection_types[clean_name] = "interval" + empty_selections[clean_name] = IntervalSelection( + name=clean_name, value={}, store=[] + ) + else: + msg = f"Unexpected selection type {select.type}" + raise ValueError(msg) + selection_watches.append(clean_name) + initial_vl_selections[clean_name] = {"value": None, "store": []} + else: + clean_value = param.value if param.value != alt.Undefined else None + initial_params[clean_name] = clean_value + + # Handle the params generated by transforms + for param_name in collect_transform_params(new_chart): + initial_params[param_name] = None + + # Setup params + self.params = Params(initial_params) + + def on_param_traitlet_changed(param_change): + new_params = dict(self._params) + new_params[param_change["name"]] = param_change["new"] + self._params = new_params + + self.params.observe(on_param_traitlet_changed) + + # Setup selections + self.selections = Selections(empty_selections) + + # Update properties all together + with self.hold_sync(): + if using_vegafusion(): + if self.local_tz is None: + self.spec = None + + def on_local_tz_change(change): + self._init_with_vegafusion(change["new"]) + + self.observe(on_local_tz_change, ["local_tz"]) + else: + self._init_with_vegafusion(self.local_tz) + else: + self.spec = new_chart.to_dict() + self._selection_types = selection_types + self._vl_selections = initial_vl_selections + self._params = initial_params + + def _init_with_vegafusion(self, local_tz: str): + if self.chart is not None: + vegalite_spec = self.chart.to_dict(context={"pre_transform": False}) + with self.hold_sync(): + self._chart_state = compile_to_vegafusion_chart_state( + vegalite_spec, local_tz + ) + self._js_watch_plan = self._chart_state.get_watch_plan()[ + "client_to_server" + ] + self.spec = self._chart_state.get_transformed_spec() + + # Callback to update chart state and send updates back to client + def on_js_to_py_updates(change): + if self.debug: + updates_str = json.dumps(change["new"], indent=2) + print( + f"JavaScript to Python VegaFusion updates:\n {updates_str}" + ) + updates = self._chart_state.update(change["new"]) + if self.debug: + updates_str = json.dumps(updates, indent=2) + print( + f"Python to JavaScript VegaFusion updates:\n {updates_str}" + ) + self._py_to_js_updates = updates + + self.observe(on_js_to_py_updates, ["_js_to_py_updates"]) + + @traitlets.observe("_params") + def _on_change_params(self, change): + for param_name, value in change.new.items(): + setattr(self.params, param_name, value) + + @traitlets.observe("_vl_selections") + def _on_change_selections(self, change): + """Updates the JupyterChart's public selections traitlet in response to changes that the JavaScript logic makes to the internal _selections traitlet.""" + for selection_name, selection_dict in change.new.items(): + value = selection_dict["value"] + store = selection_dict["store"] + selection_type = self._selection_types[selection_name] + if selection_type == "index": + self.selections._set_value( + selection_name, + IndexSelection.from_vega(selection_name, signal=value, store=store), + ) + elif selection_type == "point": + self.selections._set_value( + selection_name, + PointSelection.from_vega(selection_name, signal=value, store=store), + ) + elif selection_type == "interval": + self.selections._set_value( + selection_name, + IntervalSelection.from_vega( + selection_name, signal=value, store=store + ), + ) + + +def collect_transform_params(chart: TopLevelSpec) -> set[str]: + """ + Collect the names of params that are defined by transforms. + + Parameters + ---------- + chart: Chart from which to extract transform params + + Returns + ------- + set of param names + """ + transform_params = set() + + # Handle recursive case + for prop in ("layer", "concat", "hconcat", "vconcat"): + for child in getattr(chart, prop, []): + transform_params.update(collect_transform_params(child)) + + # Handle chart's own transforms + transforms = getattr(chart, "transform", []) + transforms = transforms if transforms != alt.Undefined else [] + for tx in transforms: + if hasattr(tx, "param"): + transform_params.add(tx.param) + + return transform_params diff --git a/.venv/lib/python3.13/site-packages/altair/typing/__init__.py b/.venv/lib/python3.13/site-packages/altair/typing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..68990a89dfb751c75626d22527f605cd8460ab2f --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/typing/__init__.py @@ -0,0 +1,96 @@ +"""Public types to ease integrating with `altair`.""" + +from __future__ import annotations + +__all__ = [ + "ChannelAngle", + "ChannelColor", + "ChannelColumn", + "ChannelDescription", + "ChannelDetail", + "ChannelFacet", + "ChannelFill", + "ChannelFillOpacity", + "ChannelHref", + "ChannelKey", + "ChannelLatitude", + "ChannelLatitude2", + "ChannelLongitude", + "ChannelLongitude2", + "ChannelOpacity", + "ChannelOrder", + "ChannelRadius", + "ChannelRadius2", + "ChannelRow", + "ChannelShape", + "ChannelSize", + "ChannelStroke", + "ChannelStrokeDash", + "ChannelStrokeOpacity", + "ChannelStrokeWidth", + "ChannelText", + "ChannelTheta", + "ChannelTheta2", + "ChannelTooltip", + "ChannelUrl", + "ChannelX", + "ChannelX2", + "ChannelXError", + "ChannelXError2", + "ChannelXOffset", + "ChannelY", + "ChannelY2", + "ChannelYError", + "ChannelYError2", + "ChannelYOffset", + "ChartType", + "EncodeKwds", + "Optional", + "is_chart_type", +] + +from altair.utils.schemapi import Optional +from altair.vegalite.v6.api import ChartType, is_chart_type +from altair.vegalite.v6.schema.channels import ( + ChannelAngle, + ChannelColor, + ChannelColumn, + ChannelDescription, + ChannelDetail, + ChannelFacet, + ChannelFill, + ChannelFillOpacity, + ChannelHref, + ChannelKey, + ChannelLatitude, + ChannelLatitude2, + ChannelLongitude, + ChannelLongitude2, + ChannelOpacity, + ChannelOrder, + ChannelRadius, + ChannelRadius2, + ChannelRow, + ChannelShape, + ChannelSize, + ChannelStroke, + ChannelStrokeDash, + ChannelStrokeOpacity, + ChannelStrokeWidth, + ChannelText, + ChannelTheta, + ChannelTheta2, + ChannelTooltip, + ChannelUrl, + ChannelX, + ChannelX2, + ChannelXError, + ChannelXError2, + ChannelXOffset, + ChannelY, + ChannelY2, + ChannelYError, + ChannelYError2, + ChannelYOffset, + EncodeKwds, +) diff --git a/.venv/lib/python3.13/site-packages/altair/utils/__init__.py b/.venv/lib/python3.13/site-packages/altair/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..68697ce33d56bf0987dfaa162fa9593b478c639b --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/utils/__init__.py @@ -0,0 +1,45 @@ +from .core import ( + SHORTHAND_KEYS, + display_traceback, + infer_encoding_types, + infer_vegalite_type_for_pandas, + parse_shorthand, + sanitize_narwhals_dataframe, + sanitize_pandas_dataframe, + update_nested, + use_signature, +) +from .deprecation import AltairDeprecationWarning, deprecated, deprecated_warn +from .html import spec_to_html +from .plugin_registry import PluginRegistry +from .schemapi import ( + VERSIONS, + Optional, + SchemaBase, + SchemaLike, + Undefined, + is_undefined, +) + +__all__ = ( + "SHORTHAND_KEYS", + "VERSIONS", + "AltairDeprecationWarning", + "Optional", + "PluginRegistry", + "SchemaBase", + "SchemaLike", + "Undefined", + "deprecated", + "deprecated_warn", + "display_traceback", + "infer_encoding_types", + "infer_vegalite_type_for_pandas", + "is_undefined", + "parse_shorthand", + "sanitize_narwhals_dataframe", + "sanitize_pandas_dataframe", + "spec_to_html", + "update_nested", + "use_signature", +) diff --git a/.venv/lib/python3.13/site-packages/altair/utils/_dfi_types.py b/.venv/lib/python3.13/site-packages/altair/utils/_dfi_types.py new file mode 100644 index 0000000000000000000000000000000000000000..1b47ddd08dc6391715dfa034b0c1e07e6e9a2398 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/utils/_dfi_types.py @@ -0,0 +1,164 @@ +# DataFrame Interchange Protocol Types +# Copied from https://data-apis.org/dataframe-protocol/latest/API.html, +# changed ABCs to Protocols, and subset the type hints to only those that are +# relevant for Altair. +# +# These classes are only for use in type signatures +from __future__ import annotations + +import enum +from typing import TYPE_CHECKING, Any, Protocol + +if TYPE_CHECKING: + from collections.abc import Iterable + + +class DtypeKind(enum.IntEnum): + """ + Integer enum for data types. + + Attributes + ---------- + INT : int + Matches to signed integer data type. + UINT : int + Matches to unsigned integer data type. + FLOAT : int + Matches to floating point data type. + BOOL : int + Matches to boolean data type. + STRING : int + Matches to string data type (UTF-8 encoded). + DATETIME : int + Matches to datetime data type. + CATEGORICAL : int + Matches to categorical data type. + """ + + INT = 0 + UINT = 1 + FLOAT = 2 + BOOL = 20 + STRING = 21 # UTF-8 + DATETIME = 22 + CATEGORICAL = 23 + + +# Type hint of first element would actually be DtypeKind but can't use that +# as other libraries won't use an instance of our own Enum in this module but have +# their own. Type checkers will raise an error on that even though the enums +# are identical. +class Column(Protocol): + @property + def dtype(self) -> tuple[Any, int, str, str]: + """ + Dtype description as a tuple ``(kind, bit-width, format string, endianness)``. + + Bit-width : the number of bits as an integer + Format string : data type description format string in Apache Arrow C + Data Interface format. + Endianness : current only native endianness (``=``) is supported + + Notes + ----- + - Kind specifiers are aligned with DLPack where possible (hence the + jump to 20, leave enough room for future extension) + - Masks must be specified as boolean with either bit width 1 (for bit + masks) or 8 (for byte masks). + - Dtype width in bits was preferred over bytes + - Endianness isn't too useful, but included now in case in the future + we need to support non-native endianness + - Went with Apache Arrow format strings over NumPy format strings + because they're more complete from a dataframe perspective + - Format strings are mostly useful for datetime specification, and + for categoricals. + - For categoricals, the format string describes the type of the + categorical in the data buffer. In case of a separate encoding of + the categorical (e.g. an integer to string mapping), this can + be derived from ``self.describe_categorical``. + - Data types not included: complex, Arrow-style null, binary, decimal, + and nested (list, struct, map, union) dtypes. + """ + ... + + # Have to use a generic Any return type as not all libraries who implement + # the dataframe interchange protocol implement the TypedDict that is usually + # returned here in the same way. As TypedDicts are invariant, even a slight change + # will lead to an error by a type checker. See PR in which this code was added + # for details. + @property + def describe_categorical(self) -> Any: + """ + If the dtype is categorical, there are two options. + + - There are only values in the data buffer. + - There is a separate non-categorical Column encoding categorical values. + + Raises TypeError if the dtype is not categorical + + Returns the dictionary with description on how to interpret the data buffer: + - "is_ordered" : bool, whether the ordering of dictionary indices is + semantically meaningful. + - "is_dictionary" : bool, whether a mapping of + categorical values to other objects exists + - "categories" : Column representing the (implicit) mapping of indices to + category values (e.g. an array of cat1, cat2, ...). + None if not a dictionary-style categorical. + + TBD: are there any other in-memory representations that are needed? + """ + ... + + +class DataFrame(Protocol): + """ + A data frame class, with only the methods required by the interchange protocol defined. + + A "data frame" represents an ordered collection of named columns. + A column's "name" must be a unique string. + Columns may be accessed by name or by position. + + This could be a public data frame class, or an object with the methods and + attributes defined on this DataFrame class could be returned from the + ``__dataframe__`` method of a public data frame class in a library adhering + to the dataframe interchange protocol specification. + """ + + def __dataframe__( + self, nan_as_null: bool = False, allow_copy: bool = True + ) -> DataFrame: + """ + Construct a new exchange object, potentially changing the parameters. + + ``nan_as_null`` is a keyword intended for the consumer to tell the + producer to overwrite null values in the data with ``NaN``. + It is intended for cases where the consumer does not support the bit + mask or byte mask that is the producer's native representation. + ``allow_copy`` is a keyword that defines whether or not the library is + allowed to make a copy of the data. For example, copying data would be + necessary if a library supports strided buffers, given that this protocol + specifies contiguous buffers. + """ + ... + + def column_names(self) -> Iterable[str]: + """Return an iterator yielding the column names.""" + ... + + def get_column_by_name(self, name: str) -> Column: + """Return the column whose name is the indicated name.""" + ... + + def get_chunks(self, n_chunks: int | None = None) -> Iterable[DataFrame]: + """ + Return an iterator yielding the chunks. + + By default (None), yields the chunks that the data is stored as by the + producer. If given, ``n_chunks`` must be a multiple of + ``self.num_chunks()``, meaning the producer must subdivide each chunk + before yielding it. + + Note that the producer must ensure that all columns are chunked the + same way. + """ + ... diff --git a/.venv/lib/python3.13/site-packages/altair/utils/_importers.py b/.venv/lib/python3.13/site-packages/altair/utils/_importers.py new file mode 100644 index 0000000000000000000000000000000000000000..2224f3c25e248ca48756897a02adbbfd5f0e57ae --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/utils/_importers.py @@ -0,0 +1,106 @@ +from __future__ import annotations + +from importlib.metadata import version as importlib_version +from typing import TYPE_CHECKING + +from packaging.version import Version + +from altair.utils.schemapi import VERSIONS + +if TYPE_CHECKING: + from types import ModuleType + + +def import_vegafusion() -> ModuleType: + min_version = VERSIONS["vegafusion"] + try: + version = importlib_version("vegafusion") + if Version(version) < Version(min_version): + msg = ( + f"The vegafusion package must be version {min_version} or greater. " + f"Found version {version}" + ) + raise RuntimeError(msg) + import vegafusion as vf + + return vf + except ImportError as err: + msg = ( + 'The "vegafusion" data transformer and chart.transformed_data feature requires\n' + f"version {min_version} or greater of the 'vegafusion' package.\n" + "This can be installed with pip using:\n" + f' pip install "vegafusion>={min_version}"\n' + "or conda:\n" + f' conda install -c conda-forge "vegafusion>={min_version}"\n\n' + f"ImportError: {err.args[0]}" + ) + raise ImportError(msg) from err + + +def import_vl_convert() -> ModuleType: + min_version = VERSIONS["vl-convert-python"] + try: + version = importlib_version("vl-convert-python") + if Version(version) < Version(min_version): + msg = ( + f"The vl-convert-python package must be version {min_version} or greater. " + f"Found version {version}" + ) + raise RuntimeError(msg) + import vl_convert as vlc + + return vlc + except ImportError as err: + msg = ( + f"The vl-convert Vega-Lite compiler and file export feature requires\n" + f"version {min_version} or greater of the 'vl-convert-python' package. \n" + f"This can be installed with pip using:\n" + f' pip install "vl-convert-python>={min_version}"\n' + "or conda:\n" + f' conda install -c conda-forge "vl-convert-python>={min_version}"\n\n' + f"ImportError: {err.args[0]}" + ) + raise ImportError(msg) from err + + +def vl_version_for_vl_convert() -> str: + from altair.vegalite import SCHEMA_VERSION + + # Compute VlConvert's vl_version string (of the form 'v5_2') + # from SCHEMA_VERSION (of the form 'v5.2.0') + return "_".join(SCHEMA_VERSION.split(".")[:2]) + + +def import_pyarrow_interchange() -> ModuleType: + min_version = "11.0.0" + try: + version = importlib_version("pyarrow") + + if Version(version) < Version(min_version): + msg = ( + f"The pyarrow package must be version {min_version} or greater. " + f"Found version {version}" + ) + raise RuntimeError(msg) + import pyarrow.interchange as pi + + return pi + except ImportError as err: + msg = ( + f"Usage of the DataFrame Interchange Protocol requires\n" + f"version {min_version} or greater of the pyarrow package. \n" + f"This can be installed with pip using:\n" + f' pip install "pyarrow>={min_version}"\n' + "or conda:\n" + f' conda install -c conda-forge "pyarrow>={min_version}"\n\n' + f"ImportError: {err.args[0]}" + ) + raise ImportError(msg) from err + + +def pyarrow_available() -> bool: + try: + import_pyarrow_interchange() + return True + except (ImportError, RuntimeError): + return False diff --git a/.venv/lib/python3.13/site-packages/altair/utils/_show.py b/.venv/lib/python3.13/site-packages/altair/utils/_show.py new file mode 100644 index 0000000000000000000000000000000000000000..e617980545173649cac52f1786549c40a3d2b0a9 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/utils/_show.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +import webbrowser +from http.server import BaseHTTPRequestHandler, HTTPServer +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Iterable + + +def open_html_in_browser( + html: str | bytes, + using: str | Iterable[str] | None = None, + port: int | None = None, +) -> None: + """ + Display an html document in a web browser without creating a temp file. + + Instantiates a simple http server and uses the webbrowser module to + open the server's URL + + Parameters + ---------- + html: str + HTML string to display + using: str or iterable of str + Name of the web browser to open (e.g. "chrome", "firefox", etc.). + If an iterable, choose the first browser available on the system. + If none, choose the system default browser. + port: int + Port to use. Defaults to a random port + """ + # Encode html to bytes + html_bytes = html.encode("utf8") if isinstance(html, str) else html + + browser = None + + if using is None: + browser = webbrowser.get(None) + else: + # normalize using to an iterable + if isinstance(using, str): + using = [using] + + for browser_key in using: + try: + browser = webbrowser.get(browser_key) + if browser is not None: + break + except webbrowser.Error: + pass + + if browser is None: + raise ValueError("Failed to locate a browser with name in " + str(using)) + + class OneShotRequestHandler(BaseHTTPRequestHandler): + def do_GET(self) -> None: + self.send_response(200) + self.send_header("Content-type", "text/html") + self.end_headers() + + bufferSize = 1024 * 1024 + for i in range(0, len(html_bytes), bufferSize): + self.wfile.write(html_bytes[i : i + bufferSize]) + + def log_message(self, format, *args): + # Silence stderr logging + pass + + # Use specified port if provided, otherwise choose a random port (port value of 0) + server = HTTPServer( + ("127.0.0.1", port if port is not None else 0), OneShotRequestHandler + ) + browser.open(f"http://127.0.0.1:{server.server_port}") + server.handle_request() diff --git a/.venv/lib/python3.13/site-packages/altair/utils/_transformed_data.py b/.venv/lib/python3.13/site-packages/altair/utils/_transformed_data.py new file mode 100644 index 0000000000000000000000000000000000000000..2d22b94e670c4de2ff02526f46b069516185b8a8 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/utils/_transformed_data.py @@ -0,0 +1,591 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, overload + +from altair import ( + Chart, + ConcatChart, + ConcatSpecGenericSpec, + FacetChart, + FacetedUnitSpec, + FacetSpec, + HConcatChart, + HConcatSpecGenericSpec, + LayerChart, + LayerSpec, + NonNormalizedSpec, + TopLevelConcatSpec, + TopLevelFacetSpec, + TopLevelHConcatSpec, + TopLevelLayerSpec, + TopLevelUnitSpec, + TopLevelVConcatSpec, + UnitSpec, + UnitSpecWithFrame, + VConcatChart, + VConcatSpecGenericSpec, + data_transformers, +) +from altair.utils._vegafusion_data import get_inline_tables, import_vegafusion +from altair.utils.schemapi import Undefined + +if TYPE_CHECKING: + import sys + from collections.abc import Iterable + + if sys.version_info >= (3, 10): + from typing import TypeAlias + else: + from typing_extensions import TypeAlias + + from altair.typing import ChartType + from altair.utils.core import DataFrameLike + +Scope: TypeAlias = tuple[int, ...] +FacetMapping: TypeAlias = dict[tuple[str, Scope], tuple[str, Scope]] + + +# For the transformed_data functionality, the chart classes in the values +# can be considered equivalent to the chart class in the key. +_chart_class_mapping = { + Chart: ( + Chart, + TopLevelUnitSpec, + FacetedUnitSpec, + UnitSpec, + UnitSpecWithFrame, + NonNormalizedSpec, + ), + LayerChart: (LayerChart, TopLevelLayerSpec, LayerSpec), + ConcatChart: (ConcatChart, TopLevelConcatSpec, ConcatSpecGenericSpec), + HConcatChart: (HConcatChart, TopLevelHConcatSpec, HConcatSpecGenericSpec), + VConcatChart: (VConcatChart, TopLevelVConcatSpec, VConcatSpecGenericSpec), + FacetChart: (FacetChart, TopLevelFacetSpec, FacetSpec), +} + + +@overload +def transformed_data( + chart: Chart | FacetChart, + row_limit: int | None = None, + exclude: Iterable[str] | None = None, +) -> DataFrameLike | None: ... + + +@overload +def transformed_data( + chart: LayerChart | HConcatChart | VConcatChart | ConcatChart, + row_limit: int | None = None, + exclude: Iterable[str] | None = None, +) -> list[DataFrameLike]: ... + + +def transformed_data(chart, row_limit=None, exclude=None): + """ + Evaluate a Chart's transforms. + + Evaluate the data transforms associated with a Chart and return the + transformed data as one or more DataFrames + + Parameters + ---------- + chart : Chart, FacetChart, LayerChart, HConcatChart, VConcatChart, or ConcatChart + Altair chart to evaluate transforms on + row_limit : int (optional) + Maximum number of rows to return for each DataFrame. None (default) for unlimited + exclude : iterable of str + Set of the names of charts to exclude + + Returns + ------- + DataFrame or list of DataFrames or None + If input chart is a Chart or Facet Chart, returns a DataFrame of the + transformed data. Otherwise, returns a list of DataFrames of the + transformed data + """ + vf = import_vegafusion() + # Add mark if none is specified to satisfy Vega-Lite + if isinstance(chart, Chart) and chart.mark == Undefined: + chart = chart.mark_point() + + # Deep copy chart so that we can rename marks without affecting caller + chart = chart.copy(deep=True) + + # Ensure that all views are named so that we can look them up in the + # resulting Vega specification + chart_names = name_views(chart, 0, exclude=exclude) + + # Compile to Vega and extract inline DataFrames + with data_transformers.enable("vegafusion"): + vega_spec = chart.to_dict(format="vega", context={"pre_transform": False}) + inline_datasets = get_inline_tables(vega_spec) + + # Build mapping from mark names to vega datasets + facet_mapping = get_facet_mapping(vega_spec) + dataset_mapping = get_datasets_for_view_names(vega_spec, chart_names, facet_mapping) + + # Build a list of vega dataset names that corresponds to the order + # of the chart components + dataset_names = [] + for chart_name in chart_names: + if chart_name in dataset_mapping: + dataset_names.append(dataset_mapping[chart_name]) + else: + msg = "Failed to locate all datasets" + raise ValueError(msg) + + # Extract transformed datasets with VegaFusion + datasets, _ = vf.runtime.pre_transform_datasets( + vega_spec, + dataset_names, + row_limit=row_limit, + inline_datasets=inline_datasets, + ) + + if isinstance(chart, (Chart, FacetChart)): + # Return DataFrame (or None if it was excluded) if input was a simple Chart + if not datasets: + return None + else: + return datasets[0] + else: + # Otherwise return the list of DataFrames + return datasets + + +# The equivalent classes from _chart_class_mapping should also be added +# to the type hints below for `chart` as the function would also work for them. +# However, this was not possible so far as mypy then complains about +# "Overloaded function signatures 1 and 2 overlap with incompatible return types [misc]" +# This might be due to the complex type hierarchy of the chart classes. +# See also https://github.com/python/mypy/issues/5119 +# and https://github.com/python/mypy/issues/4020 which show that mypy might not have +# a very consistent behavior for overloaded functions. +# The same error appeared when trying it with Protocols for the concat and layer charts. +# This function is only used internally and so we accept this inconsistency for now. +def _assign_chart_name(chart: ChartType) -> None: + """Assign a name to a chart if it doesn't have one.""" + if chart.name in {None, Undefined}: + # Use hash-based naming for Altair Chart objects + if hasattr(chart, "_get_view_hash_name"): + chart.name = chart._get_view_hash_name() + else: + # For Vega-Lite schema objects (UnitSpec, FacetedUnitSpec, etc.), + # use simple naming since these are already unique by design + chart_type = chart.__class__.__name__.lower() + # Clean up the type name for readability + chart_type = ( + chart_type.replace("spec", "") + .replace("generic", "") + .replace("concat", "") + ) + chart_type = chart_type.removesuffix("_") + # Use object ID for uniqueness - these objects are already unique + chart.name = f"view_{chart_type}_{id(chart):x}" + + +def _get_subcharts(chart: ChartType) -> list[Any]: + """Get the subcharts for a composite chart.""" + if isinstance(chart, _chart_class_mapping[LayerChart]): + return chart.layer + elif isinstance(chart, _chart_class_mapping[HConcatChart]): + return chart.hconcat + elif isinstance(chart, _chart_class_mapping[VConcatChart]): + return chart.vconcat + elif isinstance(chart, _chart_class_mapping[ConcatChart]): + return chart.concat + else: + msg = ( + "transformed_data accepts an instance of " + "Chart, FacetChart, LayerChart, HConcatChart, VConcatChart, or ConcatChart\n" + f"Received value of type: {type(chart)}" + ) + raise ValueError(msg) + + +def name_views( + chart: ChartType, i: int = 0, exclude: Iterable[str] | None = None +) -> list[str]: + """ + Name unnamed chart views. + + Name unnamed charts views so that we can look them up later in + the compiled Vega spec. + + Note: This function mutates the input chart by applying names to + unnamed views. + + Parameters + ---------- + chart : Chart, FacetChart, LayerChart, HConcatChart, VConcatChart, or ConcatChart + Altair chart to apply names to + i : int (default 0) + Starting chart index + exclude : iterable of str + Names of charts to exclude + + Returns + ------- + list of str + List of the names of the charts and subcharts + """ + exclude = set(exclude) if exclude is not None else set() + + # Handle simple charts (Chart and FacetChart) + if isinstance( + chart, (_chart_class_mapping[Chart], _chart_class_mapping[FacetChart]) + ): + if chart.name not in exclude: + _assign_chart_name(chart) + return [chart.name] + return [] + + # Handle composite charts + subcharts = _get_subcharts(chart) + chart_names: list[str] = [] + for subchart in subcharts: + for name in name_views(subchart, i=i + len(chart_names), exclude=exclude): + chart_names.append(name) + return chart_names + + +def get_group_mark_for_scope( + vega_spec: dict[str, Any], scope: Scope +) -> dict[str, Any] | None: + """ + Get the group mark at a particular scope. + + Parameters + ---------- + vega_spec : dict + Top-level Vega specification dictionary + scope : tuple of int + Scope tuple. If empty, the original Vega specification is returned. + Otherwise, the nested group mark at the scope specified is returned. + + Returns + ------- + dict or None + Top-level Vega spec (if scope is empty) + or group mark (if scope is non-empty) + or None (if group mark at scope does not exist) + + Examples + -------- + >>> spec = { + ... "marks": [ + ... {"type": "group", "marks": [{"type": "symbol"}]}, + ... {"type": "group", "marks": [{"type": "rect"}]}, + ... ] + ... } + >>> get_group_mark_for_scope(spec, (1,)) + {'type': 'group', 'marks': [{'type': 'rect'}]} + """ + group = vega_spec + + # Find group at scope + for scope_value in scope: + group_index = 0 + child_group = None + for mark in group.get("marks", []): + if mark.get("type") == "group": + if group_index == scope_value: + child_group = mark + break + group_index += 1 + if child_group is None: + return None + group = child_group + + return group + + +def get_datasets_for_scope(vega_spec: dict[str, Any], scope: Scope) -> list[str]: + """ + Get the names of the datasets that are defined at a given scope. + + Parameters + ---------- + vega_spec : dict + Top-level Vega specification + scope : tuple of int + Scope tuple. If empty, the names of top-level datasets are returned + Otherwise, the names of the datasets defined in the nested group mark + at the specified scope are returned. + + Returns + ------- + list of str + List of the names of the datasets defined at the specified scope + + Examples + -------- + >>> spec = { + ... "data": [{"name": "data1"}], + ... "marks": [ + ... { + ... "type": "group", + ... "data": [{"name": "data2"}], + ... "marks": [{"type": "symbol"}], + ... }, + ... { + ... "type": "group", + ... "data": [ + ... {"name": "data3"}, + ... {"name": "data4"}, + ... ], + ... "marks": [{"type": "rect"}], + ... }, + ... ], + ... } + + >>> get_datasets_for_scope(spec, ()) + ['data1'] + + >>> get_datasets_for_scope(spec, (0,)) + ['data2'] + + >>> get_datasets_for_scope(spec, (1,)) + ['data3', 'data4'] + + Returns empty when no group mark exists at scope + >>> get_datasets_for_scope(spec, (1, 3)) + [] + """ + group = get_group_mark_for_scope(vega_spec, scope) or {} + + # get datasets from group + datasets = [] + for dataset in group.get("data", []): + datasets.append(dataset["name"]) + + # Add facet dataset + facet_dataset = group.get("from", {}).get("facet", {}).get("name", None) + if facet_dataset: + datasets.append(facet_dataset) + return datasets + + +def get_definition_scope_for_data_reference( + vega_spec: dict[str, Any], data_name: str, usage_scope: Scope +) -> Scope | None: + """ + Return the scope that a dataset is defined at, for a given usage scope. + + Parameters + ---------- + vega_spec: dict + Top-level Vega specification + data_name: str + The name of a dataset reference + usage_scope: tuple of int + The scope that the dataset is referenced in + + Returns + ------- + tuple of int + The scope where the referenced dataset is defined, + or None if no such dataset is found + + Examples + -------- + >>> spec = { + ... "data": [{"name": "data1"}], + ... "marks": [ + ... { + ... "type": "group", + ... "data": [{"name": "data2"}], + ... "marks": [ + ... { + ... "type": "symbol", + ... "encode": { + ... "update": { + ... "x": {"field": "x", "data": "data1"}, + ... "y": {"field": "y", "data": "data2"}, + ... } + ... }, + ... } + ... ], + ... } + ... ], + ... } + + data1 is referenced at scope [0] and defined at scope [] + >>> get_definition_scope_for_data_reference(spec, "data1", (0,)) + () + + data2 is referenced at scope [0] and defined at scope [0] + >>> get_definition_scope_for_data_reference(spec, "data2", (0,)) + (0,) + + If data2 is not visible at scope [] (the top level), + because it's defined in scope [0] + >>> repr(get_definition_scope_for_data_reference(spec, "data2", ())) + 'None' + """ + for i in reversed(range(len(usage_scope) + 1)): + scope = usage_scope[:i] + datasets = get_datasets_for_scope(vega_spec, scope) + if data_name in datasets: + return scope + return None + + +def get_facet_mapping(group: dict[str, Any], scope: Scope = ()) -> FacetMapping: + """ + Create mapping from facet definitions to source datasets. + + Parameters + ---------- + group : dict + Top-level Vega spec or nested group mark + scope : tuple of int + Scope of the group dictionary within a top-level Vega spec + + Returns + ------- + dict + Dictionary from (facet_name, facet_scope) to (dataset_name, dataset_scope) + + Examples + -------- + >>> spec = { + ... "data": [{"name": "data1"}], + ... "marks": [ + ... { + ... "type": "group", + ... "from": { + ... "facet": { + ... "name": "facet1", + ... "data": "data1", + ... "groupby": ["colA"], + ... } + ... }, + ... } + ... ], + ... } + >>> get_facet_mapping(spec) + {('facet1', (0,)): ('data1', ())} + """ + facet_mapping = {} + group_index = 0 + mark_group = get_group_mark_for_scope(group, scope) or {} + for mark in mark_group.get("marks", []): + if mark.get("type", None) == "group": + # Get facet for this group + group_scope = (*scope, group_index) + facet = mark.get("from", {}).get("facet", None) + if facet is not None: + facet_name = facet.get("name", None) + facet_data = facet.get("data", None) + if facet_name is not None and facet_data is not None: + definition_scope = get_definition_scope_for_data_reference( + group, facet_data, scope + ) + if definition_scope is not None: + facet_mapping[facet_name, group_scope] = ( + facet_data, + definition_scope, + ) + + # Handle children recursively + child_mapping = get_facet_mapping(group, scope=group_scope) + facet_mapping.update(child_mapping) + group_index += 1 + + return facet_mapping + + +def get_from_facet_mapping( + scoped_dataset: tuple[str, Scope], facet_mapping: FacetMapping +) -> tuple[str, Scope]: + """ + Apply facet mapping to a scoped dataset. + + Parameters + ---------- + scoped_dataset : (str, tuple of int) + A dataset name and scope tuple + facet_mapping : dict from (str, tuple of int) to (str, tuple of int) + The facet mapping produced by get_facet_mapping + + Returns + ------- + (str, tuple of int) + Dataset name and scope tuple that has been mapped as many times as possible + + Examples + -------- + Facet mapping as produced by get_facet_mapping + >>> facet_mapping = { + ... ("facet1", (0,)): ("data1", ()), + ... ("facet2", (0, 1)): ("facet1", (0,)), + ... } + >>> get_from_facet_mapping(("facet2", (0, 1)), facet_mapping) + ('data1', ()) + """ + while scoped_dataset in facet_mapping: + scoped_dataset = facet_mapping[scoped_dataset] + return scoped_dataset + + +def get_datasets_for_view_names( + group: dict[str, Any], + vl_chart_names: list[str], + facet_mapping: FacetMapping, + scope: Scope = (), +) -> dict[str, tuple[str, Scope]]: + """ + Get the Vega datasets that correspond to the provided Altair view names. + + Parameters + ---------- + group : dict + Top-level Vega spec or nested group mark + vl_chart_names : list of str + List of the Vega-Lite + facet_mapping : dict from (str, tuple of int) to (str, tuple of int) + The facet mapping produced by get_facet_mapping + scope : tuple of int + Scope of the group dictionary within a top-level Vega spec + + Returns + ------- + dict from str to (str, tuple of int) + Dict from Altair view names to scoped datasets + """ + datasets = {} + group_index = 0 + mark_group = get_group_mark_for_scope(group, scope) or {} + for mark in mark_group.get("marks", []): + for vl_chart_name in vl_chart_names: + if mark.get("name", "") == f"{vl_chart_name}_cell": + data_name = mark.get("from", {}).get("facet", None).get("data", None) + scoped_data_name = (data_name, scope) + datasets[vl_chart_name] = get_from_facet_mapping( + scoped_data_name, facet_mapping + ) + break + + name = mark.get("name", "") + if mark.get("type", "") == "group": + group_data_names = get_datasets_for_view_names( + group, vl_chart_names, facet_mapping, scope=(*scope, group_index) + ) + for k, v in group_data_names.items(): + datasets.setdefault(k, v) + group_index += 1 + else: + for vl_chart_name in vl_chart_names: + if name.startswith(vl_chart_name) and name.endswith("_marks"): + data_name = mark.get("from", {}).get("data", None) + scoped_data = get_definition_scope_for_data_reference( + group, data_name, scope + ) + if scoped_data is not None: + datasets[vl_chart_name] = get_from_facet_mapping( + (data_name, scoped_data), facet_mapping + ) + break + + return datasets diff --git a/.venv/lib/python3.13/site-packages/altair/utils/_vegafusion_data.py b/.venv/lib/python3.13/site-packages/altair/utils/_vegafusion_data.py new file mode 100644 index 0000000000000000000000000000000000000000..2b09a8999a7d8b53d45dc318219838ee3e84b7db --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/utils/_vegafusion_data.py @@ -0,0 +1,304 @@ +from __future__ import annotations + +import uuid +from importlib.metadata import version as importlib_version +from typing import TYPE_CHECKING, Any, Final, TypedDict, Union, overload +from weakref import WeakValueDictionary + +from narwhals.stable.v1.dependencies import is_into_dataframe +from packaging.version import Version + +from altair.utils._importers import import_vegafusion +from altair.utils.core import DataFrameLike +from altair.utils.data import ( + DataType, + MaxRowsError, + SupportsGeoInterface, + ToValuesReturnType, +) +from altair.vegalite.data import default_data_transformer + +if TYPE_CHECKING: + import sys + from collections.abc import Callable, MutableMapping + + from narwhals.stable.v1.typing import IntoDataFrame + + from vegafusion.runtime import ChartState + + if sys.version_info >= (3, 13): + from typing import TypeIs + else: + from typing_extensions import TypeIs + +# Temporary storage for dataframes that have been extracted +# from charts by the vegafusion data transformer. Use a WeakValueDictionary +# rather than a dict so that the Python interpreter is free to garbage +# collect the stored DataFrames. +extracted_inline_tables: MutableMapping[str, DataFrameLike] = WeakValueDictionary() + +# Special URL prefix that VegaFusion uses to denote that a +# dataset in a Vega spec corresponds to an entry in the `inline_datasets` +# kwarg of vf.runtime.pre_transform_spec(). +VEGAFUSION_PREFIX: Final = "vegafusion+dataset://" + + +try: + VEGAFUSION_VERSION: Version | None = Version(importlib_version("vegafusion")) +except ImportError: + VEGAFUSION_VERSION = None + + +if VEGAFUSION_VERSION and Version("2.0.0a0") <= VEGAFUSION_VERSION: + + def is_supported_by_vf(data: Any) -> TypeIs[DataFrameLike]: + # Test whether VegaFusion supports the data type + # VegaFusion v2 support narwhals-compatible DataFrames + return isinstance(data, DataFrameLike) or is_into_dataframe(data) + +else: + + def is_supported_by_vf(data: Any) -> TypeIs[DataFrameLike]: + return isinstance(data, DataFrameLike) + + +class _ToVegaFusionReturnUrlDict(TypedDict): + url: str + + +_VegaFusionReturnType = Union[_ToVegaFusionReturnUrlDict, ToValuesReturnType] + + +@overload +def vegafusion_data_transformer( + data: None = ..., max_rows: int = ... +) -> Callable[..., Any]: ... + + +@overload +def vegafusion_data_transformer( + data: DataFrameLike, max_rows: int = ... +) -> ToValuesReturnType: ... + + +@overload +def vegafusion_data_transformer( + data: dict | IntoDataFrame | SupportsGeoInterface, max_rows: int = ... +) -> _VegaFusionReturnType: ... + + +def vegafusion_data_transformer( + data: DataType | None = None, max_rows: int = 100000 +) -> Callable[..., Any] | _VegaFusionReturnType: + """VegaFusion Data Transformer.""" + if data is None: + return vegafusion_data_transformer + + if is_supported_by_vf(data) and not isinstance(data, SupportsGeoInterface): + table_name = f"table_{uuid.uuid4()}".replace("-", "_") + extracted_inline_tables[table_name] = data + return {"url": VEGAFUSION_PREFIX + table_name} + else: + # Use default transformer for geo interface objects + # # (e.g. a geopandas GeoDataFrame) + # Or if we don't recognize data type + return default_data_transformer(data) + + +def get_inline_table_names(vega_spec: dict[str, Any]) -> set[str]: + """ + Get a set of the inline datasets names in the provided Vega spec. + + Inline datasets are encoded as URLs that start with the table:// + prefix. + + Parameters + ---------- + vega_spec: dict + A Vega specification dict + + Returns + ------- + set of str + Set of the names of the inline datasets that are referenced + in the specification. + + Examples + -------- + >>> spec = { + ... "data": [ + ... {"name": "foo", "url": "https://path/to/file.csv"}, + ... {"name": "bar", "url": "vegafusion+dataset://inline_dataset_123"}, + ... ] + ... } + >>> get_inline_table_names(spec) + {'inline_dataset_123'} + """ + table_names = set() + + # Process datasets + for data in vega_spec.get("data", []): + url = data.get("url", "") + if url.startswith(VEGAFUSION_PREFIX): + name = url[len(VEGAFUSION_PREFIX) :] + table_names.add(name) + + # Recursively process child marks, which may have their own datasets + for mark in vega_spec.get("marks", []): + table_names.update(get_inline_table_names(mark)) + + return table_names + + +def get_inline_tables(vega_spec: dict[str, Any]) -> dict[str, DataFrameLike]: + """ + Get the inline tables referenced by a Vega specification. + + Note: This function should only be called on a Vega spec that corresponds + to a chart that was processed by the vegafusion_data_transformer. + Furthermore, this function may only be called once per spec because + the returned dataframes are deleted from internal storage. + + Parameters + ---------- + vega_spec: dict + A Vega specification dict + + Returns + ------- + dict from str to dataframe + dict from inline dataset name to dataframe object + """ + inline_names = get_inline_table_names(vega_spec) + # exclude named dataset that was provided by the user, + # or dataframes that have been deleted. + table_names = inline_names.intersection(extracted_inline_tables) + return {k: extracted_inline_tables.pop(k) for k in table_names} + + +def compile_to_vegafusion_chart_state( + vegalite_spec: dict[str, Any], local_tz: str +) -> ChartState: + """ + Compile a Vega-Lite spec to a VegaFusion ChartState. + + Note: This function should only be called on a Vega-Lite spec + that was generated with the "vegafusion" data transformer enabled. + In particular, this spec may contain references to extract datasets + using table:// prefixed URLs. + + Parameters + ---------- + vegalite_spec: dict + A Vega-Lite spec that was generated from an Altair chart with + the "vegafusion" data transformer enabled + local_tz: str + Local timezone name (e.g. 'America/New_York') + + Returns + ------- + ChartState + A VegaFusion ChartState object + """ + # Local import to avoid circular ImportError + from altair import data_transformers, vegalite_compilers + + vf = import_vegafusion() + + # Compile Vega-Lite spec to Vega + compiler = vegalite_compilers.get() + if compiler is None: + msg = "No active vega-lite compiler plugin found" + raise ValueError(msg) + + vega_spec = compiler(vegalite_spec) + + # Retrieve dict of inline tables referenced by the spec + inline_tables = get_inline_tables(vega_spec) + + # Pre-evaluate transforms in vega spec with vegafusion + row_limit = data_transformers.options.get("max_rows", None) + + chart_state = vf.runtime.new_chart_state( + vega_spec, + local_tz=local_tz, + inline_datasets=inline_tables, + row_limit=row_limit, + ) + + # Check from row limit warning and convert to MaxRowsError + handle_row_limit_exceeded(row_limit, chart_state.get_warnings()) + + return chart_state + + +def compile_with_vegafusion(vegalite_spec: dict[str, Any]) -> dict[str, Any]: + """ + Compile a Vega-Lite spec to Vega and pre-transform with VegaFusion. + + Note: This function should only be called on a Vega-Lite spec + that was generated with the "vegafusion" data transformer enabled. + In particular, this spec may contain references to extract datasets + using table:// prefixed URLs. + + Parameters + ---------- + vegalite_spec: dict + A Vega-Lite spec that was generated from an Altair chart with + the "vegafusion" data transformer enabled + + Returns + ------- + dict + A Vega spec that has been pre-transformed by VegaFusion + """ + # Local import to avoid circular ImportError + from altair import data_transformers, vegalite_compilers + + vf = import_vegafusion() + + # Compile Vega-Lite spec to Vega + compiler = vegalite_compilers.get() + if compiler is None: + msg = "No active vega-lite compiler plugin found" + raise ValueError(msg) + + vega_spec = compiler(vegalite_spec) + + # Retrieve dict of inline tables referenced by the spec + inline_tables = get_inline_tables(vega_spec) + + # Pre-evaluate transforms in vega spec with vegafusion + row_limit = data_transformers.options.get("max_rows", None) + transformed_vega_spec, warnings = vf.runtime.pre_transform_spec( + vega_spec, + vf.get_local_tz(), + inline_datasets=inline_tables, + row_limit=row_limit, + ) + + # Check from row limit warning and convert to MaxRowsError + handle_row_limit_exceeded(row_limit, warnings) + + return transformed_vega_spec + + +def handle_row_limit_exceeded(row_limit: int | None, warnings: list): + for warning in warnings: + if warning.get("type") == "RowLimitExceeded": + msg = ( + "The number of dataset rows after filtering and aggregation exceeds\n" + f"the current limit of {row_limit}. Try adding an aggregation to reduce\n" + "the size of the dataset that must be loaded into the browser. Or, disable\n" + "the limit by calling alt.data_transformers.disable_max_rows(). Note that\n" + "disabling this limit may cause the browser to freeze or crash." + ) + raise MaxRowsError(msg) + + +def using_vegafusion() -> bool: + """Check whether the vegafusion data transformer is enabled.""" + # Local import to avoid circular ImportError + from altair import data_transformers + + return data_transformers.active == "vegafusion" diff --git a/.venv/lib/python3.13/site-packages/altair/utils/compiler.py b/.venv/lib/python3.13/site-packages/altair/utils/compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..417c8d440e49498877b694b88a5486710b8085e5 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/utils/compiler.py @@ -0,0 +1,13 @@ +from collections.abc import Callable +from typing import Any + +from altair.utils import PluginRegistry + +# ============================================================================== +# Vega-Lite to Vega compiler registry +# ============================================================================== +VegaLiteCompilerType = Callable[[dict[str, Any]], dict[str, Any]] + + +class VegaLiteCompilerRegistry(PluginRegistry[VegaLiteCompilerType, dict[str, Any]]): + pass diff --git a/.venv/lib/python3.13/site-packages/altair/utils/core.py b/.venv/lib/python3.13/site-packages/altair/utils/core.py new file mode 100644 index 0000000000000000000000000000000000000000..16e19514bdfe25ced3ae16ad996c77028c6d887b --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/utils/core.py @@ -0,0 +1,981 @@ +"""Utility routines.""" + +from __future__ import annotations + +import itertools +import json +import re +import sys +import traceback +import warnings +from collections.abc import Callable, Iterator, Mapping, MutableMapping +from copy import deepcopy +from itertools import groupby +from operator import itemgetter +from typing import TYPE_CHECKING, Any, Literal, TypeVar, cast, overload + +import jsonschema +import narwhals.stable.v1 as nw +from narwhals.stable.v1.dependencies import is_pandas_dataframe, is_polars_dataframe +from narwhals.stable.v1.typing import IntoDataFrame + +from altair.utils.schemapi import SchemaBase, SchemaLike, Undefined + +if sys.version_info >= (3, 12): + from typing import Protocol, TypeAliasType, runtime_checkable +else: + from typing_extensions import Protocol, TypeAliasType, runtime_checkable +if sys.version_info >= (3, 10): + from typing import Concatenate, ParamSpec +else: + from typing_extensions import Concatenate, ParamSpec + + +if TYPE_CHECKING: + import pandas as pd + from narwhals.stable.v1.typing import IntoExpr + + from altair.utils._dfi_types import DataFrame as DfiDataFrame + from altair.vegalite.v6.schema._typing import StandardType_T as InferredVegaLiteType + + _PandasDataFrameT = TypeVar("_PandasDataFrameT", bound="pd.DataFrame") + +TIntoDataFrame = TypeVar("TIntoDataFrame", bound=IntoDataFrame) +T = TypeVar("T") +P = ParamSpec("P") +R = TypeVar("R") + +WrapsFunc = TypeAliasType("WrapsFunc", Callable[..., R], type_params=(R,)) +WrappedFunc = TypeAliasType("WrappedFunc", Callable[P, R], type_params=(P, R)) +# NOTE: Requires stringized form to avoid `< (3, 11)` issues +# See: https://github.com/vega/altair/actions/runs/10667859416/job/29567290871?pr=3565 +WrapsMethod = TypeAliasType( + "WrapsMethod", "Callable[Concatenate[T, ...], R]", type_params=(T, R) +) +WrappedMethod = TypeAliasType( + "WrappedMethod", Callable[Concatenate[T, P], R], type_params=(T, P, R) +) + + +@runtime_checkable +class DataFrameLike(Protocol): + def __dataframe__( + self, nan_as_null: bool = False, allow_copy: bool = True + ) -> DfiDataFrame: ... + + +TYPECODE_MAP = { + "ordinal": "O", + "nominal": "N", + "quantitative": "Q", + "temporal": "T", + "geojson": "G", +} + +INV_TYPECODE_MAP = {v: k for k, v in TYPECODE_MAP.items()} + + +# aggregates from vega-lite version 4.6.0 +AGGREGATES = [ + "argmax", + "argmin", + "average", + "count", + "distinct", + "max", + "mean", + "median", + "min", + "missing", + "product", + "q1", + "q3", + "ci0", + "ci1", + "stderr", + "stdev", + "stdevp", + "sum", + "valid", + "values", + "variance", + "variancep", + "exponential", + "exponentialb", +] + +# window aggregates from vega-lite version 4.6.0 +WINDOW_AGGREGATES = [ + "row_number", + "rank", + "dense_rank", + "percent_rank", + "cume_dist", + "ntile", + "lag", + "lead", + "first_value", + "last_value", + "nth_value", +] + +# timeUnits from vega-lite version 4.17.0 +TIMEUNITS = [ + "year", + "quarter", + "month", + "week", + "day", + "dayofyear", + "date", + "hours", + "minutes", + "seconds", + "milliseconds", + "yearquarter", + "yearquartermonth", + "yearmonth", + "yearmonthdate", + "yearmonthdatehours", + "yearmonthdatehoursminutes", + "yearmonthdatehoursminutesseconds", + "yearweek", + "yearweekday", + "yearweekdayhours", + "yearweekdayhoursminutes", + "yearweekdayhoursminutesseconds", + "yeardayofyear", + "quartermonth", + "monthdate", + "monthdatehours", + "monthdatehoursminutes", + "monthdatehoursminutesseconds", + "weekday", + "weeksdayhours", + "weekdayhours", + "weekdayhoursminutes", + "weekdayhoursminutesseconds", + "dayhours", + "dayhoursminutes", + "dayhoursminutesseconds", + "hoursminutes", + "hoursminutesseconds", + "minutesseconds", + "secondsmilliseconds", + "utcyear", + "utcquarter", + "utcmonth", + "utcweek", + "utcday", + "utcdayofyear", + "utcdate", + "utchours", + "utcminutes", + "utcseconds", + "utcmilliseconds", + "utcyearquarter", + "utcyearquartermonth", + "utcyearmonth", + "utcyearmonthdate", + "utcyearmonthdatehours", + "utcyearmonthdatehoursminutes", + "utcyearmonthdatehoursminutesseconds", + "utcyearweek", + "utcyearweekday", + "utcyearweekdayhours", + "utcyearweekdayhoursminutes", + "utcyearweekdayhoursminutesseconds", + "utcyeardayofyear", + "utcquartermonth", + "utcmonthdate", + "utcmonthdatehours", + "utcmonthdatehoursminutes", + "utcmonthdatehoursminutesseconds", + "utcweekday", + "utcweekdayhours", + "utcweekdayhoursminutes", + "utcweekdayhoursminutesseconds", + "utcdayhours", + "utcdayhoursminutes", + "utcdayhoursminutesseconds", + "utchoursminutes", + "utchoursminutesseconds", + "utcminutesseconds", + "utcsecondsmilliseconds", +] + +VALID_TYPECODES = list(itertools.chain(iter(TYPECODE_MAP), iter(INV_TYPECODE_MAP))) + +SHORTHAND_UNITS = { + "field": "(?P.*)", + "type": "(?P{})".format("|".join(VALID_TYPECODES)), + "agg_count": "(?Pcount)", + "op_count": "(?Pcount)", + "aggregate": "(?P{})".format("|".join(AGGREGATES)), + "window_op": "(?P{})".format("|".join(AGGREGATES + WINDOW_AGGREGATES)), + "timeUnit": "(?P{})".format("|".join(TIMEUNITS)), +} + +SHORTHAND_KEYS: frozenset[Literal["field", "aggregate", "type", "timeUnit"]] = ( + frozenset(("field", "aggregate", "type", "timeUnit")) +) + + +def infer_vegalite_type_for_pandas( + data: Any, +) -> InferredVegaLiteType | tuple[InferredVegaLiteType, list[Any]]: + """ + From an array-like input, infer the correct vega typecode. + + ('ordinal', 'nominal', 'quantitative', or 'temporal'). + + Parameters + ---------- + data: Any + """ + # This is safe to import here, as this function is only called on pandas input. + from pandas.api.types import infer_dtype + + typ = infer_dtype(data, skipna=False) + + if typ in { + "floating", + "mixed-integer-float", + "integer", + "mixed-integer", + "complex", + }: + return "quantitative" + elif typ == "categorical" and hasattr(data, "cat") and data.cat.ordered: + return ("ordinal", data.cat.categories.tolist()) + elif typ in {"string", "bytes", "categorical", "boolean", "mixed", "unicode"}: + return "nominal" + elif typ in { + "datetime", + "datetime64", + "timedelta", + "timedelta64", + "date", + "time", + "period", + }: + return "temporal" + else: + warnings.warn( + f"I don't know how to infer vegalite type from '{typ}'. " + "Defaulting to nominal.", + stacklevel=1, + ) + return "nominal" + + +def merge_props_geom(feat: dict[str, Any]) -> dict[str, Any]: + """ + Merge properties with geometry. + + * Overwrites 'type' and 'geometry' entries if existing. + """ + geom = {k: feat[k] for k in ("type", "geometry")} + try: + feat["properties"].update(geom) + props_geom = feat["properties"] + except (AttributeError, KeyError): + # AttributeError when 'properties' equals None + # KeyError when 'properties' is non-existing + props_geom = geom + + return props_geom + + +def sanitize_geo_interface(geo: MutableMapping[Any, Any]) -> dict[str, Any]: + """ + Sanitize a geo_interface to prepare it for serialization. + + * Make a copy + * Convert type array or _Array to list + * Convert tuples to lists (using json.loads/dumps) + * Merge properties with geometry + """ + geo = deepcopy(geo) + + # convert type _Array or array to list + for key in geo: + if str(type(geo[key]).__name__).startswith(("_Array", "array")): + geo[key] = geo[key].tolist() + + # convert (nested) tuples to lists + geo_dct: dict = json.loads(json.dumps(geo)) + + # sanitize features + if geo_dct["type"] == "FeatureCollection": + geo_dct = geo_dct["features"] + if len(geo_dct) > 0: + for idx, feat in enumerate(geo_dct): + geo_dct[idx] = merge_props_geom(feat) + elif geo_dct["type"] == "Feature": + geo_dct = merge_props_geom(geo_dct) + else: + geo_dct = {"type": "Feature", "geometry": geo_dct} + + return geo_dct + + +def numpy_is_subtype(dtype: Any, subtype: Any) -> bool: + # This is only called on `numpy` inputs, so it's safe to import it here. + import numpy as np + + try: + return cast("bool", np.issubdtype(dtype, subtype)) + except (NotImplementedError, TypeError): + return False + + +def sanitize_pandas_dataframe(df: _PandasDataFrameT) -> _PandasDataFrameT: # noqa: C901 + """ + Sanitize a DataFrame to prepare it for serialization. + + * Make a copy + * Convert RangeIndex columns to strings + * Raise ValueError if column names are not strings + * Raise ValueError if it has a hierarchical index. + * Convert categoricals to strings. + * Convert np.bool_ dtypes to Python bool objects + * Convert np.int dtypes to Python int objects + * Convert floats to objects and replace NaNs/infs with None. + * Convert DateTime dtypes into appropriate string representations + * Convert Nullable integers to objects and replace NaN with None + * Convert Nullable boolean to objects and replace NaN with None + * convert dedicated string column to objects and replace NaN with None + * Raise a ValueError for TimeDelta dtypes + """ + # This is safe to import here, as this function is only called on pandas input. + # NumPy is a required dependency of pandas so is also safe to import. + import numpy as np + import pandas as pd + + df = cast("_PandasDataFrameT", df.copy()) + + if isinstance(df.columns, pd.RangeIndex): + df.columns = df.columns.astype(str) + + for col_name in df.columns: + if not isinstance(col_name, str): + msg = ( + f"Dataframe contains invalid column name: {col_name!r}. " + "Column names must be strings" + ) + raise ValueError(msg) + + if isinstance(df.index, pd.MultiIndex): + msg = "Hierarchical indices not supported" + raise ValueError(msg) + if isinstance(df.columns, pd.MultiIndex): + msg = "Hierarchical indices not supported" + raise ValueError(msg) + + def to_list_if_array(val): + if isinstance(val, np.ndarray): + return val.tolist() + else: + return val + + for dtype_item in df.dtypes.items(): + # We know that the column names are strings from the isinstance check + # further above but mypy thinks it is of type Hashable and therefore does not + # let us assign it to the col_name variable which is already of type str. + col_name = cast("str", dtype_item[0]) + dtype = dtype_item[1] + dtype_name = str(dtype) + if dtype_name == "category": + # Work around bug in to_json for categorical types in older versions + # of pandas as they do not properly convert NaN values to null in to_json. + # We can probably remove this part once we require pandas >= 1.0 + col = df[col_name].astype(object) + df[col_name] = col.where(col.notnull(), None) + elif dtype_name == "string": + # dedicated string datatype (since 1.0) + # https://pandas.pydata.org/pandas-docs/version/1.0.0/whatsnew/v1.0.0.html#dedicated-string-data-type + col = df[col_name].astype(object) + df[col_name] = col.where(col.notnull(), None) + elif dtype_name == "bool": + # convert numpy bools to objects; np.bool is not JSON serializable + df[col_name] = df[col_name].astype(object) + elif dtype_name == "boolean": + # dedicated boolean datatype (since 1.0) + # https://pandas.io/docs/user_guide/boolean.html + col = df[col_name].astype(object) + df[col_name] = col.where(col.notnull(), None) + elif dtype_name.startswith(("datetime", "timestamp")): + # Convert datetimes to strings. This needs to be a full ISO string + # with time, which is why we cannot use ``col.astype(str)``. + # This is because Javascript parses date-only times in UTC, but + # parses full ISO-8601 dates as local time, and dates in Vega and + # Vega-Lite are displayed in local time by default. + # (see https://github.com/vega/altair/issues/1027) + df[col_name] = ( + df[col_name].apply(lambda x: x.isoformat()).replace("NaT", "") + ) + elif dtype_name.startswith("timedelta"): + msg = ( + f'Field "{col_name}" has type "{dtype}" which is ' + "not supported by Altair. Please convert to " + "either a timestamp or a numerical value." + "" + ) + raise ValueError(msg) + elif dtype_name.startswith("geometry"): + # geopandas >=0.6.1 uses the dtype geometry. Continue here + # otherwise it will give an error on np.issubdtype(dtype, np.integer) + continue + elif ( + dtype_name + in { + "Int8", + "Int16", + "Int32", + "Int64", + "UInt8", + "UInt16", + "UInt32", + "UInt64", + "Float32", + "Float64", + } + ): # nullable integer datatypes (since 24.0) and nullable float datatypes (since 1.2.0) + # https://pandas.pydata.org/pandas-docs/version/0.25/whatsnew/v0.24.0.html#optional-integer-na-support + col = df[col_name].astype(object) + df[col_name] = col.where(col.notnull(), None) + elif numpy_is_subtype(dtype, np.integer): + # convert integers to objects; np.int is not JSON serializable + df[col_name] = df[col_name].astype(object) + elif numpy_is_subtype(dtype, np.floating): + # For floats, convert to Python float: np.float is not JSON serializable + # Also convert NaN/inf values to null, as they are not JSON serializable + col = df[col_name] + bad_values = col.isnull() | np.isinf(col) + df[col_name] = col.astype(object).where(~bad_values, None) + elif dtype == object: # noqa: E721 + # Convert numpy arrays saved as objects to lists + # Arrays are not JSON serializable + col = df[col_name].astype(object).apply(to_list_if_array) + df[col_name] = col.where(col.notnull(), None) + return df + + +def sanitize_narwhals_dataframe( + data: nw.DataFrame[TIntoDataFrame], +) -> nw.DataFrame[TIntoDataFrame]: + """Sanitize narwhals.DataFrame for JSON serialization.""" + schema = data.schema + columns: list[IntoExpr] = [] + # See https://github.com/vega/altair/issues/1027 for why this is necessary. + local_iso_fmt_string = "%Y-%m-%dT%H:%M:%S" + is_polars = is_polars_dataframe(data.to_native()) + for name, dtype in schema.items(): + if dtype == nw.Date and is_polars: + # Polars doesn't allow formatting `Date` with time directives. + # The date -> datetime cast is extremely fast compared with `to_string` + columns.append( + nw.col(name).cast(nw.Datetime).dt.to_string(local_iso_fmt_string) + ) + elif dtype == nw.Date: + columns.append(nw.col(name).dt.to_string(local_iso_fmt_string)) + elif dtype == nw.Datetime: + columns.append(nw.col(name).dt.to_string(f"{local_iso_fmt_string}%.f")) + elif dtype == nw.Duration: + msg = ( + f'Field "{name}" has type "{dtype}" which is ' + "not supported by Altair. Please convert to " + "either a timestamp or a numerical value." + "" + ) + raise ValueError(msg) + else: + columns.append(name) + return data.select(columns) + + +def to_eager_narwhals_dataframe(data: IntoDataFrame) -> nw.DataFrame[Any]: + """ + Wrap `data` in `narwhals.DataFrame`. + + If `data` is not supported by Narwhals, but it is convertible + to a PyArrow table, then first convert to a PyArrow Table, + and then wrap in `narwhals.DataFrame`. + """ + data_nw = nw.from_native(data, eager_or_interchange_only=True) + if nw.get_level(data_nw) == "interchange": + # If Narwhals' support for `data`'s class is only metadata-level, then we + # use the interchange protocol to convert to a PyArrow Table. + from altair.utils.data import arrow_table_from_dfi_dataframe + + pa_table = arrow_table_from_dfi_dataframe(data) # type: ignore[arg-type] + data_nw = nw.from_native(pa_table, eager_only=True) + return data_nw + + +def parse_shorthand( # noqa: C901 + shorthand: dict[str, Any] | str, + data: IntoDataFrame | None = None, + parse_aggregates: bool = True, + parse_window_ops: bool = False, + parse_timeunits: bool = True, + parse_types: bool = True, +) -> dict[str, Any]: + """ + General tool to parse shorthand values. + + These are of the form: + + - "col_name" + - "col_name:O" + - "average(col_name)" + - "average(col_name):O" + + Optionally, a dataframe may be supplied, from which the type + will be inferred if not specified in the shorthand. + + Parameters + ---------- + shorthand : dict or string + The shorthand representation to be parsed + data : DataFrame, optional + If specified and of type DataFrame, then use these values to infer the + column type if not provided by the shorthand. + parse_aggregates : boolean + If True (default), then parse aggregate functions within the shorthand. + parse_window_ops : boolean + If True then parse window operations within the shorthand (default:False) + parse_timeunits : boolean + If True (default), then parse timeUnits from within the shorthand + parse_types : boolean + If True (default), then parse typecodes within the shorthand + + Returns + ------- + attrs : dict + a dictionary of attributes extracted from the shorthand + + Examples + -------- + >>> import pandas as pd + >>> data = pd.DataFrame({"foo": ["A", "B", "A", "B"], "bar": [1, 2, 3, 4]}) + + >>> parse_shorthand("name") == {"field": "name"} + True + + >>> parse_shorthand("name:Q") == {"field": "name", "type": "quantitative"} + True + + >>> parse_shorthand("average(col)") == {"aggregate": "average", "field": "col"} + True + + >>> parse_shorthand("foo:O") == {"field": "foo", "type": "ordinal"} + True + + >>> parse_shorthand("min(foo):Q") == { + ... "aggregate": "min", + ... "field": "foo", + ... "type": "quantitative", + ... } + True + + >>> parse_shorthand("month(col)") == { + ... "field": "col", + ... "timeUnit": "month", + ... "type": "temporal", + ... } + True + + >>> parse_shorthand("year(col):O") == { + ... "field": "col", + ... "timeUnit": "year", + ... "type": "ordinal", + ... } + True + + >>> parse_shorthand("foo", data) == {"field": "foo", "type": "nominal"} + True + + >>> parse_shorthand("bar", data) == {"field": "bar", "type": "quantitative"} + True + + >>> parse_shorthand("bar:O", data) == {"field": "bar", "type": "ordinal"} + True + + >>> parse_shorthand("sum(bar)", data) == { + ... "aggregate": "sum", + ... "field": "bar", + ... "type": "quantitative", + ... } + True + + >>> parse_shorthand("count()", data) == { + ... "aggregate": "count", + ... "type": "quantitative", + ... } + True + """ + from altair.utils.data import is_data_type + + if not shorthand: + return {} + + patterns = [] + + if parse_aggregates: + patterns.extend([r"{agg_count}\(\)"]) + patterns.extend([r"{aggregate}\({field}\)"]) + if parse_window_ops: + patterns.extend([r"{op_count}\(\)"]) + patterns.extend([r"{window_op}\({field}\)"]) + if parse_timeunits: + patterns.extend([r"{timeUnit}\({field}\)"]) + + patterns.extend([r"{field}"]) + + if parse_types: + patterns = list(itertools.chain(*((p + ":{type}", p) for p in patterns))) + + regexps = ( + re.compile(r"\A" + p.format(**SHORTHAND_UNITS) + r"\Z", re.DOTALL) + for p in patterns + ) + + # find matches depending on valid fields passed + if isinstance(shorthand, dict): + attrs = shorthand + else: + attrs = next( + exp.match(shorthand).groupdict() # type: ignore[union-attr] + for exp in regexps + if exp.match(shorthand) is not None + ) + + # Handle short form of the type expression + if "type" in attrs: + attrs["type"] = INV_TYPECODE_MAP.get(attrs["type"], attrs["type"]) + + # counts are quantitative by default + if attrs == {"aggregate": "count"}: + attrs["type"] = "quantitative" + + # times are temporal by default + if "timeUnit" in attrs and "type" not in attrs: + attrs["type"] = "temporal" + + # if data is specified and type is not, infer type from data + if "type" not in attrs and is_data_type(data): + unescaped_field = attrs["field"].replace("\\", "") + data_nw = nw.from_native(data, eager_or_interchange_only=True) + schema = data_nw.schema + if unescaped_field in schema: + column = data_nw[unescaped_field] + if schema[unescaped_field] in { + nw.Object, + nw.Unknown, + } and is_pandas_dataframe(data_nw.to_native()): + attrs["type"] = infer_vegalite_type_for_pandas(column.to_native()) + else: + attrs["type"] = infer_vegalite_type_for_narwhals(column) + if isinstance(attrs["type"], tuple): + attrs["sort"] = attrs["type"][1] + attrs["type"] = attrs["type"][0] + + # If an unescaped colon is still present, it's often due to an incorrect data type specification + # but could also be due to using a column name with ":" in it. + if ( + "field" in attrs + and ":" in attrs["field"] + and attrs["field"][attrs["field"].rfind(":") - 1] != "\\" + ): + raise ValueError( + '"{}" '.format(attrs["field"].split(":")[-1]) + + "is not one of the valid encoding data types: {}.".format( + ", ".join(TYPECODE_MAP.values()) + ) + + "\nFor more details, see https://altair-viz.github.io/user_guide/encodings/index.html#encoding-data-types. " + + "If you are trying to use a column name that contains a colon, " + + 'prefix it with a backslash; for example "column\\:name" instead of "column:name".' + ) + return attrs + + +def infer_vegalite_type_for_narwhals( + column: nw.Series, +) -> InferredVegaLiteType | tuple[InferredVegaLiteType, list]: + dtype = column.dtype + if ( + nw.is_ordered_categorical(column) + and not (categories := column.cat.get_categories()).is_empty() + ): + return "ordinal", categories.to_list() + if dtype == nw.String or dtype == nw.Categorical or dtype == nw.Boolean: # noqa: PLR1714 + return "nominal" + elif dtype.is_numeric(): + return "quantitative" + elif dtype == nw.Datetime or dtype == nw.Date: # noqa: PLR1714 + # We use `== nw.Datetime` to check for any kind of Datetime, regardless of time + # unit and time zone. Prefer this over `dtype in {nw.Datetime, nw.Date}`, + # see https://narwhals-dev.github.io/narwhals/backcompat. + return "temporal" + else: + msg = f"Unexpected DtypeKind: {dtype}" + raise ValueError(msg) + + +def use_signature(tp: Callable[P, Any], /): + """ + Use the signature and doc of ``tp`` for the decorated callable ``cb``. + + - **Overload 1**: Decorating method + - **Overload 2**: Decorating function + + Returns + ------- + **Adding the annotation breaks typing**: + + Overload[Callable[[WrapsMethod[T, R]], WrappedMethod[T, P, R]], Callable[[WrapsFunc[R]], WrappedFunc[P, R]]] + """ + + @overload + def decorate(cb: WrapsMethod[T, R], /) -> WrappedMethod[T, P, R]: ... # pyright: ignore[reportOverlappingOverload] + + @overload + def decorate(cb: WrapsFunc[R], /) -> WrappedFunc[P, R]: ... # pyright: ignore[reportOverlappingOverload] + + def decorate(cb: WrapsFunc[R], /) -> WrappedMethod[T, P, R] | WrappedFunc[P, R]: + """ + Raises when no doc was found. + + Notes + ----- + - Reference to ``tp`` is stored in ``cb.__wrapped__``. + - The doc for ``cb`` will have a ``.rst`` link added, referring to ``tp``. + """ + cb.__wrapped__ = getattr(tp, "__init__", tp) # type: ignore[attr-defined] + + if doc_in := tp.__doc__: + line_1 = f"{cb.__doc__ or f'Refer to :class:`{tp.__name__}`'}\n" + cb.__doc__ = "".join((line_1, *doc_in.splitlines(keepends=True)[1:])) + return cb + else: + msg = f"Found no doc for {tp!r}" + raise AttributeError(msg) + + return decorate + + +@overload +def update_nested( + original: MutableMapping[Any, Any], + update: Mapping[Any, Any], + copy: Literal[False] = ..., +) -> MutableMapping[Any, Any]: ... +@overload +def update_nested( + original: Mapping[Any, Any], + update: Mapping[Any, Any], + copy: Literal[True], +) -> MutableMapping[Any, Any]: ... +def update_nested( + original: Any, + update: Mapping[Any, Any], + copy: bool = False, +) -> MutableMapping[Any, Any]: + """ + Update nested dictionaries. + + Parameters + ---------- + original : MutableMapping + the original (nested) dictionary, which will be updated in-place + update : Mapping + the nested dictionary of updates + copy : bool, default False + if True, then copy the original dictionary rather than modifying it + + Returns + ------- + original : MutableMapping + a reference to the (modified) original dict + + Examples + -------- + >>> original = {"x": {"b": 2, "c": 4}} + >>> update = {"x": {"b": 5, "d": 6}, "y": 40} + >>> update_nested(original, update) # doctest: +SKIP + {'x': {'b': 5, 'c': 4, 'd': 6}, 'y': 40} + >>> original # doctest: +SKIP + {'x': {'b': 5, 'c': 4, 'd': 6}, 'y': 40} + """ + if copy: + original = deepcopy(original) + for key, val in update.items(): + if isinstance(val, Mapping): + orig_val = original.get(key, {}) + if isinstance(orig_val, MutableMapping): + original[key] = update_nested(orig_val, val) + else: + original[key] = val + else: + original[key] = val + return original + + +def display_traceback(in_ipython: bool = True): + exc_info = sys.exc_info() + + if in_ipython: + from IPython.core.getipython import get_ipython + + ip = get_ipython() + else: + ip = None + + if ip is not None: + ip.showtraceback(exc_info) + else: + traceback.print_exception(*exc_info) + + +_ChannelType = Literal["field", "datum", "value"] +_CHANNEL_CACHE: _ChannelCache +"""Singleton `_ChannelCache` instance. + +Initialized on first use. +""" + + +class _ChannelCache: + channel_to_name: dict[type[SchemaBase], str] + name_to_channel: dict[str, dict[_ChannelType, type[SchemaBase]]] + + @classmethod + def from_cache(cls) -> _ChannelCache: + global _CHANNEL_CACHE + try: + cached = _CHANNEL_CACHE + except NameError: + cached = cls.__new__(cls) + cached.channel_to_name = _init_channel_to_name() # pyright: ignore[reportAttributeAccessIssue] + cached.name_to_channel = _invert_group_channels(cached.channel_to_name) + _CHANNEL_CACHE = cached + return _CHANNEL_CACHE + + def get_encoding(self, tp: type[Any], /) -> str: + if encoding := self.channel_to_name.get(tp): + return encoding + msg = f"positional of type {type(tp).__name__!r}" + raise NotImplementedError(msg) + + def _wrap_in_channel(self, obj: Any, encoding: str, /): + if isinstance(obj, SchemaBase): + return obj + elif isinstance(obj, str): + obj = {"shorthand": obj} + elif isinstance(obj, (list, tuple)): + return [self._wrap_in_channel(el, encoding) for el in obj] + elif isinstance(obj, SchemaLike): + obj = obj.to_dict() + if channel := self.name_to_channel.get(encoding): + tp = channel["value" if "value" in obj else "field"] + try: + # Don't force validation here; some objects won't be valid until + # they're created in the context of a chart. + return tp.from_dict(obj, validate=False) + except jsonschema.ValidationError: + # our attempts at finding the correct class have failed + return obj + else: + warnings.warn(f"Unrecognized encoding channel {encoding!r}", stacklevel=1) + return obj + + def infer_encoding_types(self, kwargs: dict[str, Any], /): + return { + encoding: self._wrap_in_channel(obj, encoding) + for encoding, obj in kwargs.items() + if obj is not Undefined + } + + +def _init_channel_to_name(): + """ + Construct a dictionary of channel type to encoding name. + + Note + ---- + The return type is not expressible using annotations, but is used + internally by `mypy`/`pyright` and avoids the need for type ignores. + + Returns + ------- + mapping: dict[type[``] | type[``] | type[``], str] + """ + from altair.vegalite.v6.schema import channels as ch + + mixins = ch.FieldChannelMixin, ch.ValueChannelMixin, ch.DatumChannelMixin + + return { + c: c._encoding_name + for c in ch.__dict__.values() + if isinstance(c, type) and issubclass(c, mixins) and issubclass(c, SchemaBase) + } + + +def _invert_group_channels( + m: dict[type[SchemaBase], str], / +) -> dict[str, dict[_ChannelType, type[SchemaBase]]]: + """Grouped inverted index for `_ChannelCache.channel_to_name`.""" + + def _reduce(it: Iterator[tuple[type[Any], str]]) -> Any: + """ + Returns a 1-2 item dict, per channel. + + Never includes `datum`, as it is never utilized in `wrap_in_channel`. + """ + item: dict[Any, type[SchemaBase]] = {} + for tp, _ in it: + name = tp.__name__ + if name.endswith("Datum"): + continue + elif name.endswith("Value"): + sub_key = "value" + else: + sub_key = "field" + item[sub_key] = tp + return item + + grouper = groupby(m.items(), itemgetter(1)) + return {k: _reduce(chans) for k, chans in grouper} + + +def infer_encoding_types(args: tuple[Any, ...], kwargs: dict[str, Any]): + """ + Infer typed keyword arguments for args and kwargs. + + Parameters + ---------- + args : Sequence + Sequence of function args + kwargs : MutableMapping + Dict of function kwargs + + Returns + ------- + kwargs : dict + All args and kwargs in a single dict, with keys and types + based on the channels mapping. + """ + cache = _ChannelCache.from_cache() + # First use the mapping to convert args to kwargs based on their types. + for arg in args: + el = next(iter(arg), None) if isinstance(arg, (list, tuple)) else arg + encoding = cache.get_encoding(type(el)) + if encoding not in kwargs: + kwargs[encoding] = arg + else: + msg = f"encoding {encoding!r} specified twice." + raise ValueError(msg) + + return cache.infer_encoding_types(kwargs) diff --git a/.venv/lib/python3.13/site-packages/altair/utils/data.py b/.venv/lib/python3.13/site-packages/altair/utils/data.py new file mode 100644 index 0000000000000000000000000000000000000000..5efa778b0f69d101122924e749f3771e9e1d5ceb --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/utils/data.py @@ -0,0 +1,435 @@ +from __future__ import annotations + +import hashlib +import json +import random +import sys +from collections.abc import Callable, MutableMapping, Sequence +from functools import partial +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal, TypedDict, TypeVar, Union, overload + +import narwhals.stable.v1 as nw +from narwhals.stable.v1.dependencies import is_pandas_dataframe +from narwhals.stable.v1.typing import IntoDataFrame + +from ._importers import import_pyarrow_interchange +from .core import ( + DataFrameLike, + sanitize_geo_interface, + sanitize_narwhals_dataframe, + sanitize_pandas_dataframe, + to_eager_narwhals_dataframe, +) +from .plugin_registry import PluginRegistry + +if sys.version_info >= (3, 13): + from typing import Protocol, runtime_checkable +else: + from typing_extensions import Protocol, runtime_checkable +if sys.version_info >= (3, 10): + from typing import Concatenate, ParamSpec +else: + from typing_extensions import Concatenate, ParamSpec + +if TYPE_CHECKING: + if sys.version_info >= (3, 13): + from typing import TypeIs + else: + from typing_extensions import TypeIs + + if sys.version_info >= (3, 10): + from typing import TypeAlias + else: + from typing_extensions import TypeAlias + import pandas as pd + import pyarrow as pa + + +@runtime_checkable +class SupportsGeoInterface(Protocol): + __geo_interface__: MutableMapping + + +DataType: TypeAlias = Union[ + dict[Any, Any], IntoDataFrame, SupportsGeoInterface, DataFrameLike +] + +TDataType = TypeVar("TDataType", bound=DataType) +TIntoDataFrame = TypeVar("TIntoDataFrame", bound=IntoDataFrame) + +VegaLiteDataDict: TypeAlias = dict[ + str, Union[str, dict[Any, Any], list[dict[Any, Any]]] +] +ToValuesReturnType: TypeAlias = dict[str, Union[dict[Any, Any], list[dict[Any, Any]]]] +SampleReturnType = Union[IntoDataFrame, dict[str, Sequence], None] + + +def is_data_type(obj: Any) -> TypeIs[DataType]: + return isinstance(obj, (dict, SupportsGeoInterface)) or isinstance( + nw.from_native(obj, eager_or_interchange_only=True, pass_through=True), + nw.DataFrame, + ) + + +# ============================================================================== +# Data transformer registry +# +# A data transformer is a callable that takes a supported data type and returns +# a transformed dictionary version of it which is compatible with the VegaLite schema. +# The dict objects will be the Data portion of the VegaLite schema. +# +# Renderers only deal with the dict form of a +# VegaLite spec, after the Data model has been put into a schema compliant +# form. +# ============================================================================== + +P = ParamSpec("P") +# NOTE: `Any` required due to the complexity of existing signatures imported in `altair.vegalite.v6.data.py` +R = TypeVar("R", VegaLiteDataDict, Any) +DataTransformerType = Callable[Concatenate[DataType, P], R] + + +class DataTransformerRegistry(PluginRegistry[DataTransformerType, R]): + _global_settings = {"consolidate_datasets": True} + + @property + def consolidate_datasets(self) -> bool: + return self._global_settings["consolidate_datasets"] + + @consolidate_datasets.setter + def consolidate_datasets(self, value: bool) -> None: + self._global_settings["consolidate_datasets"] = value + + +# ============================================================================== +class MaxRowsError(Exception): + """Raised when a data model has too many rows.""" + + def __init__(self, message: str, /) -> None: + self.message = message + super().__init__(self.message) + + @classmethod + def from_limit_rows(cls, user_rows: int, max_rows: int, /) -> MaxRowsError: + msg = ( + f"The number of rows in your dataset ({user_rows}) is greater " + f"than the maximum allowed ({max_rows}).\n\n" + "Try enabling the VegaFusion data transformer which " + "raises this limit by pre-evaluating data\n" + "transformations in Python.\n" + " >> import altair as alt\n" + ' >> alt.data_transformers.enable("vegafusion")\n\n' + "Or, see https://altair-viz.github.io/user_guide/large_datasets.html " + "for additional information\n" + "on how to plot large datasets." + ) + return cls(msg) + + +@overload +def limit_rows(data: None = ..., max_rows: int | None = ...) -> partial: ... +@overload +def limit_rows(data: DataType, max_rows: int | None = ...) -> DataType: ... +def limit_rows( + data: DataType | None = None, max_rows: int | None = 5000 +) -> partial | DataType: + """ + Raise MaxRowsError if the data model has more than max_rows. + + If max_rows is None, then do not perform any check. + """ + if data is None: + return partial(limit_rows, max_rows=max_rows) + check_data_type(data) + + if isinstance(data, SupportsGeoInterface): + if data.__geo_interface__["type"] == "FeatureCollection": + values = data.__geo_interface__["features"] + else: + values = data.__geo_interface__ + elif isinstance(data, dict): + if "values" in data: + values = data["values"] + else: + return data + else: + data = to_eager_narwhals_dataframe(data) + values = data + + n = len(values) + if max_rows is not None and n > max_rows: + raise MaxRowsError.from_limit_rows(n, max_rows) + + return data + + +@overload +def sample( + data: None = ..., n: int | None = ..., frac: float | None = ... +) -> partial: ... +@overload +def sample( + data: TIntoDataFrame, n: int | None = ..., frac: float | None = ... +) -> TIntoDataFrame: ... +@overload +def sample( + data: DataType, n: int | None = ..., frac: float | None = ... +) -> SampleReturnType: ... +def sample( + data: DataType | None = None, + n: int | None = None, + frac: float | None = None, +) -> partial | SampleReturnType: + """Reduce the size of the data model by sampling without replacement.""" + if data is None: + return partial(sample, n=n, frac=frac) + check_data_type(data) + if is_pandas_dataframe(data): + return data.sample(n=n, frac=frac) + elif isinstance(data, dict): + if "values" in data: + values = data["values"] + if not n: + if frac is None: + msg = "frac cannot be None if n is None and data is a dictionary" + raise ValueError(msg) + n = int(frac * len(values)) + values = random.sample(values, n) + return {"values": values} + else: + # Maybe this should raise an error or return something useful? + return None + data = nw.from_native(data, eager_only=True) + if not n: + if frac is None: + msg = "frac cannot be None if n is None with this data input type" + raise ValueError(msg) + n = int(frac * len(data)) + indices = random.sample(range(len(data)), n) + return data[indices].to_native() + + +_FormatType = Literal["csv", "json"] + + +class _FormatDict(TypedDict): + type: _FormatType + + +class _ToFormatReturnUrlDict(TypedDict): + url: str + format: _FormatDict + + +@overload +def to_json( + data: None = ..., + prefix: str = ..., + extension: str = ..., + filename: str = ..., + urlpath: str = ..., +) -> partial: ... + + +@overload +def to_json( + data: DataType, + prefix: str = ..., + extension: str = ..., + filename: str = ..., + urlpath: str = ..., +) -> _ToFormatReturnUrlDict: ... + + +def to_json( + data: DataType | None = None, + prefix: str = "altair-data", + extension: str = "json", + filename: str = "{prefix}-{hash}.{extension}", + urlpath: str = "", +) -> partial | _ToFormatReturnUrlDict: + """Write the data model to a .json file and return a url based data model.""" + kwds = _to_text_kwds(prefix, extension, filename, urlpath) + if data is None: + return partial(to_json, **kwds) + else: + data_str = _data_to_json_string(data) + return _to_text(data_str, **kwds, format=_FormatDict(type="json")) + + +@overload +def to_csv( + data: None = ..., + prefix: str = ..., + extension: str = ..., + filename: str = ..., + urlpath: str = ..., +) -> partial: ... + + +@overload +def to_csv( + data: dict | pd.DataFrame | DataFrameLike, + prefix: str = ..., + extension: str = ..., + filename: str = ..., + urlpath: str = ..., +) -> _ToFormatReturnUrlDict: ... + + +def to_csv( + data: dict | pd.DataFrame | DataFrameLike | None = None, + prefix: str = "altair-data", + extension: str = "csv", + filename: str = "{prefix}-{hash}.{extension}", + urlpath: str = "", +) -> partial | _ToFormatReturnUrlDict: + """Write the data model to a .csv file and return a url based data model.""" + kwds = _to_text_kwds(prefix, extension, filename, urlpath) + if data is None: + return partial(to_csv, **kwds) + else: + data_str = _data_to_csv_string(data) + return _to_text(data_str, **kwds, format=_FormatDict(type="csv")) + + +def _to_text( + data: str, + prefix: str, + extension: str, + filename: str, + urlpath: str, + format: _FormatDict, +) -> _ToFormatReturnUrlDict: + data_hash = _compute_data_hash(data) + filename = filename.format(prefix=prefix, hash=data_hash, extension=extension) + Path(filename).write_text(data, encoding="utf-8") + url = str(Path(urlpath, filename)) + return _ToFormatReturnUrlDict({"url": url, "format": format}) + + +def _to_text_kwds(prefix: str, extension: str, filename: str, urlpath: str, /) -> dict[str, str]: # fmt: skip + return {"prefix": prefix, "extension": extension, "filename": filename, "urlpath": urlpath} # fmt: skip + + +def to_values(data: DataType) -> ToValuesReturnType: + """Replace a DataFrame by a data model with values.""" + check_data_type(data) + # `pass_through=True` passes `data` through as-is if it is not a Narwhals object. + data_native = nw.to_native(data, pass_through=True) + if isinstance(data_native, SupportsGeoInterface): + return {"values": _from_geo_interface(data_native)} + elif is_pandas_dataframe(data_native): + data_native = sanitize_pandas_dataframe(data_native) + return {"values": data_native.to_dict(orient="records")} + elif isinstance(data_native, dict): + if "values" not in data_native: + msg = "values expected in data dict, but not present." + raise KeyError(msg) + return data_native + elif isinstance(data, nw.DataFrame): + data = sanitize_narwhals_dataframe(data) + return {"values": data.rows(named=True)} + else: + # Should never reach this state as tested by check_data_type + msg = f"Unrecognized data type: {type(data)}" + raise ValueError(msg) + + +def check_data_type(data: DataType) -> None: + if not is_data_type(data): + msg = f"Expected dict, DataFrame or a __geo_interface__ attribute, got: {type(data)}" + raise TypeError(msg) + + +# ============================================================================== +# Private utilities +# ============================================================================== +def _compute_data_hash(data_str: str) -> str: + return hashlib.sha256(data_str.encode()).hexdigest()[:32] + + +def _from_geo_interface(data: SupportsGeoInterface) -> dict[str, Any]: + """ + Sanitize a ``__geo_interface__`` w/ pre-sanitize step for ``pandas`` if needed. + + Introduces an intersection type:: + + geo: | SupportsGeoInterface + """ + geo = sanitize_pandas_dataframe(data) if is_pandas_dataframe(data) else data + return sanitize_geo_interface(geo.__geo_interface__) + + +def _data_to_json_string(data: DataType) -> str: + """Return a JSON string representation of the input data.""" + check_data_type(data) + if isinstance(data, SupportsGeoInterface): + return json.dumps(_from_geo_interface(data)) + elif is_pandas_dataframe(data): + data = sanitize_pandas_dataframe(data) + return data.to_json(orient="records", double_precision=15) + elif isinstance(data, dict): + if "values" not in data: + msg = "values expected in data dict, but not present." + raise KeyError(msg) + return json.dumps(data["values"], sort_keys=True) + try: + data_nw = nw.from_native(data, eager_only=True) + except TypeError as exc: + msg = "to_json only works with data expressed as a DataFrame or as a dict" + raise NotImplementedError(msg) from exc + data_nw = sanitize_narwhals_dataframe(data_nw) + return json.dumps(data_nw.rows(named=True)) + + +def _data_to_csv_string(data: DataType) -> str: + """Return a CSV string representation of the input data.""" + check_data_type(data) + if isinstance(data, SupportsGeoInterface): + msg = ( + f"to_csv does not yet work with data that " + f"is of type {type(SupportsGeoInterface).__name__!r}.\n" + f"See https://github.com/vega/altair/issues/3441" + ) + raise NotImplementedError(msg) + elif is_pandas_dataframe(data): + data = sanitize_pandas_dataframe(data) + return data.to_csv(index=False) + elif isinstance(data, dict): + if "values" not in data: + msg = "values expected in data dict, but not present" + raise KeyError(msg) + try: + import pandas as pd + except ImportError as exc: + msg = "pandas is required to convert a dict to a CSV string" + raise ImportError(msg) from exc + return pd.DataFrame.from_dict(data["values"]).to_csv(index=False) + try: + data_nw = nw.from_native(data, eager_only=True) + except TypeError as exc: + msg = "to_csv only works with data expressed as a DataFrame or as a dict" + raise NotImplementedError(msg) from exc + return data_nw.write_csv() + + +def arrow_table_from_dfi_dataframe(dfi_df: DataFrameLike) -> pa.Table: + """Convert a DataFrame Interchange Protocol compatible object to an Arrow Table.""" + import pyarrow as pa + + # First check if the dataframe object has a method to convert to arrow. + # Give this preference over the pyarrow from_dataframe function since the object + # has more control over the conversion, and may have broader compatibility. + # This is the case for Polars, which supports Date32 columns in direct conversion + # while pyarrow does not yet support this type in from_dataframe + for convert_method_name in ("arrow", "to_arrow", "to_arrow_table", "to_pyarrow"): + convert_method = getattr(dfi_df, convert_method_name, None) + if callable(convert_method): + result = convert_method() + if isinstance(result, pa.Table): + return result + + pi = import_pyarrow_interchange() + return pi.from_dataframe(dfi_df) diff --git a/.venv/lib/python3.13/site-packages/altair/utils/deprecation.py b/.venv/lib/python3.13/site-packages/altair/utils/deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..2b07a229e5fe285ed49cd0dbec12fded3e66a8d1 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/utils/deprecation.py @@ -0,0 +1,196 @@ +from __future__ import annotations + +import sys +import threading +import warnings +from typing import TYPE_CHECKING, Literal + +if sys.version_info >= (3, 13): + from warnings import deprecated as _deprecated +else: + from typing_extensions import deprecated as _deprecated + + +if TYPE_CHECKING: + if sys.version_info >= (3, 11): + from typing import LiteralString + else: + from typing_extensions import LiteralString + +__all__ = [ + "AltairDeprecationWarning", + "deprecated", + "deprecated_static_only", + "deprecated_warn", +] + + +class AltairDeprecationWarning(DeprecationWarning): ... + + +def _format_message( + version: LiteralString, + alternative: LiteralString | None, + message: LiteralString | None, + /, +) -> LiteralString: + output = f"\nDeprecated since `altair={version}`." + if alternative: + output = f"{output} Use {alternative} instead." + return f"{output}\n{message}" if message else output + + +# NOTE: Annotating the return type breaks `pyright` detecting [reportDeprecated] +# NOTE: `LiteralString` requirement is introduced by stubs +def deprecated( + *, + version: LiteralString, + alternative: LiteralString | None = None, + message: LiteralString | None = None, + category: type[AltairDeprecationWarning] | None = AltairDeprecationWarning, + stacklevel: int = 1, +): # te.deprecated + """ + Indicate that a class, function or overload is deprecated. + + When this decorator is applied to an object, the type checker + will generate a diagnostic on usage of the deprecated object. + + Parameters + ---------- + version + ``altair`` version the deprecation first appeared. + alternative + Suggested replacement class/method/function. + message + Additional message appended to ``version``, ``alternative``. + category + If the *category* is ``None``, no warning is emitted at runtime. + stacklevel + The *stacklevel* determines where the + warning is emitted. If it is ``1`` (the default), the warning + is emitted at the direct caller of the deprecated object; if it + is higher, it is emitted further up the stack. + Static type checker behavior is not affected by the *category* + and *stacklevel* arguments. + + References + ---------- + [PEP 702](https://peps.python.org/pep-0702/) + """ + msg = _format_message(version, alternative, message) + return _deprecated(msg, category=category, stacklevel=stacklevel) + + +def deprecated_warn( + message: LiteralString, + *, + version: LiteralString, + alternative: LiteralString | None = None, + category: type[AltairDeprecationWarning] = AltairDeprecationWarning, + stacklevel: int = 2, + action: Literal["once"] | None = None, +) -> None: + """ + Indicate that the current code path is deprecated. + + This should be used for non-trivial cases *only*. ``@deprecated`` should + always be preferred as it is recognized by static type checkers. + + Parameters + ---------- + message + Explanation of the deprecated behaviour. + + .. note:: + Unlike ``@deprecated``, this is *not* optional. + + version + ``altair`` version the deprecation first appeared. + alternative + Suggested replacement argument/method/function. + category + The runtime warning type emitted. + stacklevel + How far up the call stack to make this warning appear. + A value of ``2`` attributes the warning to the caller + of the code calling ``deprecated_warn()``. + + References + ---------- + [warnings.warn](https://docs.python.org/3/library/warnings.html#warnings.warn) + """ + msg = _format_message(version, alternative, message) + if action is None: + warnings.warn(msg, category=category, stacklevel=stacklevel) + elif action == "once": + _warn_once(msg, category=category, stacklevel=stacklevel) + else: + raise NotImplementedError(action) + + +deprecated_static_only = _deprecated +""" +Using this decorator **exactly as described**, ensures ``message`` is displayed to a static type checker. + +**BE CAREFUL USING THIS**. + +See screenshots in `comment`_ for motivation. + +Every use should look like:: + + @deprecated_static_only( + "Deprecated since `altair=5.5.0`. Use altair.other instead.", + category=None, + ) + def old_function(*args): ... + +If a runtime warning is desired, use `@alt.utils.deprecated` instead. + +Parameters +---------- +message : LiteralString + - **Not** a variable + - **Not** use placeholders + - **Not** use concatenation + - **Do not use anything that could be considered dynamic** + +category : None + You **need** to explicitly pass ``None`` + +.. _comment: + https://github.com/vega/altair/pull/3618#issuecomment-2423991968 +--- +""" + + +class _WarningsMonitor: + def __init__(self) -> None: + self._warned: dict[LiteralString, Literal[True]] = {} + self._lock = threading.Lock() + + def __contains__(self, key: LiteralString, /) -> bool: + with self._lock: + return key in self._warned + + def hit(self, key: LiteralString, /) -> None: + with self._lock: + self._warned[key] = True + + def clear(self) -> None: + with self._lock: + self._warned.clear() + + +_warnings_monitor = _WarningsMonitor() + + +def _warn_once( + msg: LiteralString, /, *, category: type[AltairDeprecationWarning], stacklevel: int +) -> None: + global _warnings_monitor + if msg in _warnings_monitor: + return + else: + _warnings_monitor.hit(msg) + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) diff --git a/.venv/lib/python3.13/site-packages/altair/utils/display.py b/.venv/lib/python3.13/site-packages/altair/utils/display.py new file mode 100644 index 0000000000000000000000000000000000000000..3de205d7452064c071b58e3cdf5b0e0fa11d3257 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/utils/display.py @@ -0,0 +1,233 @@ +from __future__ import annotations + +import json +import pkgutil +import textwrap +import uuid +from collections.abc import Callable +from typing import TYPE_CHECKING, Any, Union + +from ._vegafusion_data import compile_with_vegafusion, using_vegafusion +from .mimebundle import spec_to_mimebundle +from .plugin_registry import PluginEnabler, PluginRegistry +from .schemapi import validate_jsonschema + +if TYPE_CHECKING: + import sys + + if sys.version_info >= (3, 10): + from typing import TypeAlias + else: + from typing_extensions import TypeAlias + +# ============================================================================== +# Renderer registry +# ============================================================================== +# MimeBundleType needs to be the same as what are acceptable return values +# for _repr_mimebundle_, +# see https://ipython.readthedocs.io/en/stable/config/integrating.html#MyObject._repr_mimebundle_ +MimeBundleDataType: TypeAlias = dict[str, Any] +MimeBundleMetaDataType: TypeAlias = dict[str, Any] +MimeBundleType: TypeAlias = Union[ + MimeBundleDataType, tuple[MimeBundleDataType, MimeBundleMetaDataType] +] +RendererType: TypeAlias = Callable[..., MimeBundleType] +# Subtype of MimeBundleType as more specific in the values of the dictionaries + +DefaultRendererReturnType: TypeAlias = tuple[ + dict[str, Union[str, dict[str, Any]]], dict[str, dict[str, Any]] +] + + +class RendererRegistry(PluginRegistry[RendererType, MimeBundleType]): + entrypoint_err_messages = { + "notebook": textwrap.dedent( + """ + To use the 'notebook' renderer, you must install the vega package + and the associated Jupyter extension. + See https://altair-viz.github.io/getting_started/installation.html + for more information. + """ + ), + } + + def set_embed_options( + self, + defaultStyle: bool | str | None = None, + renderer: str | None = None, + width: int | None = None, + height: int | None = None, + padding: int | None = None, + scaleFactor: float | None = None, + actions: bool | dict[str, bool] | None = None, + format_locale: str | dict | None = None, + time_format_locale: str | dict | None = None, + **kwargs, + ) -> PluginEnabler: + """ + Set options for embeddings of Vega & Vega-Lite charts. + + Options are fully documented at https://github.com/vega/vega-embed. + Similar to the `enable()` method, this can be used as either + a persistent global switch, or as a temporary local setting using + a context manager (i.e. a `with` statement). + + Parameters + ---------- + defaultStyle : bool or string + Specify a default stylesheet for embed actions. + renderer : string + The renderer to use for the view. One of "canvas" (default) or "svg" + width : integer + The view width in pixels + height : integer + The view height in pixels + padding : integer + The view padding in pixels + scaleFactor : number + The number by which to multiply the width and height (default 1) + of an exported PNG or SVG image. + actions : bool or dict + Determines if action links ("Export as PNG/SVG", "View Source", + "View Vega" (only for Vega-Lite), "Open in Vega Editor") are + included with the embedded view. If the value is true, all action + links will be shown and none if the value is false. This property + can take a key-value mapping object that maps keys (export, source, + compiled, editor) to boolean values for determining if + each action link should be shown. + format_locale : str or dict + d3-format locale name or dictionary. Defaults to "en-US" for United States English. + See https://github.com/d3/d3-format/tree/main/locale for available names and example + definitions. + time_format_locale : str or dict + d3-time-format locale name or dictionary. Defaults to "en-US" for United States English. + See https://github.com/d3/d3-time-format/tree/main/locale for available names and example + definitions. + **kwargs : + Additional options are passed directly to embed options. + """ + options: dict[str, bool | str | float | dict[str, bool] | None] = { + "defaultStyle": defaultStyle, + "renderer": renderer, + "width": width, + "height": height, + "padding": padding, + "scaleFactor": scaleFactor, + "actions": actions, + "formatLocale": format_locale, + "timeFormatLocale": time_format_locale, + } + kwargs.update({key: val for key, val in options.items() if val is not None}) + return self.enable(None, embed_options=kwargs) + + +# ============================================================================== +# VegaLite v1/v2 renderer logic +# ============================================================================== + + +class Displayable: + """ + A base display class for VegaLite v1/v2. + + This class takes a VegaLite v1/v2 spec and does the following: + + 1. Optionally validates the spec against a schema. + 2. Uses the RendererPlugin to grab a renderer and call it when the + IPython/Jupyter display method (_repr_mimebundle_) is called. + + The spec passed to this class must be fully schema compliant and already + have the data portion of the spec fully processed and ready to serialize. + In practice, this means, the data portion of the spec should have been passed + through appropriate data model transformers. + """ + + renderers: RendererRegistry | None = None + schema_path = ("altair", "") + + def __init__(self, spec: dict[str, Any], validate: bool = False) -> None: + self.spec = spec + self.validate = validate + self._validate() + + def _validate(self) -> None: + """Validate the spec against the schema.""" + data = pkgutil.get_data(*self.schema_path) + assert data is not None + schema_dict: dict[str, Any] = json.loads(data.decode("utf-8")) + validate_jsonschema( + self.spec, + schema_dict, + ) + + def _repr_mimebundle_( + self, include: Any = None, exclude: Any = None + ) -> MimeBundleType: + """Return a MIME bundle for display in Jupyter frontends.""" + if self.renderers is not None: + renderer_func = self.renderers.get() + assert renderer_func is not None + return renderer_func(self.spec) + else: + return {} + + +def default_renderer_base( + spec: dict[str, Any], mime_type: str, str_repr: str, **options +) -> DefaultRendererReturnType: + """ + A default renderer for Vega or VegaLite that works for modern frontends. + + This renderer works with modern frontends (JupyterLab, nteract) that know + how to render the custom VegaLite MIME type listed above. + """ + # Local import to avoid circular ImportError + from altair.vegalite.v6.display import VEGA_MIME_TYPE, VEGALITE_MIME_TYPE + + assert isinstance(spec, dict) + bundle: dict[str, str | dict] = {} + metadata: dict[str, dict[str, Any]] = {} + + if using_vegafusion(): + spec = compile_with_vegafusion(spec) + + # Swap mimetype from Vega-Lite to Vega. + # If mimetype was JSON, leave it alone + if mime_type == VEGALITE_MIME_TYPE: + mime_type = VEGA_MIME_TYPE + + bundle[mime_type] = spec + bundle["text/plain"] = str_repr + if options: + metadata[mime_type] = options + return bundle, metadata + + +def json_renderer_base( + spec: dict[str, Any], str_repr: str, **options +) -> DefaultRendererReturnType: + """ + A renderer that returns a MIME type of application/json. + + In JupyterLab/nteract this is rendered as a nice JSON tree. + """ + return default_renderer_base( + spec, mime_type="application/json", str_repr=str_repr, **options + ) + + +class HTMLRenderer: + """Object to render charts as HTML, with a unique output div each time.""" + + def __init__(self, output_div: str = "altair-viz-{}", **kwargs) -> None: + self._output_div = output_div + self.kwargs = kwargs + + @property + def output_div(self) -> str: + return self._output_div.format(uuid.uuid4().hex) + + def __call__(self, spec: dict[str, Any], **metadata) -> dict[str, str]: + kwargs = self.kwargs.copy() + kwargs.update(**metadata, output_div=self.output_div) + return spec_to_mimebundle(spec, format="html", **kwargs) diff --git a/.venv/lib/python3.13/site-packages/altair/utils/execeval.py b/.venv/lib/python3.13/site-packages/altair/utils/execeval.py new file mode 100644 index 0000000000000000000000000000000000000000..36942122971c649e8ec799f3b8af1ee9ec880d5b --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/utils/execeval.py @@ -0,0 +1,99 @@ +from __future__ import annotations + +import ast +import sys +from typing import TYPE_CHECKING, Any, Literal, overload + +if TYPE_CHECKING: + from collections.abc import Callable + from os import PathLike + + from _typeshed import ReadableBuffer + + if sys.version_info >= (3, 11): + from typing import Self + else: + from typing_extensions import Self + + +class _CatchDisplay: + """Class to temporarily catch sys.displayhook.""" + + def __init__(self) -> None: + self.output: Any | None = None + + def __enter__(self) -> Self: + self.old_hook: Callable[[object], Any] = sys.displayhook + sys.displayhook = self + return self + + def __exit__(self, type, value, traceback) -> Literal[False]: + sys.displayhook = self.old_hook + # Returning False will cause exceptions to propagate + return False + + def __call__(self, output: Any) -> None: + self.output = output + + +@overload +def eval_block( + code: str | Any, + namespace: dict[str, Any] | None = ..., + filename: str | ReadableBuffer | PathLike[Any] = ..., + *, + strict: Literal[False] = ..., +) -> Any | None: ... +@overload +def eval_block( + code: str | Any, + namespace: dict[str, Any] | None = ..., + filename: str | ReadableBuffer | PathLike[Any] = ..., + *, + strict: Literal[True], +) -> Any: ... +def eval_block( + code: str | Any, + namespace: dict[str, Any] | None = None, + filename: str | ReadableBuffer | PathLike[Any] = "", + *, + strict: bool = False, +) -> Any | None: + """ + Execute a multi-line block of code in the given namespace. + + If the final statement in the code is an expression, return + the result of the expression. + + If ``strict``, raise a ``TypeError`` when the return value would be ``None``. + """ + tree = ast.parse(code, filename="", mode="exec") + if namespace is None: + namespace = {} + catch_display = _CatchDisplay() + + if isinstance(tree.body[-1], ast.Expr): + to_exec, to_eval = tree.body[:-1], tree.body[-1:] + else: + to_exec, to_eval = tree.body, [] + + for node in to_exec: + compiled = compile(ast.Module([node], []), filename=filename, mode="exec") + exec(compiled, namespace) + + with catch_display: + for node in to_eval: + compiled = compile( + ast.Interactive([node]), filename=filename, mode="single" + ) + exec(compiled, namespace) + + if strict: + output = catch_display.output + if output is None: + msg = f"Expected a non-None value but got {output!r}" + raise TypeError(msg) + else: + return output + else: + return catch_display.output diff --git a/.venv/lib/python3.13/site-packages/altair/utils/html.py b/.venv/lib/python3.13/site-packages/altair/utils/html.py new file mode 100644 index 0000000000000000000000000000000000000000..9dbd4807d96a044131554c738b102ed90aa93235 --- /dev/null +++ b/.venv/lib/python3.13/site-packages/altair/utils/html.py @@ -0,0 +1,411 @@ +from __future__ import annotations + +import json +from typing import Any, Literal + +import jinja2 + +from altair.utils._importers import import_vl_convert, vl_version_for_vl_convert + +TemplateName = Literal["standard", "universal", "inline", "olli"] +RenderMode = Literal["vega", "vega-lite"] + +HTML_TEMPLATE = jinja2.Template( + """ +{%- if fullhtml -%} + + + + +{%- endif %} + +{%- if not requirejs %} + + {%- if mode == 'vega-lite' %} + + {%- endif %} + +{%- endif %} +{%- if fullhtml %} +{%- if requirejs %} + + +{%- endif %} + + +{%- endif %} +
+ +{%- if fullhtml %} + + +{%- endif %} +""" +) + + +HTML_TEMPLATE_UNIVERSAL = jinja2.Template( + """ + +
+ +""" +) + + +# This is like the HTML_TEMPLATE template, but includes vega javascript inline +# so that the resulting file is not dependent on external resources. This was +# ported over from altair_saver. +# +# implies requirejs=False and full_html=True +INLINE_HTML_TEMPLATE = jinja2.Template( + """\ + + + + + + + + +
+ + + +""" +) + + +HTML_TEMPLATE_OLLI = jinja2.Template( + """ + +
+ +""" +) + + +TEMPLATES: dict[TemplateName, jinja2.Template] = { + "standard": HTML_TEMPLATE, + "universal": HTML_TEMPLATE_UNIVERSAL, + "inline": INLINE_HTML_TEMPLATE, + "olli": HTML_TEMPLATE_OLLI, +} + + +def spec_to_html( + spec: dict[str, Any], + mode: RenderMode, + vega_version: str | None, + vegaembed_version: str | None, + vegalite_version: str | None = None, + base_url: str = "https://cdn.jsdelivr.net/npm", + output_div: str = "vis", + embed_options: dict[str, Any] | None = None, + json_kwds: dict[str, Any] | None = None, + fullhtml: bool = True, + requirejs: bool = False, + template: jinja2.Template | TemplateName = "standard", +) -> str: + """ + Embed a Vega/Vega-Lite spec into an HTML page. + + Parameters + ---------- + spec : dict + a dictionary representing a vega-lite plot spec. + mode : string {'vega' | 'vega-lite'} + The rendering mode. This value is overridden by embed_options['mode'], + if it is present. + vega_version : string + For html output, the version of vega.js to use. + vegalite_version : string + For html output, the version of vegalite.js to use. + vegaembed_version : string + For html output, the version of vegaembed.js to use. + base_url : string (optional) + The base url from which to load the javascript libraries. + output_div : string (optional) + The id of the div element where the plot will be shown. + embed_options : dict (optional) + Dictionary of options to pass to the vega-embed script. Default + entry is {'mode': mode}. + json_kwds : dict (optional) + Dictionary of keywords to pass to json.dumps(). + fullhtml : boolean (optional) + If True (default) then return a full html page. If False, then return + an HTML snippet that can be embedded into an HTML page. + requirejs : boolean (optional) + If False (default) then load libraries from base_url using