diff --git a/.gitattributes b/.gitattributes index 314d7ac7355d32234f77bd2d8d83ce449fee521a..8d929094555c40cf13eeff52cf330722b2700977 100644 --- a/.gitattributes +++ b/.gitattributes @@ -528,3 +528,51 @@ pace_revision_1/.venv-pace/lib/python3.11/site-packages/fontTools/misc/bezierToo pace_revision_1/.venv-pace/lib/python3.11/site-packages/fontTools/pens/momentsPen.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text pace_revision_1/.venv-pace/lib/python3.11/site-packages/fontTools/qu2cu/qu2cu.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text pace_revision_1/.venv-pace/lib/python3.11/site-packages/fontTools/varLib/iup.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_C.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_conv.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_errors.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_npystrings.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_objects.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_proxy.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_selector.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/defs.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5a.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5ac.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5d.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5ds.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5f.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5fd.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5g.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5i.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5l.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5o.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5p.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5pl.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5r.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5s.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5t.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5z.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/utils.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libaec-187855bc.so.0.1.3 filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libhdf5-7d060e2f.so.310.5.1 filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libhdf5_hl-0ce065ed.so.310.0.6 filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/kiwisolver/_cext.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/_cm_listed.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/_mathtext.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/axis.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/backend_bases.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/cbook.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/collections.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/colors.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/figure.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/patches.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/pyplot.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/ticker.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/transforms.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/__pycache__/widgets.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/_c_internal_utils.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/_image.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/_path.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/_qhull.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +pace_revision_1/.venv-pace/lib/python3.11/site-packages/matplotlib/_tri.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/METADATA b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..369e66b1d0f65050a4b3d7541ed4fec1ad3cd069 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/METADATA @@ -0,0 +1,257 @@ +Metadata-Version: 2.4 +Name: fsspec +Version: 2026.7.0 +Summary: File-system specification +Project-URL: Changelog, https://filesystem-spec.readthedocs.io/en/latest/changelog.html +Project-URL: Documentation, https://filesystem-spec.readthedocs.io/en/latest/ +Project-URL: Homepage, https://github.com/fsspec/filesystem_spec +Maintainer-email: Martin Durant +License-Expression: BSD-3-Clause +License-File: LICENSE +Keywords: file +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Requires-Python: >=3.10 +Provides-Extra: abfs +Requires-Dist: adlfs; extra == 'abfs' +Provides-Extra: adl +Requires-Dist: adlfs; extra == 'adl' +Provides-Extra: arrow +Requires-Dist: pyarrow>=1; extra == 'arrow' +Provides-Extra: dask +Requires-Dist: dask; extra == 'dask' +Requires-Dist: distributed; extra == 'dask' +Provides-Extra: dev +Requires-Dist: pre-commit; extra == 'dev' +Requires-Dist: ruff>=0.5; extra == 'dev' +Provides-Extra: doc +Requires-Dist: numpydoc; extra == 'doc' +Requires-Dist: sphinx; extra == 'doc' +Requires-Dist: sphinx-design; extra == 'doc' +Requires-Dist: sphinx-rtd-theme; extra == 'doc' +Requires-Dist: yarl; extra == 'doc' +Provides-Extra: dropbox +Requires-Dist: dropbox; extra == 'dropbox' +Requires-Dist: dropboxdrivefs; extra == 'dropbox' +Requires-Dist: requests; extra == 'dropbox' +Provides-Extra: entrypoints +Provides-Extra: full +Requires-Dist: adlfs; extra == 'full' +Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'full' +Requires-Dist: dask; extra == 'full' +Requires-Dist: distributed; extra == 'full' +Requires-Dist: dropbox; extra == 'full' +Requires-Dist: dropboxdrivefs; extra == 'full' +Requires-Dist: fusepy; extra == 'full' +Requires-Dist: gcsfs>=2026.4.0; extra == 'full' +Requires-Dist: libarchive-c; extra == 'full' +Requires-Dist: ocifs; extra == 'full' +Requires-Dist: panel; extra == 'full' +Requires-Dist: paramiko; extra == 'full' +Requires-Dist: pyarrow>=1; extra == 'full' +Requires-Dist: pygit2; extra == 'full' +Requires-Dist: requests; extra == 'full' +Requires-Dist: s3fs>=2026.6.0; extra == 'full' +Requires-Dist: smbprotocol; extra == 'full' +Requires-Dist: tqdm; extra == 'full' +Provides-Extra: fuse +Requires-Dist: fusepy; extra == 'fuse' +Provides-Extra: gcs +Requires-Dist: gcsfs>=2026.4.0; extra == 'gcs' +Provides-Extra: git +Requires-Dist: pygit2; extra == 'git' +Provides-Extra: github +Requires-Dist: requests; extra == 'github' +Provides-Extra: gs +Requires-Dist: gcsfs>=2026.4.0; extra == 'gs' +Provides-Extra: gui +Requires-Dist: panel; extra == 'gui' +Provides-Extra: hdfs +Requires-Dist: pyarrow>=1; extra == 'hdfs' +Provides-Extra: http +Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'http' +Provides-Extra: libarchive +Requires-Dist: libarchive-c; extra == 'libarchive' +Provides-Extra: oci +Requires-Dist: ocifs; extra == 'oci' +Provides-Extra: s3 +Requires-Dist: s3fs>=2026.6.0; extra == 's3' +Provides-Extra: sftp +Requires-Dist: paramiko; extra == 'sftp' +Provides-Extra: smb +Requires-Dist: smbprotocol; extra == 'smb' +Provides-Extra: ssh +Requires-Dist: paramiko; extra == 'ssh' +Provides-Extra: test +Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test' +Requires-Dist: numpy; extra == 'test' +Requires-Dist: pytest; extra == 'test' +Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test' +Requires-Dist: pytest-benchmark; extra == 'test' +Requires-Dist: pytest-cov; extra == 'test' +Requires-Dist: pytest-mock; extra == 'test' +Requires-Dist: pytest-recording; extra == 'test' +Requires-Dist: pytest-rerunfailures; extra == 'test' +Requires-Dist: requests; extra == 'test' +Provides-Extra: test-downstream +Requires-Dist: aiobotocore<3.0.0,>=2.5.4; extra == 'test-downstream' +Requires-Dist: dask[dataframe,test]; extra == 'test-downstream' +Requires-Dist: moto[server]<5,>4; extra == 'test-downstream' +Requires-Dist: pytest-timeout; extra == 'test-downstream' +Requires-Dist: xarray; extra == 'test-downstream' +Provides-Extra: test-full +Requires-Dist: adlfs; extra == 'test-full' +Requires-Dist: aiohttp!=4.0.0a0,!=4.0.0a1; extra == 'test-full' +Requires-Dist: backports-zstd; (python_version < '3.14') and extra == 'test-full' +Requires-Dist: cloudpickle; extra == 'test-full' +Requires-Dist: dask; extra == 'test-full' +Requires-Dist: distributed; extra == 'test-full' +Requires-Dist: dropbox; extra == 'test-full' +Requires-Dist: dropboxdrivefs; extra == 'test-full' +Requires-Dist: fastparquet; extra == 'test-full' +Requires-Dist: fusepy; extra == 'test-full' +Requires-Dist: gcsfs>=2026.4.0; extra == 'test-full' +Requires-Dist: jinja2; extra == 'test-full' +Requires-Dist: kerchunk; extra == 'test-full' +Requires-Dist: libarchive-c; extra == 'test-full' +Requires-Dist: lz4; extra == 'test-full' +Requires-Dist: notebook; extra == 'test-full' +Requires-Dist: numpy; extra == 'test-full' +Requires-Dist: ocifs; extra == 'test-full' +Requires-Dist: pandas<3.0.0; extra == 'test-full' +Requires-Dist: panel; extra == 'test-full' +Requires-Dist: paramiko; extra == 'test-full' +Requires-Dist: pyarrow>=1; extra == 'test-full' +Requires-Dist: pyftpdlib; extra == 'test-full' +Requires-Dist: pygit2; extra == 'test-full' +Requires-Dist: pytest; extra == 'test-full' +Requires-Dist: pytest-asyncio!=0.22.0; extra == 'test-full' +Requires-Dist: pytest-benchmark; extra == 'test-full' +Requires-Dist: pytest-cov; extra == 'test-full' +Requires-Dist: pytest-mock; extra == 'test-full' +Requires-Dist: pytest-recording; extra == 'test-full' +Requires-Dist: pytest-rerunfailures; extra == 'test-full' +Requires-Dist: python-snappy; extra == 'test-full' +Requires-Dist: requests; extra == 'test-full' +Requires-Dist: s3fs>=2026.6.0; extra == 'test-full' +Requires-Dist: smbprotocol; extra == 'test-full' +Requires-Dist: tqdm; extra == 'test-full' +Requires-Dist: urllib3; extra == 'test-full' +Requires-Dist: zarr<3.2.0; extra == 'test-full' +Requires-Dist: zstandard; (python_version < '3.14') and extra == 'test-full' +Provides-Extra: tqdm +Requires-Dist: tqdm; extra == 'tqdm' +Description-Content-Type: text/markdown + +# filesystem_spec + +[![PyPI version](https://badge.fury.io/py/fsspec.svg)](https://pypi.python.org/pypi/fsspec/) +[![Anaconda-Server Badge](https://anaconda.org/conda-forge/fsspec/badges/version.svg)](https://anaconda.org/conda-forge/fsspec) +![Build](https://github.com/fsspec/filesystem_spec/workflows/CI/badge.svg) +[![Docs](https://readthedocs.org/projects/filesystem-spec/badge/?version=latest)](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest) + +A specification for pythonic filesystems. + +## Install + +```bash +pip install fsspec +``` + +would install the base fsspec. Various optionally supported features might require specification of custom +extra require, e.g. `pip install fsspec[ssh]` will install dependencies for `ssh` backends support. +Use `pip install fsspec[full]` for installation of all known extra dependencies. + +Up-to-date package also provided through conda-forge distribution: + +```bash +conda install -c conda-forge fsspec +``` + + +## Purpose + +To produce a template or specification for a file-system interface, that specific implementations should follow, +so that applications making use of them can rely on a common behaviour and not have to worry about the specific +internal implementation decisions with any given backend. Many such implementations are included in this package, +or in sister projects such as `s3fs` and `gcsfs`. + +In addition, if this is well-designed, then additional functionality, such as a key-value store or FUSE +mounting of the file-system implementation may be available for all implementations "for free". + +## Documentation + +Please refer to [RTD](https://filesystem-spec.readthedocs.io/en/latest/?badge=latest) + +## Develop + +fsspec uses GitHub Actions for CI. Environment files can be found +in the "ci/" directory. Note that the main environment is called "py38", +but it is expected that the version of python installed be adjustable at +CI runtime. For local use, pick a version suitable for you. + +```bash +# For a new environment (mamba / conda). +mamba create -n fsspec -c conda-forge python=3.10 -y +conda activate fsspec + +# Standard dev install with docs and tests. +pip install -e ".[dev,doc,test]" + +# Full tests except for downstream +pip install s3fs +pip uninstall s3fs +pip install -e .[dev,doc,test_full] +pip install s3fs --no-deps +pytest -v + +# Downstream tests. +sh install_s3fs.sh +# Windows powershell. +install_s3fs.sh +``` + +### Testing + +Tests can be run in the dev environment, if activated, via ``pytest fsspec``. + +The full fsspec suite requires a system-level docker, docker-compose, and fuse +installation. If only making changes to one backend implementation, it is +not generally necessary to run all tests locally. + +It is expected that contributors ensure that any change to fsspec does not +cause issues or regressions for either other fsspec-related packages such +as gcsfs and s3fs, nor for downstream users of fsspec. The "downstream" CI +run and corresponding environment file run a set of tests from the dask +test suite, and very minimal tests against pandas and zarr from the +test_downstream.py module in this repo. + +### Code Formatting + +fsspec uses [Black](https://black.readthedocs.io/en/stable) to ensure +a consistent code format throughout the project. +Run ``black fsspec`` from the root of the filesystem_spec repository to +auto-format your code. Additionally, many editors have plugins that will apply +``black`` as you edit files. ``black`` is included in the ``tox`` environments. + +Optionally, you may wish to setup [pre-commit hooks](https://pre-commit.com) to +automatically run ``black`` when you make a git commit. +Run ``pre-commit install --install-hooks`` from the root of the +filesystem_spec repository to setup pre-commit hooks. ``black`` will now be run +before you commit, reformatting any changed files. You can format without +committing via ``pre-commit run`` or skip these checks with ``git commit +--no-verify``. + +## Support + +Work on this repository is supported in part by: + +"Anaconda, Inc. - Advancing AI through open source." + +anaconda logo diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/RECORD b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..5ceee9158ddd0b439445fe117d1a6e7f6fa1d3ee --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/RECORD @@ -0,0 +1,61 @@ +fsspec-2026.7.0.dist-info/METADATA,sha256=iLFldYXeFOO7gqpSeKqVlbMKpMp06tBz2JUGFcgICZ0,10561 +fsspec-2026.7.0.dist-info/RECORD,, +fsspec-2026.7.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87 +fsspec-2026.7.0.dist-info/licenses/LICENSE,sha256=LcNUls5TpzB5FcAIqESq1T53K0mzTN0ARFBnaRQH7JQ,1513 +fsspec/__init__.py,sha256=xFcoHBD17fc5KamKUQAIA0rePGjLqIN1WBAd9NAoAi8,2111 +fsspec/_version.py,sha256=XYrsnKX7E2XNoSiwqs7ALMtioidXl8y8KSliz3pL7S0,526 +fsspec/archive.py,sha256=vM6t_lgV6lBWbBYwpm3S4ofBQFQxUPr5KkDQrrQcQro,2411 +fsspec/asyn.py,sha256=V1Kig3HVzgWwZ-VtUYhys3QfdmiWRLG7EcP1E1PwM6M,39105 +fsspec/caching.py,sha256=Glmc9tDtS8Ctp44sd7mJURJYq7sHkH_yD480q6IgbxE,34777 +fsspec/callbacks.py,sha256=BDIwLzK6rr_0V5ch557fSzsivCElpdqhXr5dZ9Te-EE,9210 +fsspec/compression.py,sha256=3v_Fe39gzRRWfaeXpzNjAGPqgTzmETYRCo3qHVqD3po,5132 +fsspec/config.py,sha256=mHKzAgjXa_LwqtO_VoTJJ568VqwYkbK3gUp4J6JZJp4,4238 +fsspec/conftest.py,sha256=uWfm_Qs5alPRxOhRpDfQ0-1jqSJ54pni4y96IxOREXM,3446 +fsspec/core.py,sha256=EapTTO4bGR9G12rC90FiaBRemMhqo0ypx3ZqXj1zVuk,24189 +fsspec/dircache.py,sha256=YzogWJrhEastHU7vWz-cJiJ7sdtLXFXhEpInGKd4EcM,2717 +fsspec/exceptions.py,sha256=pauSLDMxzTJMOjvX1WEUK0cMyFkrFxpWJsyFywav7A8,331 +fsspec/fuse.py,sha256=Q-3NOOyLqBfYa4Db5E19z_ZY36zzYHtIs1mOUasItBQ,10177 +fsspec/generic.py,sha256=-LIADa9qRN79bfa3Hl9m3HaN6rlU2GNivawLNmybqxE,13752 +fsspec/gui.py,sha256=CQ7QsrTpaDlWSLNOpwNoJc7khOcYXIZxmrAJN9bHWQU,14002 +fsspec/implementations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +fsspec/implementations/arrow.py,sha256=HSXhExZ3HKNkWEm6m36h2jrbVilt3u8MvJI60u1_6fU,9236 +fsspec/implementations/asyn_wrapper.py,sha256=3lfJkGs6D_AwRBdxTSYlL-RCVdaXBZ9Itys2P5o5Si0,3738 +fsspec/implementations/cache_mapper.py,sha256=W4wlxyPxZbSp9ItJ0pYRVBMh6bw9eFypgP6kUYuuiI4,2421 +fsspec/implementations/cache_metadata.py,sha256=EPhQV27lgPlYREYprDET1vcMed15pVNMit-Ta1ljoyE,7942 +fsspec/implementations/cached.py,sha256=A_QyiukZzVznBWSZgMXSLd6h6K7k-ueroqnsoVY4bZg,37134 +fsspec/implementations/chained.py,sha256=iGivpNaHUFjB_ea0-HAPhcmm6CL8qnDf270PSj7JwuE,680 +fsspec/implementations/dask.py,sha256=CXZbJzIVOhKV8ILcxuy3bTvcacCueAbyQxmvAkbPkrk,4466 +fsspec/implementations/data.py,sha256=9tMcy1fyX1auvzFX2aANPK9CfPoarnxTCDLhX12usvs,2131 +fsspec/implementations/dbfs.py,sha256=yHuLUGNmQd5pUCt9vpXleQNpjOpIZZwVZA08YauQU4U,16249 +fsspec/implementations/dirfs.py,sha256=KaIHW18i4-eNqdv7NR9qXEvoobQ88trGCNrqb4XW9ew,13449 +fsspec/implementations/ftp.py,sha256=S_y5XOv_QhBiYBw430qzFB5MfS9AzxNBOs3f87XehC0,13539 +fsspec/implementations/gist.py,sha256=Y6jTDrE-wuTwvpPyAQDuuOMBGxlajafKWoB1_yX6jdY,8528 +fsspec/implementations/git.py,sha256=qBDWMz5LNllPqVjr5jf_1FuNha4P5lyQI3IlhYg-wUE,3731 +fsspec/implementations/github.py,sha256=aCsZL8UvXZgdkcB1RUs3DdLeNrjLKcFsFYeQFDWbBFo,11653 +fsspec/implementations/http.py,sha256=1uWwxllOjPe8mQD54IrCYQJHU1YaAXh_cDmXBk-AoQ8,30894 +fsspec/implementations/http_sync.py,sha256=UmBqd938ebwVjYgVtzg-ysG3ZoGhIJw0wFtQAfxV3Aw,30332 +fsspec/implementations/jupyter.py,sha256=q1PlQ66AAswGFyr8MFKWyobaV2YekMWRtqENBDQtD28,4002 +fsspec/implementations/libarchive.py,sha256=SpIA1F-zf7kb2-VYUVuhMrXTBOhBxUXKgEW1RaAdDoA,7098 +fsspec/implementations/local.py,sha256=jpvvSYj8RaocLB8YuHjGlWOTMJAJNTnUBj9D_Zn32BA,17216 +fsspec/implementations/memory.py,sha256=fXUYjKF1xr4_9FX26vDCazEhmFbE7Om4xUufIOQe2vA,14088 +fsspec/implementations/reference.py,sha256=YKLzPBF6bLpOnHY9iM0MR5JLGRi5CB6x1cWIgMb6Ahg,49974 +fsspec/implementations/sftp.py,sha256=v7t-LpD4hEycHnw1kbepyoNgrhClshXQXitFuY4mBWE,5951 +fsspec/implementations/smb.py,sha256=5fhu8h06nOLBPh2c48aT7WBRqh9cEcbIwtyu06wTjec,15236 +fsspec/implementations/tar.py,sha256=adO9r_Badc4ucfApmK-mrvbv1re0_qoxwBjgnSMIrh0,4601 +fsspec/implementations/webhdfs.py,sha256=osF2m0nhDil6sbMzYW_4DZzhxF4ygtb59XDiybd9Fyg,17589 +fsspec/implementations/zip.py,sha256=GPDJh4UtUNJmaqijUQ0eiEZIGpwusQjkIcbhsrmLSi0,6263 +fsspec/json.py,sha256=4EBZ-xOmRiyxmIqPIwxmDImosRQ7io7qBM2xjJPsEE4,3768 +fsspec/mapping.py,sha256=m2ndB_gtRBXYmNJg0Ie1-BVR75TFleHmIQBzC-yWhjU,8343 +fsspec/parquet.py,sha256=0SzfswUTc2k5nAj7xZNYPPyvUkFNXznFRXXtBRhr-iE,20506 +fsspec/registry.py,sha256=KeDNL9HOyHX_D4D4qQGAI-Y3DQhiLeUC1VK2I81NZaE,12344 +fsspec/spec.py,sha256=3LTaRdAhOTIPCetwPCS9HC6MR1VlcdfLVBh4mWFrXns,79674 +fsspec/tests/abstract/__init__.py,sha256=V0-8FqQPfHlHZ3xomJ0hyWl6t1QvqsDnQFJYHeSTlEw,10197 +fsspec/tests/abstract/common.py,sha256=1GQwNo5AONzAnzZj0fWgn8NJPLXALehbsuGxS3FzWVU,4973 +fsspec/tests/abstract/copy.py,sha256=gU5-d97U3RSde35Vp4RxPY4rWwL744HiSrJ8IBOp9-8,19967 +fsspec/tests/abstract/get.py,sha256=vNR4HztvTR7Cj56AMo7_tx7TeYz1Jgr_2Wb8Lv-UiBY,20755 +fsspec/tests/abstract/mv.py,sha256=k8eUEBIrRrGMsBY5OOaDXdGnQUKGwDIfQyduB6YD3Ns,1982 +fsspec/tests/abstract/open.py,sha256=Fi2PBPYLbRqysF8cFm0rwnB41kMdQVYjq8cGyDXp3BU,329 +fsspec/tests/abstract/pipe.py,sha256=LFzIrLCB5GLXf9rzFKJmE8AdG7LQ_h4bJo70r8FLPqM,402 +fsspec/tests/abstract/put.py,sha256=7aih17OKB_IZZh1Mkq1eBDIjobhtMQmI8x-Pw-S_aZk,21201 +fsspec/transaction.py,sha256=xliRG6U2Zf3khG4xcw9WiB-yAoqJSHEGK_VjHOdtgo0,2398 +fsspec/utils.py,sha256=T6x7JS-qHGdZ6hMPrT1tH6_41lHFw88g3WxgNIItYPc,24114 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/WHEEL b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..7401812e19af977cc5088f3b8fb1ef6bc0441c0a --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.31.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/licenses/LICENSE b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..67590a5e5be5a5a2dde3fe53a7512e404a896c22 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec-2026.7.0.dist-info/licenses/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2018, Martin Durant +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/arrow.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/arrow.py new file mode 100644 index 0000000000000000000000000000000000000000..c312cd4a57b92d92e936d0cf97129f4fef0624fc --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/arrow.py @@ -0,0 +1,322 @@ +import errno +import io +import os +import secrets +import shutil +from contextlib import suppress +from functools import cached_property, wraps +from urllib.parse import parse_qs + +from fsspec.spec import AbstractFileSystem +from fsspec.utils import ( + get_package_version_without_import, + infer_storage_options, + mirror_from, + tokenize, +) + + +def wrap_exceptions(func): + @wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except OSError as exception: + if not exception.args: + raise + + message, *args = exception.args + if isinstance(message, str) and "does not exist" in message: + raise FileNotFoundError(errno.ENOENT, message) from exception + else: + raise + + return wrapper + + +PYARROW_VERSION = None +_EMPTY_ROOT_MARKER_FILESYSTEMS = {"gcs", "s3"} + + +class ArrowFSWrapper(AbstractFileSystem): + """FSSpec-compatible wrapper of pyarrow.fs.FileSystem. + + Parameters + ---------- + fs : pyarrow.fs.FileSystem + + """ + + root_marker = "/" + + def __init__(self, fs, **kwargs): + global PYARROW_VERSION + PYARROW_VERSION = get_package_version_without_import("pyarrow") + self.fs = fs + if fs.type_name in _EMPTY_ROOT_MARKER_FILESYSTEMS: + self.root_marker = "" + super().__init__(**kwargs) + + @property + def protocol(self): + return self.fs.type_name + + @cached_property + def fsid(self): + return "hdfs_" + tokenize(self.fs.host, self.fs.port) + + def _parent(self, path): + if self.root_marker: + return super()._parent(path) + + path = self._strip_protocol(path).lstrip("/") + return path.rsplit("/", 1)[0] if "/" in path else "" + + @classmethod + def _strip_protocol(cls, path): + ops = infer_storage_options(path) + path = ops["path"] + if path.startswith("//"): + # special case for "hdfs://path" (without the triple slash) + path = path[1:] + return path + + def ls(self, path, detail=False, **kwargs): + path = self._strip_protocol(path) + from pyarrow.fs import FileSelector + + try: + entries = [ + self._make_entry(entry) + for entry in self.fs.get_file_info(FileSelector(path)) + ] + except (FileNotFoundError, NotADirectoryError): + entries = [self.info(path, **kwargs)] + if detail: + return entries + else: + return [entry["name"] for entry in entries] + + def info(self, path, **kwargs): + path = self._strip_protocol(path) + [info] = self.fs.get_file_info([path]) + return self._make_entry(info) + + def exists(self, path): + path = self._strip_protocol(path) + try: + self.info(path) + except FileNotFoundError: + return False + else: + return True + + def _make_entry(self, info): + from pyarrow.fs import FileType + + if info.type is FileType.Directory: + kind = "directory" + elif info.type is FileType.File: + kind = "file" + elif info.type is FileType.NotFound: + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), info.path) + else: + kind = "other" + + return { + "name": info.path, + "size": info.size, + "type": kind, + "mtime": info.mtime, + } + + @wrap_exceptions + def cp_file(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1).rstrip("/") + path2 = self._strip_protocol(path2).rstrip("/") + + with self._open(path1, "rb") as lstream: + tmp_fname = f"{path2}.tmp.{secrets.token_hex(6)}" + try: + with self.open(tmp_fname, "wb") as rstream: + shutil.copyfileobj(lstream, rstream) + self.fs.move(tmp_fname, path2) + except BaseException: + with suppress(FileNotFoundError): + self.fs.delete_file(tmp_fname) + raise + + @wrap_exceptions + def mv(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1).rstrip("/") + path2 = self._strip_protocol(path2).rstrip("/") + self.fs.move(path1, path2) + + @wrap_exceptions + def rm_file(self, path): + path = self._strip_protocol(path) + self.fs.delete_file(path) + + @wrap_exceptions + def rm(self, path, recursive=False, maxdepth=None): + path = self._strip_protocol(path).rstrip("/") + if self.isdir(path): + if recursive: + self.fs.delete_dir(path) + else: + raise ValueError("Can't delete directories without recursive=False") + else: + self.fs.delete_file(path) + + @wrap_exceptions + def _open(self, path, mode="rb", block_size=None, seekable=True, **kwargs): + if mode == "rb": + if seekable: + method = self.fs.open_input_file + else: + method = self.fs.open_input_stream + elif mode == "wb": + method = self.fs.open_output_stream + elif mode == "ab": + method = self.fs.open_append_stream + else: + raise ValueError(f"unsupported mode for Arrow filesystem: {mode!r}") + + _kwargs = {} + if mode != "rb" or not seekable: + if int(PYARROW_VERSION.split(".")[0]) >= 4: + # disable compression auto-detection + _kwargs["compression"] = None + stream = method(path, **_kwargs) + + return ArrowFile(self, stream, path, mode, block_size, **kwargs) + + @wrap_exceptions + def mkdir(self, path, create_parents=True, **kwargs): + path = self._strip_protocol(path) + if create_parents: + self.makedirs(path, exist_ok=True) + else: + self.fs.create_dir(path, recursive=False) + + @wrap_exceptions + def makedirs(self, path, exist_ok=False): + path = self._strip_protocol(path) + self.fs.create_dir(path, recursive=True) + + @wrap_exceptions + def rmdir(self, path): + path = self._strip_protocol(path) + self.fs.delete_dir(path) + + @wrap_exceptions + def modified(self, path): + path = self._strip_protocol(path) + return self.fs.get_file_info(path).mtime + + def cat_file(self, path, start=None, end=None, **kwargs): + kwargs.setdefault("seekable", start not in [None, 0]) + return super().cat_file(path, start, end, **kwargs) + + def get_file(self, rpath, lpath, **kwargs): + kwargs.setdefault("seekable", False) + super().get_file(rpath, lpath, **kwargs) + + +@mirror_from( + "stream", + [ + "read", + "seek", + "tell", + "write", + "readable", + "writable", + "close", + "seekable", + ], +) +class ArrowFile(io.IOBase): + def __init__(self, fs, stream, path, mode, block_size=None, **kwargs): + self.path = path + self.mode = mode + + self.fs = fs + self.stream = stream + + self.blocksize = self.block_size = block_size + self.kwargs = kwargs + + def __enter__(self): + return self + + @property + def size(self): + if self.stream.seekable(): + return self.stream.size() + return None + + def __exit__(self, *args): + return self.close() + + +class HadoopFileSystem(ArrowFSWrapper): + """A wrapper on top of the pyarrow.fs.HadoopFileSystem + to connect it's interface with fsspec""" + + protocol = "hdfs" + + def __init__( + self, + host="default", + port=0, + user=None, + kerb_ticket=None, + replication=3, + extra_conf=None, + **kwargs, + ): + """ + + Parameters + ---------- + host: str + Hostname, IP or "default" to try to read from Hadoop config + port: int + Port to connect on, or default from Hadoop config if 0 + user: str or None + If given, connect as this username + kerb_ticket: str or None + If given, use this ticket for authentication + replication: int + set replication factor of file for write operations. default value is 3. + extra_conf: None or dict + Passed on to HadoopFileSystem + """ + from pyarrow.fs import HadoopFileSystem + + fs = HadoopFileSystem( + host=host, + port=port, + user=user, + kerb_ticket=kerb_ticket, + replication=replication, + extra_conf=extra_conf, + ) + super().__init__(fs=fs, **kwargs) + + @staticmethod + def _get_kwargs_from_urls(path): + ops = infer_storage_options(path) + out = {} + if ops.get("host", None): + out["host"] = ops["host"] + if ops.get("username", None): + out["user"] = ops["username"] + if ops.get("port", None): + out["port"] = ops["port"] + if ops.get("url_query", None): + queries = parse_qs(ops["url_query"]) + if queries.get("replication", None): + out["replication"] = int(queries["replication"][0]) + return out diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/asyn_wrapper.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/asyn_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..91db5eb48d00e36b46d9deb49504a7d2ad76d690 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/asyn_wrapper.py @@ -0,0 +1,124 @@ +import asyncio +import functools +import inspect + +import fsspec +from fsspec.asyn import AsyncFileSystem, running_async + +from .chained import ChainedFileSystem + + +def async_wrapper(func, obj=None, semaphore=None): + """ + Wraps a synchronous function to make it awaitable. + + Parameters + ---------- + func : callable + The synchronous function to wrap. + obj : object, optional + The instance to bind the function to, if applicable. + semaphore : asyncio.Semaphore, optional + A semaphore to limit concurrent calls. + + Returns + ------- + coroutine + An awaitable version of the function. + """ + + @functools.wraps(func) + async def wrapper(*args, **kwargs): + if semaphore: + async with semaphore: + return await asyncio.to_thread(func, *args, **kwargs) + return await asyncio.to_thread(func, *args, **kwargs) + + return wrapper + + +class AsyncFileSystemWrapper(AsyncFileSystem, ChainedFileSystem): + """ + A wrapper class to convert a synchronous filesystem into an asynchronous one. + + This class takes an existing synchronous filesystem implementation and wraps all + its methods to provide an asynchronous interface. + + Parameters + ---------- + sync_fs : AbstractFileSystem + The synchronous filesystem instance to wrap. + """ + + protocol = "asyncwrapper", "async_wrapper" + cachable = False + + def __init__( + self, + fs=None, + asynchronous=None, + target_protocol=None, + target_options=None, + semaphore=None, + max_concurrent_tasks=None, + **kwargs, + ): + if asynchronous is None: + asynchronous = running_async() + super().__init__(asynchronous=asynchronous, **kwargs) + if fs is not None: + self.sync_fs = fs + else: + self.sync_fs = fsspec.filesystem(target_protocol, **target_options) + self.protocol = self.sync_fs.protocol + self.semaphore = semaphore + self._wrap_all_sync_methods() + + @property + def fsid(self): + return f"async_{self.sync_fs.fsid}" + + def _wrap_all_sync_methods(self): + """ + Wrap all synchronous methods of the underlying filesystem with asynchronous versions. + """ + excluded_methods = {"open"} + for method_name in dir(self.sync_fs): + if method_name.startswith("_") or method_name in excluded_methods: + continue + + attr = inspect.getattr_static(self.sync_fs, method_name) + if isinstance(attr, property): + continue + + method = getattr(self.sync_fs, method_name) + if callable(method) and not inspect.iscoroutinefunction(method): + async_method = async_wrapper(method, obj=self, semaphore=self.semaphore) + setattr(self, f"_{method_name}", async_method) + + @classmethod + def wrap_class(cls, sync_fs_class): + """ + Create a new class that can be used to instantiate an AsyncFileSystemWrapper + with lazy instantiation of the underlying synchronous filesystem. + + Parameters + ---------- + sync_fs_class : type + The class of the synchronous filesystem to wrap. + + Returns + ------- + type + A new class that wraps the provided synchronous filesystem class. + """ + + class GeneratedAsyncFileSystemWrapper(cls): + def __init__(self, *args, **kwargs): + sync_fs = sync_fs_class(*args, **kwargs) + super().__init__(sync_fs) + + GeneratedAsyncFileSystemWrapper.__name__ = ( + f"Async{sync_fs_class.__name__}Wrapper" + ) + return GeneratedAsyncFileSystemWrapper diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/cache_mapper.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/cache_mapper.py new file mode 100644 index 0000000000000000000000000000000000000000..6e7c7d88afdddf12f77b26bb635bd8bf1e2bd7f1 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/cache_mapper.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +import abc +import hashlib + +from fsspec.implementations.local import make_path_posix + + +class AbstractCacheMapper(abc.ABC): + """Abstract super-class for mappers from remote URLs to local cached + basenames. + """ + + @abc.abstractmethod + def __call__(self, path: str) -> str: ... + + def __eq__(self, other: object) -> bool: + # Identity only depends on class. When derived classes have attributes + # they will need to be included. + return isinstance(other, type(self)) + + def __hash__(self) -> int: + # Identity only depends on class. When derived classes have attributes + # they will need to be included. + return hash(type(self)) + + +class BasenameCacheMapper(AbstractCacheMapper): + """Cache mapper that uses the basename of the remote URL and a fixed number + of directory levels above this. + + The default is zero directory levels, meaning different paths with the same + basename will have the same cached basename. + """ + + def __init__(self, directory_levels: int = 0): + if directory_levels < 0: + raise ValueError( + "BasenameCacheMapper requires zero or positive directory_levels" + ) + self.directory_levels = directory_levels + + # Separator for directories when encoded as strings. + self._separator = "_@_" + + def __call__(self, path: str) -> str: + path = make_path_posix(path) + prefix, *bits = path.rsplit("/", self.directory_levels + 1) + if bits: + return self._separator.join(bits) + else: + return prefix # No separator found, simple filename + + def __eq__(self, other: object) -> bool: + return super().__eq__(other) and self.directory_levels == other.directory_levels + + def __hash__(self) -> int: + return super().__hash__() ^ hash(self.directory_levels) + + +class HashCacheMapper(AbstractCacheMapper): + """Cache mapper that uses a hash of the remote URL.""" + + def __call__(self, path: str) -> str: + return hashlib.sha256(path.encode()).hexdigest() + + +def create_cache_mapper(same_names: bool) -> AbstractCacheMapper: + """Factory method to create cache mapper for backward compatibility with + ``CachingFileSystem`` constructor using ``same_names`` kwarg. + """ + if same_names: + return BasenameCacheMapper() + else: + return HashCacheMapper() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/cache_metadata.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/cache_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..2a48231cac9f984f3e41bc9f81a113ae28a1f5dd --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/cache_metadata.py @@ -0,0 +1,217 @@ +from __future__ import annotations + +import os +import time +from typing import TYPE_CHECKING + +from fsspec.utils import atomic_write + +try: + import ujson as json +except ImportError: + if not TYPE_CHECKING: + import json + +if TYPE_CHECKING: + from collections.abc import Iterator + from typing import Any, Literal, TypeAlias + + from .cached import CachingFileSystem + + Detail: TypeAlias = dict[str, Any] + + +class CacheMetadata: + """Cache metadata. + + All reading and writing of cache metadata is performed by this class, + accessing the cached files and blocks is not. + + Metadata is stored in a single file per storage directory in JSON format. + For backward compatibility. No longer supports pickle. + """ + + def __init__(self, storage: list[str]): + """ + + Parameters + ---------- + storage: list[str] + Directories containing cached files, must be at least one. Metadata + is stored in the last of these directories by convention. + """ + if not storage: + raise ValueError("CacheMetadata expects at least one storage location") + + self._storage = storage + self.cached_files: list[Detail] = [{}] + + def _load(self, fn: str) -> Detail: + """Low-level function to load metadata from specific file""" + with open(fn, "r") as f: + loaded = json.load(f) + for c in loaded.values(): + if isinstance(c.get("blocks"), list): + c["blocks"] = set(c["blocks"]) + return loaded + + def _save(self, metadata_to_save: Detail, fn: str) -> None: + """Low-level function to save metadata to specific file""" + with atomic_write(fn, mode="w") as f: + json.dump(metadata_to_save, f) + + def _scan_locations( + self, writable_only: bool = False + ) -> Iterator[tuple[str, str, bool]]: + """Yield locations (filenames) where metadata is stored, and whether + writable or not. + + Parameters + ---------- + writable: bool + Set to True to only yield writable locations. + + Returns + ------- + Yields (str, str, bool) + """ + n = len(self._storage) + for i, storage in enumerate(self._storage): + writable = i == n - 1 + if writable_only and not writable: + continue + yield os.path.join(storage, "cache"), storage, writable + + def check_file( + self, path: str, cfs: CachingFileSystem | None + ) -> Literal[False] | tuple[Detail, str]: + """If path is in cache return its details, otherwise return ``False``. + + If the optional CachingFileSystem is specified then it is used to + perform extra checks to reject possible matches, such as if they are + too old. + """ + for (fn, base, _), cache in zip(self._scan_locations(), self.cached_files): + if path not in cache: + continue + detail = cache[path].copy() + + if cfs is not None: + if cfs.check_files and detail["uid"] != cfs.fs.ukey(path): + # Wrong file as determined by hash of file properties + continue + if cfs.expiry and time.time() - detail["time"] > cfs.expiry: + # Cached file has expired + continue + + fn = os.path.join(base, detail["fn"]) + if os.path.exists(fn): + return detail, fn + return False + + def clear_expired(self, expiry_time: int) -> tuple[list[str], bool]: + """Remove expired metadata from the cache. + + Returns names of files corresponding to expired metadata and a boolean + flag indicating whether the writable cache is empty. Caller is + responsible for deleting the expired files. + """ + expired_files = [] + for path, detail in self.cached_files[-1].copy().items(): + if time.time() - detail["time"] > expiry_time: + fn = detail.get("fn", "") + if not fn: + raise RuntimeError( + f"Cache metadata does not contain 'fn' for {path}" + ) + fn = os.path.join(self._storage[-1], fn) + expired_files.append(fn) + self.cached_files[-1].pop(path) + + if self.cached_files[-1]: + cache_path = os.path.join(self._storage[-1], "cache") + self._save(self.cached_files[-1], cache_path) + + writable_cache_empty = not self.cached_files[-1] + return expired_files, writable_cache_empty + + def load(self) -> None: + """Load all metadata from disk and store in ``self.cached_files``""" + cached_files = [] + for fn, _, _ in self._scan_locations(): + if os.path.exists(fn): + # TODO: consolidate blocks here + cached_files.append(self._load(fn)) + else: + cached_files.append({}) + self.cached_files = cached_files or [{}] + + def on_close_cached_file(self, f: Any, path: str) -> None: + """Perform side-effect actions on closing a cached file. + + The actual closing of the file is the responsibility of the caller. + """ + # File must be writable, so in self.cached_files[-1] + c = self.cached_files[-1][path] + if c["blocks"] is not True and len(c["blocks"]) * f.blocksize >= f.size: + c["blocks"] = True + + def pop_file(self, path: str) -> str | None: + """Remove metadata of cached file. + + If path is in the cache, return the filename of the cached file, + otherwise return ``None``. Caller is responsible for deleting the + cached file. + """ + details = self.check_file(path, None) + if not details: + return None + _, fn = details + if fn.startswith(self._storage[-1]): + self.cached_files[-1].pop(path) + self.save() + else: + raise PermissionError( + "Can only delete cached file in last, writable cache location" + ) + return fn + + def save(self) -> None: + """Save metadata to disk""" + for (fn, _, writable), cache in zip(self._scan_locations(), self.cached_files): + if not writable: + continue + + if os.path.exists(fn): + cached_files = self._load(fn) + for k, c in cached_files.items(): + if k in cache: + if c["blocks"] is True or cache[k]["blocks"] is True: + c["blocks"] = True + else: + # self.cached_files[*][*]["blocks"] must continue to + # point to the same set object so that updates + # performed by MMapCache are propagated back to + # self.cached_files. + blocks = cache[k]["blocks"] + blocks.update(c["blocks"]) + c["blocks"] = blocks + c["time"] = max(c["time"], cache[k]["time"]) + c["uid"] = cache[k]["uid"] + + # Files can be added to cache after it was written once + for k, c in cache.items(): + if k not in cached_files: + cached_files[k] = c + else: + cached_files = cache + cache = {k: v.copy() for k, v in cached_files.items()} + for c in cache.values(): + if isinstance(c["blocks"], set): + c["blocks"] = list(c["blocks"]) + self._save(cache, fn) + self.cached_files[-1] = cached_files + + def update_file(self, path: str, detail: Detail) -> None: + """Update metadata for specific file in memory, do not save""" + self.cached_files[-1][path] = detail diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/cached.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/cached.py new file mode 100644 index 0000000000000000000000000000000000000000..c01ce9aef88ba62b04bbc308fd1a65bab354782b --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/cached.py @@ -0,0 +1,1040 @@ +from __future__ import annotations + +import inspect +import logging +import os +import tempfile +import time +import weakref +from collections.abc import Callable +from shutil import rmtree +from typing import TYPE_CHECKING, Any, ClassVar + +from fsspec import filesystem +from fsspec.callbacks import DEFAULT_CALLBACK +from fsspec.compression import compr +from fsspec.core import BaseCache, MMapCache +from fsspec.exceptions import BlocksizeMismatchError +from fsspec.implementations.cache_mapper import create_cache_mapper +from fsspec.implementations.cache_metadata import CacheMetadata +from fsspec.implementations.chained import ChainedFileSystem +from fsspec.implementations.local import LocalFileSystem +from fsspec.spec import AbstractBufferedFile +from fsspec.transaction import Transaction +from fsspec.utils import infer_compression + +if TYPE_CHECKING: + from fsspec.implementations.cache_mapper import AbstractCacheMapper + +logger = logging.getLogger("fsspec.cached") + + +class WriteCachedTransaction(Transaction): + def complete(self, commit=True): + rpaths = [f.path for f in self.files] + lpaths = [f.fn for f in self.files] + if commit: + self.fs.put(lpaths, rpaths) + self.files.clear() + self.fs._intrans = False + self.fs._transaction = None + self.fs = None # break cycle + + +class CachingFileSystem(ChainedFileSystem): + """Locally caching filesystem, layer over any other FS + + This class implements chunk-wise local storage of remote files, for quick + access after the initial download. The files are stored in a given + directory with hashes of URLs for the filenames. If no directory is given, + a temporary one is used, which should be cleaned up by the OS after the + process ends. The files themselves are sparse (as implemented in + :class:`~fsspec.caching.MMapCache`), so only the data which is accessed + takes up space. + + Restrictions: + + - the block-size must be the same for each access of a given file, unless + all blocks of the file have already been read + - caching can only be applied to file-systems which produce files + derived from fsspec.spec.AbstractBufferedFile ; LocalFileSystem is also + allowed, for testing + """ + + protocol: ClassVar[str | tuple[str, ...]] = ("blockcache", "cached") + _strip_tokenize_options = ("fo",) + + def __init__( + self, + target_protocol=None, + cache_storage="TMP", + cache_check=10, + check_files=False, + expiry_time=604800, + target_options=None, + fs=None, + same_names: bool | None = None, + compression=None, + cache_mapper: AbstractCacheMapper | None = None, + cache_storage_mode=None, + **kwargs, + ): + """ + + Parameters + ---------- + target_protocol: str (optional) + Target filesystem protocol. Provide either this or ``fs``. + cache_storage: str or list(str) + Location to store files. If "TMP", this is a temporary directory, + and will be cleaned up by the OS when this process ends (or later). + If a list, each location will be tried in the order given, but + only the last will be considered writable. + cache_check: int + Number of seconds between reload of cache metadata + check_files: bool + Whether to explicitly see if the UID of the remote file matches + the stored one before using. Warning: some file systems such as + HTTP cannot reliably give a unique hash of the contents of some + path, so be sure to set this option to False. + expiry_time: int + The time in seconds after which a local copy is considered useless. + Set to falsy to prevent expiry. The default is equivalent to one + week. + target_options: dict or None + Passed to the instantiation of the FS, if fs is None. + fs: filesystem instance + The target filesystem to run against. Provide this or ``protocol``. + same_names: bool (optional) + By default, target URLs are hashed using a ``HashCacheMapper`` so + that files from different backends with the same basename do not + conflict. If this argument is ``true``, a ``BasenameCacheMapper`` + is used instead. Other cache mapper options are available by using + the ``cache_mapper`` keyword argument. Only one of this and + ``cache_mapper`` should be specified. + compression: str (optional) + To decompress on download. Can be 'infer' (guess from the URL name), + one of the entries in ``fsspec.compression.compr``, or None for no + decompression. + cache_mapper: AbstractCacheMapper (optional) + The object use to map from original filenames to cached filenames. + Only one of this and ``same_names`` should be specified. + cache_storage_mode: int (optional) + Permission mode used when creating the cache storage directory, + e.g. ``0o700``. The default of ``None`` leaves the directory at + the system default (governed by the umask), which is the existing + behaviour. Pass an octal mode such as ``0o700`` to keep the cache + directory, and so the cached data files within it, readable by the + owner only. + """ + super().__init__(**kwargs) + if fs is None and target_protocol is None: + raise ValueError( + "Please provide filesystem instance(fs) or target_protocol" + ) + if not (fs is None) ^ (target_protocol is None): + raise ValueError( + "Both filesystems (fs) and target_protocol may not be both given." + ) + if cache_storage == "TMP": + tempdir = tempfile.mkdtemp() + storage = [tempdir] + weakref.finalize(self, self._remove_tempdir, tempdir) + else: + if isinstance(cache_storage, str): + storage = [cache_storage] + else: + storage = cache_storage + self.cache_storage_mode = cache_storage_mode + self._makedirs(storage[-1]) + self.storage = storage + self.kwargs = target_options or {} + self.cache_check = cache_check + self.check_files = check_files + self.expiry = expiry_time + self.compression = compression + + # Size of cache in bytes. If None then the size is unknown and will be + # recalculated the next time cache_size() is called. On writes to the + # cache this is reset to None. + self._cache_size = None + + if same_names is not None and cache_mapper is not None: + raise ValueError( + "Cannot specify both same_names and cache_mapper in " + "CachingFileSystem.__init__" + ) + if cache_mapper is not None: + self._mapper = cache_mapper + else: + self._mapper = create_cache_mapper( + same_names if same_names is not None else False + ) + + self.target_protocol = ( + target_protocol + if isinstance(target_protocol, str) + else (fs.protocol if isinstance(fs.protocol, str) else fs.protocol[0]) + ) + self._metadata = CacheMetadata(self.storage) + self.load_cache() + self.fs = fs if fs is not None else filesystem(target_protocol, **self.kwargs) + + def _strip_protocol(path): + # acts as a method, since each instance has a difference target + return self.fs._strip_protocol(type(self)._strip_protocol(path)) + + self._strip_protocol: Callable = _strip_protocol + + @staticmethod + def _remove_tempdir(tempdir): + try: + rmtree(tempdir) + except Exception: + pass + + def _makedirs(self, path): + if self.cache_storage_mode is None: + os.makedirs(path, exist_ok=True) + else: + os.makedirs(path, exist_ok=True, mode=self.cache_storage_mode) + + def _mkcache(self): + self._makedirs(self.storage[-1]) + + def cache_size(self): + """Return size of cache in bytes. + + If more than one cache directory is in use, only the size of the last + one (the writable cache directory) is returned. + """ + if self._cache_size is None: + cache_dir = self.storage[-1] + self._cache_size = filesystem("file").du(cache_dir, withdirs=True) + return self._cache_size + + def load_cache(self): + """Read set of stored blocks from file""" + self._metadata.load() + self._mkcache() + self.last_cache = time.time() + + def save_cache(self): + """Save set of stored blocks from file""" + self._mkcache() + self._metadata.save() + self.last_cache = time.time() + self._cache_size = None + + def _check_cache(self): + """Reload caches if time elapsed or any disappeared""" + self._mkcache() + if not self.cache_check: + # explicitly told not to bother checking + return + timecond = time.time() - self.last_cache > self.cache_check + existcond = all(os.path.exists(storage) for storage in self.storage) + if timecond or not existcond: + self.load_cache() + + def _check_file(self, path): + """Is path in cache and still valid""" + path = self._strip_protocol(path) + self._check_cache() + return self._metadata.check_file(path, self) + + def clear_cache(self): + """Remove all files and metadata from the cache + + In the case of multiple cache locations, this clears only the last one, + which is assumed to be the read/write one. + """ + rmtree(self.storage[-1]) + self.load_cache() + self._cache_size = None + + def clear_expired_cache(self, expiry_time=None): + """Remove all expired files and metadata from the cache + + In the case of multiple cache locations, this clears only the last one, + which is assumed to be the read/write one. + + Parameters + ---------- + expiry_time: int + The time in seconds after which a local copy is considered useless. + If not defined the default is equivalent to the attribute from the + file caching instantiation. + """ + + if not expiry_time: + expiry_time = self.expiry + + self._check_cache() + + expired_files, writable_cache_empty = self._metadata.clear_expired(expiry_time) + for fn in expired_files: + if os.path.exists(fn): + os.remove(fn) + + if writable_cache_empty: + rmtree(self.storage[-1]) + self.load_cache() + + self._cache_size = None + + def pop_from_cache(self, path): + """Remove cached version of given file + + Deletes local copy of the given (remote) path. If it is found in a cache + location which is not the last, it is assumed to be read-only, and + raises PermissionError + """ + path = self._strip_protocol(path) + fn = self._metadata.pop_file(path) + if fn is not None: + os.remove(fn) + self._cache_size = None + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + """Wrap the target _open + + If the whole file exists in the cache, just open it locally and + return that. + + Otherwise, open the file on the target FS, and make it have a mmap + cache pointing to the location which we determine, in our cache. + The ``blocks`` instance is shared, so as the mmap cache instance + updates, so does the entry in our ``cached_files`` attribute. + We monkey-patch this file, so that when it closes, we call + ``close_and_update`` to save the state of the blocks. + """ + path = self._strip_protocol(path) + + path = self.fs._strip_protocol(path) + if "r" not in mode: + return self.fs._open( + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_options=cache_options, + **kwargs, + ) + detail = self._check_file(path) + if detail: + # file is in cache + detail, fn = detail + hash, blocks = detail["fn"], detail["blocks"] + if blocks is True: + # stored file is complete + logger.debug("Opening local copy of %s", path) + return open(fn, mode) + # TODO: action where partial file exists in read-only cache + logger.debug("Opening partially cached copy of %s", path) + else: + hash = self._mapper(path) + fn = os.path.join(self.storage[-1], hash) + blocks = set() + detail = { + "original": path, + "fn": hash, + "blocks": blocks, + "time": time.time(), + "uid": self.fs.ukey(path), + } + self._metadata.update_file(path, detail) + logger.debug("Creating local sparse file for %s", path) + + # explicitly submitting the size to the open call will avoid extra + # operations when opening. This is particularly relevant + # for any file that is read over a network, e.g. S3. + size = detail.get("size") + + # call target filesystems open + self._mkcache() + f = self.fs._open( + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_options=cache_options, + cache_type="none", + size=size, + **kwargs, + ) + + # set size if not already set + if size is None: + detail["size"] = f.size + self._metadata.update_file(path, detail) + + if self.compression: + comp = ( + infer_compression(path) + if self.compression == "infer" + else self.compression + ) + f = compr[comp](f, mode="rb") + if "blocksize" in detail: + if detail["blocksize"] != f.blocksize: + raise BlocksizeMismatchError( + f"Cached file must be reopened with same block" + f" size as original (old: {detail['blocksize']}," + f" new {f.blocksize})" + ) + else: + detail["blocksize"] = f.blocksize + + def _fetch_ranges(ranges): + return self.fs.cat_ranges( + [path] * len(ranges), + [r[0] for r in ranges], + [r[1] for r in ranges], + **kwargs, + ) + + multi_fetcher = None if self.compression else _fetch_ranges + f.cache = MMapCache( + f.blocksize, f._fetch_range, f.size, fn, blocks, multi_fetcher=multi_fetcher + ) + close = f.close + f.close = lambda: self.close_and_update(f, close) + self.save_cache() + return f + + def _parent(self, path): + return self.fs._parent(path) + + def hash_name(self, path: str, *args: Any) -> str: + # Kept for backward compatibility with downstream libraries. + # Ignores extra arguments, previously same_name boolean. + return self._mapper(path) + + def close_and_update(self, f, close): + """Called when a file is closing, so store the set of blocks""" + if f.closed: + return + path = self._strip_protocol(f.path) + self._metadata.on_close_cached_file(f, path) + try: + logger.debug("going to save") + self.save_cache() + logger.debug("saved") + except OSError: + logger.debug("Cache saving failed while closing file") + except NameError: + logger.debug("Cache save failed due to interpreter shutdown") + close() + f.closed = True + + def ls(self, path, detail=True, **kwargs): + return self.fs.ls(path, detail, **kwargs) + + def __getattribute__(self, item): + if item in { + "load_cache", + "_get_cached_file_before_open", + "_open", + "save_cache", + "close_and_update", + "__init__", + "__getattribute__", + "__reduce__", + "_make_local_details", + "open", + "cat", + "cat_file", + "_cat_file", + "cat_ranges", + "_cat_ranges", + "get", + "read_block", + "tail", + "head", + "info", + "ls", + "exists", + "isfile", + "isdir", + "_check_file", + "_check_cache", + "_makedirs", + "_mkcache", + "clear_cache", + "clear_expired_cache", + "pop_from_cache", + "local_file", + "_paths_from_path", + "get_mapper", + "open_many", + "commit_many", + "hash_name", + "__hash__", + "__eq__", + "to_json", + "to_dict", + "cache_size", + "pipe_file", + "pipe", + "start_transaction", + "end_transaction", + }: + # all the methods defined in this class. Note `open` here, since + # it calls `_open`, but is actually in superclass + if hasattr(type(self), item): + return lambda *args, **kw: getattr(type(self), item).__get__(self)( + *args, **kw + ) + # method is in the whitelist but not defined on this subclass; + # fall through to delegate to the wrapped filesystem below + if item in ["__reduce_ex__"]: + raise AttributeError + if item in ["transaction"]: + # property + return type(self).transaction.__get__(self) + if item in {"_cache", "transaction_type", "protocol"}: + # class attributes + return getattr(type(self), item) + if item == "__class__": + return type(self) + d = object.__getattribute__(self, "__dict__") + fs = d.get("fs", None) # fs is not immediately defined + if item in d: + return d[item] + elif fs is not None: + if item in fs.__dict__: + # attribute of instance + return fs.__dict__[item] + # attributed belonging to the target filesystem + cls = type(fs) + m = getattr(cls, item) + if (inspect.isfunction(m) or inspect.isdatadescriptor(m)) and ( + not hasattr(m, "__self__") or m.__self__ is None + ): + # instance method + return m.__get__(fs, cls) + return m # class method or attribute + else: + # attributes of the superclass, while target is being set up + return super().__getattribute__(item) + + def __eq__(self, other): + """Test for equality.""" + if self is other: + return True + if not isinstance(other, type(self)): + return False + return ( + self.storage == other.storage + and self.kwargs == other.kwargs + and self.cache_check == other.cache_check + and self.check_files == other.check_files + and self.expiry == other.expiry + and self.compression == other.compression + and self._mapper == other._mapper + and self.target_protocol == other.target_protocol + ) + + def __hash__(self): + """Calculate hash.""" + return ( + hash(tuple(self.storage)) + ^ hash(str(self.kwargs)) + ^ hash(self.cache_check) + ^ hash(self.check_files) + ^ hash(self.expiry) + ^ hash(self.compression) + ^ hash(self._mapper) + ^ hash(self.target_protocol) + ) + + +class WholeFileCacheFileSystem(CachingFileSystem): + """Caches whole remote files on first access + + This class is intended as a layer over any other file system, and + will make a local copy of each file accessed, so that all subsequent + reads are local. This is similar to ``CachingFileSystem``, but without + the block-wise functionality and so can work even when sparse files + are not allowed. See its docstring for definition of the init + arguments. + + The class still needs access to the remote store for listing files, + and may refresh cached files. + """ + + protocol = "filecache" + local_file = True + + def open_many(self, open_files, **kwargs): + paths = [of.path for of in open_files] + if "r" in open_files.mode: + self._mkcache() + else: + return [ + LocalTempFile( + self.fs, + path, + mode=open_files.mode, + fn=os.path.join(self.storage[-1], self._mapper(path)), + **kwargs, + ) + for path in paths + ] + + if self.compression: + raise NotImplementedError + details = [self._check_file(sp) for sp in paths] + downpath = [p for p, d in zip(paths, details) if not d] + downfn0 = [ + os.path.join(self.storage[-1], self._mapper(p)) + for p, d in zip(paths, details) + ] # keep these path names for opening later + downfn = [fn for fn, d in zip(downfn0, details) if not d] + if downpath: + # skip if all files are already cached and up to date + self.fs.get(downpath, downfn) + + # update metadata - only happens when downloads are successful + newdetail = [ + { + "original": path, + "fn": self._mapper(path), + "blocks": True, + "time": time.time(), + "uid": self.fs.ukey(path), + } + for path in downpath + ] + for path, detail in zip(downpath, newdetail): + self._metadata.update_file(path, detail) + self.save_cache() + + def firstpart(fn): + # helper to adapt both whole-file and simple-cache + return fn[1] if isinstance(fn, tuple) else fn + + return [ + open(firstpart(fn0) if fn0 else fn1, mode=open_files.mode) + for fn0, fn1 in zip(details, downfn0) + ] + + def commit_many(self, open_files): + self.fs.put([f.fn for f in open_files], [f.path for f in open_files]) + [f.close() for f in open_files] + for f in open_files: + # in case autocommit is off, and so close did not already delete + try: + os.remove(f.name) + except FileNotFoundError: + pass + self._cache_size = None + + def _make_local_details(self, path): + hash = self._mapper(path) + fn = os.path.join(self.storage[-1], hash) + detail = { + "original": path, + "fn": hash, + "blocks": True, + "time": time.time(), + "uid": self.fs.ukey(path), + } + self._metadata.update_file(path, detail) + logger.debug("Copying %s to local cache", path) + return fn + + def cat( + self, + path, + recursive=False, + on_error="raise", + callback=DEFAULT_CALLBACK, + **kwargs, + ): + paths = self.expand_path( + path, recursive=recursive, maxdepth=kwargs.get("maxdepth") + ) + getpaths = [] + storepaths = [] + fns = [] + out = {} + for p in paths.copy(): + try: + detail = self._check_file(p) + if not detail: + fn = self._make_local_details(p) + getpaths.append(p) + storepaths.append(fn) + else: + detail, fn = detail if isinstance(detail, tuple) else (None, detail) + fns.append(fn) + except Exception as e: + if on_error == "raise": + raise + if on_error == "return": + out[p] = e + paths.remove(p) + + if getpaths: + self.fs.get(getpaths, storepaths) + self.save_cache() + + callback.set_size(len(paths)) + for p, fn in zip(paths, fns): + with open(fn, "rb") as f: + out[p] = f.read() + callback.relative_update(1) + if isinstance(path, str) and len(paths) == 1 and recursive is False: + out = out[paths[0]] + return out + + def _get_cached_file_before_open(self, path, **kwargs): + fn = self._make_local_details(path) + # call target filesystems open + self._mkcache() + if self.compression: + with self.fs._open(path, mode="rb", **kwargs) as f, open(fn, "wb") as f2: + if isinstance(f, AbstractBufferedFile): + # want no type of caching if just downloading whole thing + f.cache = BaseCache(0, f.cache.fetcher, f.size) + comp = ( + infer_compression(path) + if self.compression == "infer" + else self.compression + ) + f = compr[comp](f, mode="rb") + data = True + while data: + block = getattr(f, "blocksize", 5 * 2**20) + data = f.read(block) + f2.write(data) + else: + self.fs.get_file(path, fn) + self.save_cache() + + def _open(self, path, mode="rb", **kwargs): + path = self._strip_protocol(path) + # For read (or append), (try) download from remote + if "r" in mode or "a" in mode: + if not self._check_file(path): + if self.fs.exists(path): + self._get_cached_file_before_open(path, **kwargs) + elif "r" in mode: + raise FileNotFoundError(path) + + detail, fn = self._check_file(path) + _, blocks = detail["fn"], detail["blocks"] + if blocks is True: + logger.debug("Opening local copy of %s", path) + else: + raise ValueError( + f"Attempt to open partially cached file {path}" + f" as a wholly cached file" + ) + + # Just reading does not need special file handling + if "r" in mode and "+" not in mode: + # In order to support downstream filesystems to be able to + # infer the compression from the original filename, like + # the `TarFileSystem`, let's extend the `io.BufferedReader` + # fileobject protocol by adding a dedicated attribute + # `original`. + f = open(fn, mode) + f.original = detail.get("original") + return f + + hash = self._mapper(path) + fn = os.path.join(self.storage[-1], hash) + user_specified_kwargs = { + k: v + for k, v in kwargs.items() + # those kwargs were added by open(), we don't want them + if k not in ["autocommit", "block_size", "cache_options"] + } + return LocalTempFile(self, path, mode=mode, fn=fn, **user_specified_kwargs) + + async def _cat_file(self, path, start=None, end=None, **kwargs): + logger.debug("async cat_file %s", path) + path = self._strip_protocol(path) + sha = self._mapper(path) + fn = self._check_file(path) + + if not fn: + fn = os.path.join(self.storage[-1], sha) + await self.fs._get_file(path, fn, **kwargs) + + with open(fn, "rb") as f: # noqa ASYNC230 + if start: + f.seek(start) + size = -1 if end is None else end - f.tell() + return f.read(size) + + async def _cat_ranges( + self, paths, starts, ends, max_gap=None, on_error="return", **kwargs + ): + logger.debug("async cat ranges %s", paths) + lpaths = [] + rset = set() + download = [] + rpaths = [] + for p in paths: + fn = self._check_file(p) + if fn is None and p not in rset: + sha = self._mapper(p) + fn = os.path.join(self.storage[-1], sha) + download.append(fn) + rset.add(p) + rpaths.append(p) + lpaths.append(fn) + if download: + await self.fs._get(rpaths, download, on_error=on_error) + + return LocalFileSystem().cat_ranges( + lpaths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs + ) + + +class SimpleCacheFileSystem(WholeFileCacheFileSystem): + """Caches whole remote files on first access + + This class is intended as a layer over any other file system, and + will make a local copy of each file accessed, so that all subsequent + reads are local. This implementation only copies whole files, and + does not keep any metadata about the download time or file details. + It is therefore safer to use in multi-threaded/concurrent situations. + + This is the only of the caching filesystems that supports write: you will + be given a real local open file, and upon close and commit, it will be + uploaded to the target filesystem; the writability or the target URL is + not checked until that time. + + """ + + protocol = "simplecache" + local_file = True + transaction_type = WriteCachedTransaction + + def __init__(self, **kwargs): + kw = kwargs.copy() + for key in ["cache_check", "expiry_time", "check_files"]: + kw[key] = False + super().__init__(**kw) + for storage in self.storage: + if not os.path.exists(storage): + self._makedirs(storage) + + def _check_file(self, path): + self._check_cache() + sha = self._mapper(path) + for storage in self.storage: + fn = os.path.join(storage, sha) + if os.path.exists(fn): + return fn + + def save_cache(self): + pass + + def load_cache(self): + pass + + def pipe_file(self, path, value=None, **kwargs): + if self._intrans: + with self.open(path, "wb") as f: + f.write(value) + else: + super().pipe_file(path, value) + + def ls(self, path, detail=True, **kwargs): + path = self._strip_protocol(path) + details = [] + try: + details = self.fs.ls( + path, detail=True, **kwargs + ).copy() # don't edit original! + except FileNotFoundError as e: + ex = e + else: + ex = None + if self._intrans: + path1 = path.rstrip("/") + "/" + for f in self.transaction.files: + if f.path == path: + details.append( + {"name": path, "size": f.size or f.tell(), "type": "file"} + ) + elif f.path.startswith(path1): + if f.path.count("/") == path1.count("/"): + details.append( + {"name": f.path, "size": f.size or f.tell(), "type": "file"} + ) + else: + dname = "/".join(f.path.split("/")[: path1.count("/") + 1]) + details.append({"name": dname, "size": 0, "type": "directory"}) + if ex is not None and not details: + raise ex + if detail: + return details + return sorted(_["name"] for _ in details) + + def info(self, path, **kwargs): + path = self._strip_protocol(path) + if self._intrans: + f = [_ for _ in self.transaction.files if _.path == path] + if f: + size = os.path.getsize(f[0].fn) if f[0].closed else f[0].tell() + return {"name": path, "size": size, "type": "file"} + f = any(_.path.startswith(path + "/") for _ in self.transaction.files) + if f: + return {"name": path, "size": 0, "type": "directory"} + return self.fs.info(path, **kwargs) + + def pipe(self, path, value=None, **kwargs): + if isinstance(path, str): + self.pipe_file(self._strip_protocol(path), value, **kwargs) + elif isinstance(path, dict): + for k, v in path.items(): + self.pipe_file(self._strip_protocol(k), v, **kwargs) + else: + raise ValueError("path must be str or dict") + + def cat_ranges( + self, paths, starts, ends, max_gap=None, on_error="return", **kwargs + ): + logger.debug("cat ranges %s", paths) + lpaths = [self._check_file(p) for p in paths] + rpaths = [p for l, p in zip(lpaths, paths) if l is False] + lpaths = [l for l, p in zip(lpaths, paths) if l is False] + self.fs.get(rpaths, lpaths) + paths = [self._check_file(p) for p in paths] + return LocalFileSystem().cat_ranges( + paths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs + ) + + def _get_cached_file_before_open(self, path, **kwargs): + sha = self._mapper(path) + fn = os.path.join(self.storage[-1], sha) + logger.debug("Copying %s to local cache", path) + + self._mkcache() + self._cache_size = None + + if self.compression: + with self.fs._open(path, mode="rb", **kwargs) as f, open(fn, "wb") as f2: + if isinstance(f, AbstractBufferedFile): + # want no type of caching if just downloading whole thing + f.cache = BaseCache(0, f.cache.fetcher, f.size) + comp = ( + infer_compression(path) + if self.compression == "infer" + else self.compression + ) + f = compr[comp](f, mode="rb") + data = True + while data: + block = getattr(f, "blocksize", 5 * 2**20) + data = f.read(block) + f2.write(data) + else: + self.fs.get_file(path, fn) + + def _open(self, path, mode="rb", **kwargs): + path = self._strip_protocol(path) + sha = self._mapper(path) + + # For read (or append), (try) download from remote + if "r" in mode or "a" in mode: + if not self._check_file(path): + # append does not require an existing file but read does + if self.fs.exists(path): + self._get_cached_file_before_open(path, **kwargs) + elif "r" in mode: + raise FileNotFoundError(path) + + fn = self._check_file(path) + # Just reading does not need special file handling + if "r" in mode and "+" not in mode: + return open(fn, mode) + + fn = os.path.join(self.storage[-1], sha) + user_specified_kwargs = { + k: v + for k, v in kwargs.items() + if k not in ["autocommit", "block_size", "cache_options"] + } # those were added by open() + return LocalTempFile( + self, + path, + mode=mode, + autocommit=not self._intrans, + fn=fn, + **user_specified_kwargs, + ) + + +class LocalTempFile: + """A temporary local file, which will be uploaded on commit""" + + def __init__(self, fs, path, fn, mode="wb", autocommit=True, seek=0, **kwargs): + self.fn = fn + self.fh = open(fn, mode) + self.mode = mode + if seek: + self.fh.seek(seek) + self.path = path + self.size = None + self.fs = fs + self.closed = False + self.autocommit = autocommit + self.kwargs = kwargs + + def __reduce__(self): + # always open in r+b to allow continuing writing at a location + return ( + LocalTempFile, + (self.fs, self.path, self.fn, "r+b", self.autocommit, self.tell()), + ) + + def __enter__(self): + return self.fh + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def close(self): + # self.size = self.fh.tell() + if self.closed: + return + self.fh.close() + self.closed = True + if self.autocommit: + self.commit() + + def discard(self): + self.fh.close() + os.remove(self.fn) + + def commit(self): + # calling put() with list arguments avoids path expansion and additional operations + # like isdir() + self.fs.put([self.fn], [self.path], **self.kwargs) + # we do not delete the local copy, it's still in the cache. + + @property + def name(self): + return self.fn + + def __repr__(self) -> str: + return f"LocalTempFile: {self.path}" + + def __getattr__(self, item): + return getattr(self.fh, item) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/chained.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/chained.py new file mode 100644 index 0000000000000000000000000000000000000000..bfce64334e8db0272eefa96b4428b23524b059f0 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/chained.py @@ -0,0 +1,23 @@ +from typing import ClassVar + +from fsspec import AbstractFileSystem + +__all__ = ("ChainedFileSystem",) + + +class ChainedFileSystem(AbstractFileSystem): + """Chained filesystem base class. + + A chained filesystem is designed to be layered over another FS. + This is useful to implement things like caching. + + This base class does very little on its own, but is used as a marker + that the class is designed for chaining. + + Right now this is only used in `url_to_fs` to provide the path argument + (`fo`) to the chained filesystem from the underlying filesystem. + + Additional functionality may be added in the future. + """ + + protocol: ClassVar[str] = "chained" diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/dask.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/dask.py new file mode 100644 index 0000000000000000000000000000000000000000..3e1276463db6866665e6a0fe114efc247971b57e --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/dask.py @@ -0,0 +1,152 @@ +import dask +from distributed.client import Client, _get_global_client +from distributed.worker import Worker + +from fsspec import filesystem +from fsspec.spec import AbstractBufferedFile, AbstractFileSystem +from fsspec.utils import infer_storage_options + + +def _get_client(client): + if client is None: + return _get_global_client() + elif isinstance(client, Client): + return client + else: + # e.g., connection string + return Client(client) + + +def _in_worker(): + return bool(Worker._instances) + + +class DaskWorkerFileSystem(AbstractFileSystem): + """View files accessible to a worker as any other remote file-system + + When instances are run on the worker, uses the real filesystem. When + run on the client, they call the worker to provide information or data. + + **Warning** this implementation is experimental, and read-only for now. + """ + + def __init__( + self, target_protocol=None, target_options=None, fs=None, client=None, **kwargs + ): + super().__init__(**kwargs) + if not (fs is None) ^ (target_protocol is None): + raise ValueError( + "Please provide one of filesystem instance (fs) or" + " target_protocol, not both" + ) + self.target_protocol = target_protocol + self.target_options = target_options + self.worker = None + self.client = client + self.fs = fs + self._determine_worker() + + @staticmethod + def _get_kwargs_from_urls(path): + so = infer_storage_options(path) + if "host" in so and "port" in so: + return {"client": f"{so['host']}:{so['port']}"} + else: + return {} + + def _determine_worker(self): + if _in_worker(): + self.worker = True + if self.fs is None: + self.fs = filesystem( + self.target_protocol, **(self.target_options or {}) + ) + else: + self.worker = False + self.client = _get_client(self.client) + self.rfs = dask.delayed(self) + + def mkdir(self, *args, **kwargs): + if self.worker: + self.fs.mkdir(*args, **kwargs) + else: + self.rfs.mkdir(*args, **kwargs).compute() + + def rm(self, *args, **kwargs): + if self.worker: + self.fs.rm(*args, **kwargs) + else: + self.rfs.rm(*args, **kwargs).compute() + + def copy(self, *args, **kwargs): + if self.worker: + self.fs.copy(*args, **kwargs) + else: + self.rfs.copy(*args, **kwargs).compute() + + def mv(self, *args, **kwargs): + if self.worker: + self.fs.mv(*args, **kwargs) + else: + self.rfs.mv(*args, **kwargs).compute() + + def ls(self, *args, **kwargs): + if self.worker: + return self.fs.ls(*args, **kwargs) + else: + return self.rfs.ls(*args, **kwargs).compute() + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + if self.worker: + return self.fs._open( + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_options=cache_options, + **kwargs, + ) + else: + return DaskFile( + fs=self, + path=path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_options=cache_options, + **kwargs, + ) + + def fetch_range(self, path, mode, start, end): + if self.worker: + with self._open(path, mode) as f: + f.seek(start) + return f.read(end - start) + else: + return self.rfs.fetch_range(path, mode, start, end).compute() + + +class DaskFile(AbstractBufferedFile): + def __init__(self, mode="rb", **kwargs): + if mode != "rb": + raise ValueError('Remote dask files can only be opened in "rb" mode') + super().__init__(**kwargs) + + def _upload_chunk(self, final=False): + pass + + def _initiate_upload(self): + """Create remote file/upload""" + pass + + def _fetch_range(self, start, end): + """Get the specified set of bytes from remote""" + return self.fs.fetch_range(self.path, self.mode, start, end) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/data.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/data.py new file mode 100644 index 0000000000000000000000000000000000000000..fad1b56d0940a6e5232497475ab32a504e19ec9a --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/data.py @@ -0,0 +1,71 @@ +import base64 +import io +from urllib.parse import unquote + +from fsspec import AbstractFileSystem +from fsspec.utils import stringify_path + + +class DataFileSystem(AbstractFileSystem): + """A handy decoder for data-URLs + + Example + ------- + >>> with fsspec.open("data:,Hello%2C%20World%21") as f: + ... print(f.read()) + b"Hello, World!" + + See https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs + """ + + protocol = "data" + + def __init__(self, **kwargs): + """No parameters for this filesystem""" + super().__init__(**kwargs) + + @classmethod + def _strip_protocol(cls, path): + if isinstance(path, list): + return [cls._strip_protocol(p) for p in path] + path = stringify_path(path) + if path.startswith("data://"): + path = path[7:] + elif path.startswith("data:"): + path = path[5:] + # Do NOT strip trailing slashes, as they may be meaningful base64 characters + # or percent-encoded data content + return path + + def cat_file(self, path, start=None, end=None, **kwargs): + pref, data = path.split(",", 1) + if pref.endswith("base64"): + return base64.b64decode(data)[start:end] + return unquote(data).encode()[start:end] + + def info(self, path, **kwargs): + pref, name = path.split(",", 1) + data = self.cat_file(path) + mime = pref.split(":", 1)[1].split(";", 1)[0] + return {"name": name, "size": len(data), "type": "file", "mimetype": mime} + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + if "r" not in mode: + raise ValueError("Read only filesystem") + return io.BytesIO(self.cat_file(path)) + + @staticmethod + def encode(data: bytes, mime: str | None = None): + """Format the given data into data-URL syntax + + This version always base64 encodes, even when the data is ascii/url-safe. + """ + return f"data:{mime or ''};base64,{base64.b64encode(data).decode()}" diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/dbfs.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/dbfs.py new file mode 100644 index 0000000000000000000000000000000000000000..1b7f03f66c94dccf7880546728ce1c3f110bc10a --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/dbfs.py @@ -0,0 +1,497 @@ +from __future__ import annotations + +import base64 +import urllib + +import requests +from requests.adapters import HTTPAdapter, Retry +from typing_extensions import override + +from fsspec import AbstractFileSystem +from fsspec.spec import AbstractBufferedFile + + +class DatabricksException(Exception): + """ + Helper class for exceptions raised in this module. + """ + + def __init__(self, error_code, message, details=None): + """Create a new DatabricksException""" + super().__init__(message) + + self.error_code = error_code + self.message = message + self.details = details + + +class DatabricksFileSystem(AbstractFileSystem): + """ + Get access to the Databricks filesystem implementation over HTTP. + Can be used inside and outside of a databricks cluster. + """ + + def __init__(self, instance, token, **kwargs): + """ + Create a new DatabricksFileSystem. + + Parameters + ---------- + instance: str + The instance URL of the databricks cluster. + For example for an Azure databricks cluster, this + has the form adb-..azuredatabricks.net. + token: str + Your personal token. Find out more + here: https://docs.databricks.com/dev-tools/api/latest/authentication.html + """ + self.instance = instance + self.token = token + self.session = requests.Session() + self.retries = Retry( + total=10, + backoff_factor=0.05, + status_forcelist=[408, 429, 500, 502, 503, 504], + ) + + self.session.mount("https://", HTTPAdapter(max_retries=self.retries)) + self.session.headers.update({"Authorization": f"Bearer {self.token}"}) + + super().__init__(**kwargs) + + @override + def _ls_from_cache(self, path) -> list[dict[str, str | int]] | None: + """Check cache for listing + + Returns listing, if found (may be empty list for a directory that + exists but contains nothing), None if not in cache. + """ + self.dircache.pop(path.rstrip("/"), None) + + parent = self._parent(path) + if parent in self.dircache: + for entry in self.dircache[parent]: + if entry["name"] == path.rstrip("/"): + if entry["type"] != "directory": + return [entry] + return [] + raise FileNotFoundError(path) + + def ls(self, path, detail=True, **kwargs): + """ + List the contents of the given path. + + Parameters + ---------- + path: str + Absolute path + detail: bool + Return not only the list of filenames, + but also additional information on file sizes + and types. + """ + try: + out = self._ls_from_cache(path) + except FileNotFoundError: + # This happens if the `path`'s parent was cached, but `path` is not + # there. This suggests that `path` is new since the parent was + # cached. Attempt to invalidate parent's cache before continuing. + self.dircache.pop(self._parent(path), None) + out = None + + if not out: + try: + r = self._send_to_api( + method="get", endpoint="list", json={"path": path} + ) + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + raise FileNotFoundError(e.message) from e + + raise + files = r.get("files", []) + out = [ + { + "name": o["path"], + "type": "directory" if o["is_dir"] else "file", + "size": o["file_size"], + } + for o in files + ] + self.dircache[path] = out + + if detail: + return out + return [o["name"] for o in out] + + def makedirs(self, path, exist_ok=True): + """ + Create a given absolute path and all of its parents. + + Parameters + ---------- + path: str + Absolute path to create + exist_ok: bool + If false, checks if the folder + exists before creating it (and raises an + Exception if this is the case) + """ + if not exist_ok: + try: + # If the following succeeds, the path is already present + self._send_to_api( + method="get", endpoint="get-status", json={"path": path} + ) + raise FileExistsError(f"Path {path} already exists") + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + pass + + try: + self._send_to_api(method="post", endpoint="mkdirs", json={"path": path}) + except DatabricksException as e: + if e.error_code == "RESOURCE_ALREADY_EXISTS": + raise FileExistsError(e.message) from e + + raise + self.invalidate_cache(self._parent(path)) + + def mkdir(self, path, create_parents=True, **kwargs): + """ + Create a given absolute path and all of its parents. + + Parameters + ---------- + path: str + Absolute path to create + create_parents: bool + Whether to create all parents or not. + "False" is not implemented so far. + """ + if not create_parents: + raise NotImplementedError + + self.mkdirs(path, **kwargs) + + def rm(self, path, recursive=False, **kwargs): + """ + Remove the file or folder at the given absolute path. + + Parameters + ---------- + path: str + Absolute path what to remove + recursive: bool + Recursively delete all files in a folder. + """ + try: + self._send_to_api( + method="post", + endpoint="delete", + json={"path": path, "recursive": recursive}, + ) + except DatabricksException as e: + # This is not really an exception, it just means + # not everything was deleted so far + if e.error_code == "PARTIAL_DELETE": + self.rm(path=path, recursive=recursive) + elif e.error_code == "IO_ERROR": + # Using the same exception as the os module would use here + raise OSError(e.message) from e + + raise + self.invalidate_cache(self._parent(path)) + + def mv( + self, source_path, destination_path, recursive=False, maxdepth=None, **kwargs + ): + """ + Move a source to a destination path. + + A note from the original [databricks API manual] + (https://docs.databricks.com/dev-tools/api/latest/dbfs.html#move). + + When moving a large number of files the API call will time out after + approximately 60s, potentially resulting in partially moved data. + Therefore, for operations that move more than 10k files, we strongly + discourage using the DBFS REST API. + + Parameters + ---------- + source_path: str + From where to move (absolute path) + destination_path: str + To where to move (absolute path) + recursive: bool + Not implemented to far. + maxdepth: + Not implemented to far. + """ + if recursive: + raise NotImplementedError + if maxdepth: + raise NotImplementedError + + try: + self._send_to_api( + method="post", + endpoint="move", + json={"source_path": source_path, "destination_path": destination_path}, + ) + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + raise FileNotFoundError(e.message) from e + elif e.error_code == "RESOURCE_ALREADY_EXISTS": + raise FileExistsError(e.message) from e + + raise + self.invalidate_cache(self._parent(source_path)) + self.invalidate_cache(self._parent(destination_path)) + + def _open(self, path, mode="rb", block_size="default", **kwargs): + """ + Overwrite the base class method to make sure to create a DBFile. + All arguments are copied from the base method. + + Only the default blocksize is allowed. + """ + return DatabricksFile(self, path, mode=mode, block_size=block_size, **kwargs) + + def _send_to_api(self, method, endpoint, json): + """ + Send the given json to the DBFS API + using a get or post request (specified by the argument `method`). + + Parameters + ---------- + method: str + Which http method to use for communication; "get" or "post". + endpoint: str + Where to send the request to (last part of the API URL) + json: dict + Dictionary of information to send + """ + if method == "post": + session_call = self.session.post + elif method == "get": + session_call = self.session.get + else: + raise ValueError(f"Do not understand method {method}") + + url = urllib.parse.urljoin(f"https://{self.instance}/api/2.0/dbfs/", endpoint) + + r = session_call(url, json=json) + + # The DBFS API will return a json, also in case of an exception. + # We want to preserve this information as good as possible. + try: + r.raise_for_status() + except requests.HTTPError as e: + # try to extract json error message + # if that fails, fall back to the original exception + try: + exception_json = e.response.json() + except Exception: + raise e from None + + raise DatabricksException(**exception_json) from e + + return r.json() + + def _create_handle(self, path, overwrite=True): + """ + Internal function to create a handle, which can be used to + write blocks of a file to DBFS. + A handle has a unique identifier which needs to be passed + whenever written during this transaction. + The handle is active for 10 minutes - after that a new + write transaction needs to be created. + Make sure to close the handle after you are finished. + + Parameters + ---------- + path: str + Absolute path for this file. + overwrite: bool + If a file already exist at this location, either overwrite + it or raise an exception. + """ + try: + r = self._send_to_api( + method="post", + endpoint="create", + json={"path": path, "overwrite": overwrite}, + ) + return r["handle"] + except DatabricksException as e: + if e.error_code == "RESOURCE_ALREADY_EXISTS": + raise FileExistsError(e.message) from e + + raise + + def _close_handle(self, handle): + """ + Close a handle, which was opened by :func:`_create_handle`. + + Parameters + ---------- + handle: str + Which handle to close. + """ + try: + self._send_to_api(method="post", endpoint="close", json={"handle": handle}) + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + raise FileNotFoundError(e.message) from e + + raise + + def _add_data(self, handle, data): + """ + Upload data to an already opened file handle + (opened by :func:`_create_handle`). + The maximal allowed data size is 1MB after + conversion to base64. + Remember to close the handle when you are finished. + + Parameters + ---------- + handle: str + Which handle to upload data to. + data: bytes + Block of data to add to the handle. + """ + data = base64.b64encode(data).decode() + try: + self._send_to_api( + method="post", + endpoint="add-block", + json={"handle": handle, "data": data}, + ) + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + raise FileNotFoundError(e.message) from e + elif e.error_code == "MAX_BLOCK_SIZE_EXCEEDED": + raise ValueError(e.message) from e + + raise + + def _get_data(self, path, start, end): + """ + Download data in bytes from a given absolute path in a block + from [start, start+length]. + The maximum number of allowed bytes to read is 1MB. + + Parameters + ---------- + path: str + Absolute path to download data from + start: int + Start position of the block + end: int + End position of the block + """ + try: + r = self._send_to_api( + method="get", + endpoint="read", + json={"path": path, "offset": start, "length": end - start}, + ) + return base64.b64decode(r["data"]) + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + raise FileNotFoundError(e.message) from e + elif e.error_code in ["INVALID_PARAMETER_VALUE", "MAX_READ_SIZE_EXCEEDED"]: + raise ValueError(e.message) from e + + raise + + def invalidate_cache(self, path=None): + if path is None: + self.dircache.clear() + else: + self.dircache.pop(path, None) + super().invalidate_cache(path) + + +class DatabricksFile(AbstractBufferedFile): + """ + Helper class for files referenced in the DatabricksFileSystem. + """ + + DEFAULT_BLOCK_SIZE = 1 * 2**20 # only allowed block size + + def __init__( + self, + fs, + path, + mode="rb", + block_size="default", + autocommit=True, + cache_type="readahead", + cache_options=None, + **kwargs, + ): + """ + Create a new instance of the DatabricksFile. + + The blocksize needs to be the default one. + """ + if block_size is None or block_size == "default": + block_size = self.DEFAULT_BLOCK_SIZE + + if block_size != self.DEFAULT_BLOCK_SIZE: + raise ValueError( + f"Only the default block size is allowed, not {block_size}" + ) + + super().__init__( + fs, + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_type=cache_type, + cache_options=cache_options or {}, + **kwargs, + ) + + def _initiate_upload(self): + """Internal function to start a file upload""" + self.handle = self.fs._create_handle(self.path) + + def _upload_chunk(self, final=False): + """Internal function to add a chunk of data to a started upload""" + self.buffer.seek(0) + data = self.buffer.getvalue() + + data_chunks = [ + data[start:end] for start, end in self._to_sized_blocks(len(data)) + ] + + for data_chunk in data_chunks: + self.fs._add_data(handle=self.handle, data=data_chunk) + + if final: + self.fs._close_handle(handle=self.handle) + return True + + def _fetch_range(self, start, end): + """Internal function to download a block of data""" + return_buffer = b"" + length = end - start + for chunk_start, chunk_end in self._to_sized_blocks(length, start): + return_buffer += self.fs._get_data( + path=self.path, start=chunk_start, end=chunk_end + ) + + return return_buffer + + def _to_sized_blocks(self, length, start=0): + """Helper function to split a range from 0 to total_length into blocksizes""" + end = start + length + for data_chunk in range(start, end, self.blocksize): + data_start = data_chunk + data_end = min(end, data_chunk + self.blocksize) + yield data_start, data_end diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/dirfs.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/dirfs.py new file mode 100644 index 0000000000000000000000000000000000000000..0fe1ababfe5a7749ed75cc1c29bedea492c8f1f4 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/dirfs.py @@ -0,0 +1,426 @@ +from .. import filesystem +from ..asyn import AsyncFileSystem +from .chained import ChainedFileSystem +from .local import LocalFileSystem + + +def _escapes_root(path): + """Whether a relative path would resolve above its root via ".." segments.""" + depth = 0 + for part in path.split("/"): + if part == "..": + depth -= 1 + if depth < 0: + return True + elif part and part != ".": + depth += 1 + return False + + +class DirFileSystem(AsyncFileSystem, ChainedFileSystem): + """Directory prefix filesystem + + The DirFileSystem is a filesystem-wrapper. It assumes every path it is dealing with + is relative to the `path`. After performing the necessary paths operation it + delegates everything to the wrapped filesystem. + """ + + protocol = "dir" + + def __init__( + self, + path=None, + fs=None, + fo=None, + target_protocol=None, + target_options=None, + **storage_options, + ): + """ + Parameters + ---------- + path: str + Path to the directory. + fs: AbstractFileSystem + An instantiated filesystem to wrap. + target_protocol, target_options: + if fs is none, construct it from these + fo: str + Alternate for path; do not provide both + """ + super().__init__(**storage_options) + if fs is None: + fs = filesystem(protocol=target_protocol, **(target_options or {})) + path = path or fo + + if self.asynchronous and not fs.async_impl: + raise ValueError("can't use asynchronous with non-async fs") + + if fs.async_impl and self.asynchronous != fs.asynchronous: + raise ValueError("both dirfs and fs should be in the same sync/async mode") + + self.path = fs._strip_protocol(path) + self.fs = fs + + def _join(self, path): + if isinstance(path, str): + if not self.path: + return path + if not path: + return self.path + path = self._strip_protocol(path) + # ".." only navigates above the root on filesystems that resolve it + # against a real directory tree; on object stores it is a literal + # path part, so only guard the local case here. + if isinstance(self.fs, LocalFileSystem) and _escapes_root(path): + raise ValueError( + f"path {path!r} escapes the {self.path!r} root of the filesystem" + ) + return self.fs.sep.join((self.path, path)) + if isinstance(path, dict): + return {self._join(_path): value for _path, value in path.items()} + return [self._join(_path) for _path in path] + + def _relpath(self, path): + if isinstance(path, str): + if not self.path: + return path + # We need to account for S3FileSystem returning paths that do not + # start with a '/' + if path == self.path or ( + self.path.startswith(self.fs.sep) and path == self.path[1:] + ): + return "" + prefix = self.path + self.fs.sep + if self.path.startswith(self.fs.sep) and not path.startswith(self.fs.sep): + prefix = prefix[1:] + assert path.startswith(prefix) + return path[len(prefix) :] + return [self._relpath(_path) for _path in path] + + # Wrappers below + + @property + def sep(self): + return self.fs.sep + + async def set_session(self, *args, **kwargs): + return await self.fs.set_session(*args, **kwargs) + + async def _rm_file(self, path, **kwargs): + return await self.fs._rm_file(self._join(path), **kwargs) + + def rm_file(self, path, **kwargs): + return self.fs.rm_file(self._join(path), **kwargs) + + async def _rm(self, path, *args, **kwargs): + return await self.fs._rm(self._join(path), *args, **kwargs) + + def rm(self, path, *args, **kwargs): + return self.fs.rm(self._join(path), *args, **kwargs) + + def delete(self, path, recursive=False, maxdepth=None): + return self.fs.delete(self._join(path), recursive=recursive, maxdepth=maxdepth) + + async def _cp_file(self, path1, path2, **kwargs): + return await self.fs._cp_file(self._join(path1), self._join(path2), **kwargs) + + def cp_file(self, path1, path2, **kwargs): + return self.fs.cp_file(self._join(path1), self._join(path2), **kwargs) + + async def _copy( + self, + path1, + path2, + *args, + **kwargs, + ): + return await self.fs._copy( + self._join(path1), + self._join(path2), + *args, + **kwargs, + ) + + def copy(self, path1, path2, *args, **kwargs): + return self.fs.copy( + self._join(path1), + self._join(path2), + *args, + **kwargs, + ) + + async def _pipe(self, path, *args, **kwargs): + return await self.fs._pipe(self._join(path), *args, **kwargs) + + def pipe(self, path, *args, **kwargs): + return self.fs.pipe(self._join(path), *args, **kwargs) + + async def _pipe_file(self, path, *args, **kwargs): + return await self.fs._pipe_file(self._join(path), *args, **kwargs) + + def pipe_file(self, path, *args, **kwargs): + return self.fs.pipe_file(self._join(path), *args, **kwargs) + + def write_text( + self, path, value, encoding=None, errors=None, newline=None, **kwargs + ): + return self.fs.write_text( + self._join(path), + value, + encoding=encoding, + errors=errors, + newline=newline, + **kwargs, + ) + + async def _cat_file(self, path, *args, **kwargs): + return await self.fs._cat_file(self._join(path), *args, **kwargs) + + def cat_file(self, path, *args, **kwargs): + return self.fs.cat_file(self._join(path), *args, **kwargs) + + async def _cat(self, path, *args, **kwargs): + ret = await self.fs._cat( + self._join(path), + *args, + **kwargs, + ) + + if isinstance(ret, dict): + return {self._relpath(key): value for key, value in ret.items()} + + return ret + + def cat(self, path, *args, **kwargs): + ret = self.fs.cat( + self._join(path), + *args, + **kwargs, + ) + + if isinstance(ret, dict): + return {self._relpath(key): value for key, value in ret.items()} + + return ret + + async def _put_file(self, lpath, rpath, **kwargs): + return await self.fs._put_file(lpath, self._join(rpath), **kwargs) + + def put_file(self, lpath, rpath, **kwargs): + return self.fs.put_file(lpath, self._join(rpath), **kwargs) + + async def _put( + self, + lpath, + rpath, + *args, + **kwargs, + ): + return await self.fs._put( + lpath, + self._join(rpath), + *args, + **kwargs, + ) + + def put(self, lpath, rpath, *args, **kwargs): + return self.fs.put( + lpath, + self._join(rpath), + *args, + **kwargs, + ) + + async def _get_file(self, rpath, lpath, **kwargs): + return await self.fs._get_file(self._join(rpath), lpath, **kwargs) + + def get_file(self, rpath, lpath, **kwargs): + return self.fs.get_file(self._join(rpath), lpath, **kwargs) + + async def _get(self, rpath, *args, **kwargs): + return await self.fs._get(self._join(rpath), *args, **kwargs) + + def get(self, rpath, *args, **kwargs): + return self.fs.get(self._join(rpath), *args, **kwargs) + + async def _isfile(self, path): + return await self.fs._isfile(self._join(path)) + + def isfile(self, path): + return self.fs.isfile(self._join(path)) + + async def _isdir(self, path): + return await self.fs._isdir(self._join(path)) + + def isdir(self, path): + return self.fs.isdir(self._join(path)) + + async def _size(self, path): + return await self.fs._size(self._join(path)) + + def size(self, path): + return self.fs.size(self._join(path)) + + async def _exists(self, path): + return await self.fs._exists(self._join(path)) + + def exists(self, path): + return self.fs.exists(self._join(path)) + + async def _info(self, path, **kwargs): + info = await self.fs._info(self._join(path), **kwargs) + info = info.copy() + info["name"] = self._relpath(info["name"]) + return info + + def info(self, path, **kwargs): + info = self.fs.info(self._join(path), **kwargs) + info = info.copy() + info["name"] = self._relpath(info["name"]) + return info + + async def _ls(self, path, detail=True, **kwargs): + ret = (await self.fs._ls(self._join(path), detail=detail, **kwargs)).copy() + if detail: + out = [] + for entry in ret: + entry = entry.copy() + entry["name"] = self._relpath(entry["name"]) + out.append(entry) + return out + + return self._relpath(ret) + + def ls(self, path, detail=True, **kwargs): + ret = self.fs.ls(self._join(path), detail=detail, **kwargs).copy() + if detail: + out = [] + for entry in ret: + entry = entry.copy() + entry["name"] = self._relpath(entry["name"]) + out.append(entry) + return out + + return self._relpath(ret) + + async def _walk(self, path, *args, **kwargs): + async for root, dirs, files in self.fs._walk(self._join(path), *args, **kwargs): + yield self._relpath(root), dirs, files + + def walk(self, path, *args, **kwargs): + for root, dirs, files in self.fs.walk(self._join(path), *args, **kwargs): + yield self._relpath(root), dirs, files + + async def _glob(self, path, **kwargs): + detail = kwargs.get("detail", False) + ret = await self.fs._glob(self._join(path), **kwargs) + if detail: + return {self._relpath(path): info for path, info in ret.items()} + return self._relpath(ret) + + def glob(self, path, **kwargs): + detail = kwargs.get("detail", False) + ret = self.fs.glob(self._join(path), **kwargs) + if detail: + return {self._relpath(path): info for path, info in ret.items()} + return self._relpath(ret) + + async def _du(self, path, *args, **kwargs): + total = kwargs.get("total", True) + ret = await self.fs._du(self._join(path), *args, **kwargs) + if total: + return ret + + return {self._relpath(path): size for path, size in ret.items()} + + def du(self, path, *args, **kwargs): + total = kwargs.get("total", True) + ret = self.fs.du(self._join(path), *args, **kwargs) + if total: + return ret + + return {self._relpath(path): size for path, size in ret.items()} + + async def _find(self, path, *args, **kwargs): + detail = kwargs.get("detail", False) + ret = await self.fs._find(self._join(path), *args, **kwargs) + if detail: + return {self._relpath(path): info for path, info in ret.items()} + return self._relpath(ret) + + def find(self, path, *args, **kwargs): + detail = kwargs.get("detail", False) + ret = self.fs.find(self._join(path), *args, **kwargs) + if detail: + return {self._relpath(path): info for path, info in ret.items()} + return self._relpath(ret) + + async def _expand_path(self, path, *args, **kwargs): + return self._relpath( + await self.fs._expand_path(self._join(path), *args, **kwargs) + ) + + def expand_path(self, path, *args, **kwargs): + return self._relpath(self.fs.expand_path(self._join(path), *args, **kwargs)) + + async def _mkdir(self, path, *args, **kwargs): + return await self.fs._mkdir(self._join(path), *args, **kwargs) + + def mkdir(self, path, *args, **kwargs): + return self.fs.mkdir(self._join(path), *args, **kwargs) + + async def _makedirs(self, path, *args, **kwargs): + return await self.fs._makedirs(self._join(path), *args, **kwargs) + + def makedirs(self, path, *args, **kwargs): + return self.fs.makedirs(self._join(path), *args, **kwargs) + + def rmdir(self, path): + return self.fs.rmdir(self._join(path)) + + def mv(self, path1, path2, **kwargs): + return self.fs.mv( + self._join(path1), + self._join(path2), + **kwargs, + ) + + def touch(self, path, **kwargs): + return self.fs.touch(self._join(path), **kwargs) + + def created(self, path): + return self.fs.created(self._join(path)) + + def modified(self, path): + return self.fs.modified(self._join(path)) + + def sign(self, path, *args, **kwargs): + return self.fs.sign(self._join(path), *args, **kwargs) + + def __repr__(self): + return f"{self.__class__.__qualname__}(path='{self.path}', fs={self.fs})" + + def open( + self, + path, + *args, + **kwargs, + ): + return self.fs.open( + self._join(path), + *args, + **kwargs, + ) + + async def open_async( + self, + path, + *args, + **kwargs, + ): + return await self.fs.open_async( + self._join(path), + *args, + **kwargs, + ) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/ftp.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/ftp.py new file mode 100644 index 0000000000000000000000000000000000000000..5f20d4302c460e2460c6ab1bd99b07904fc765cb --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/ftp.py @@ -0,0 +1,442 @@ +import os +import ssl +import uuid +from ftplib import FTP, FTP_TLS, Error, error_perm +from typing import Any + +from ..spec import AbstractBufferedFile, AbstractFileSystem +from ..utils import infer_storage_options, isfilelike + +SECURITY_PROTOCOL_MAP = { + "tls": ssl.PROTOCOL_TLS, + "sslv23": ssl.PROTOCOL_SSLv23, +} +for protocol in ["TLSv1", "TLSv1_1", "TLSv1_2"]: + if hasattr(ssl, f"PROTOCOL_{protocol}"): + SECURITY_PROTOCOL_MAP[protocol.lower()] = getattr(ssl, f"PROTOCOL_{protocol}") + + +class ImplicitFTPTLS(FTP_TLS): + """ + FTP_TLS subclass that automatically wraps sockets in SSL + to support implicit FTPS. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._sock = None + + @property + def sock(self): + """Return the socket.""" + return self._sock + + @sock.setter + def sock(self, value): + """When modifying the socket, ensure that it is ssl wrapped.""" + if value is not None and not isinstance(value, ssl.SSLSocket): + value = self.context.wrap_socket(value) + self._sock = value + + +class FTPFileSystem(AbstractFileSystem): + """A filesystem over classic FTP""" + + root_marker = "/" + cachable = False + protocol = "ftp" + + def __init__( + self, + host, + port=21, + username=None, + password=None, + acct=None, + block_size=None, + tempdir=None, + timeout=30, + encoding="utf-8", + tls=False, + **kwargs, + ): + """ + You can use _get_kwargs_from_urls to get some kwargs from + a reasonable FTP url. + + Authentication will be anonymous if username/password are not + given. + + Parameters + ---------- + host: str + The remote server name/ip to connect to + port: int + Port to connect with + username: str or None + If authenticating, the user's identifier + password: str of None + User's password on the server, if using + acct: str or None + Some servers also need an "account" string for auth + block_size: int or None + If given, the read-ahead or write buffer size. + tempdir: str + Directory on remote to put temporary files when in a transaction + timeout: int + Timeout of the ftp connection in seconds + encoding: str + Encoding to use for directories and filenames in FTP connection + tls: bool or str + Enable FTP-TLS for secure connections: + - False: Plain FTP (default) + - True: Explicit TLS (FTPS with AUTH TLS command) + - "tls": Auto-negotiate highest protocol + - "tlsv1": TLS v1.0 + - "tlsv1_1": TLS v1.1 + - "tlsv1_2": TLS v1.2 + """ + super().__init__(**kwargs) + self.host = host + self.port = port + self.tempdir = tempdir or "/tmp" + self.cred = username or "", password or "", acct or "" + self.timeout = timeout + self.encoding = encoding + if block_size is not None: + self.blocksize = block_size + else: + self.blocksize = 2**16 + self.tls = tls + self._connect() + if isinstance(self.tls, bool) and self.tls: + self.ftp.prot_p() + + def _connect(self): + security = None + if self.tls: + if isinstance(self.tls, str): + ftp_cls = ImplicitFTPTLS + security = SECURITY_PROTOCOL_MAP.get( + self.tls, + f"Not supported {self.tls} protocol", + ) + if isinstance(security, str): + raise ValueError(security) + else: + ftp_cls = FTP_TLS + else: + ftp_cls = FTP + self.ftp = ftp_cls(timeout=self.timeout, encoding=self.encoding) + if security: + self.ftp.ssl_version = security + self.ftp.connect(self.host, self.port) + self.ftp.login(*self.cred) + + @classmethod + def _strip_protocol(cls, path): + return "/" + infer_storage_options(path)["path"].lstrip("/").rstrip("/") + + @staticmethod + def _get_kwargs_from_urls(urlpath): + out = infer_storage_options(urlpath) + out.pop("path", None) + out.pop("protocol", None) + return out + + def ls(self, path, detail=True, **kwargs): + path = self._strip_protocol(path) + out = [] + if path not in self.dircache: + try: + try: + out = [ + (fn, details) + for (fn, details) in self.ftp.mlsd(path) + if fn not in [".", ".."] + and details["type"] not in ["pdir", "cdir"] + ] + except error_perm: + out = _mlsd2(self.ftp, path) # Not platform independent + for fn, details in out: + details["name"] = "/".join( + ["" if path == "/" else path, fn.lstrip("/")] + ) + if details["type"] == "file": + details["size"] = int(details["size"]) + else: + details["size"] = 0 + if details["type"] == "dir": + details["type"] = "directory" + self.dircache[path] = out + except Error: + try: + info = self.info(path) + if info["type"] == "file": + out = [(path, info)] + except (Error, IndexError) as exc: + raise FileNotFoundError(path) from exc + files = self.dircache.get(path, out) + if not detail: + return sorted([fn for fn, details in files]) + return [details for fn, details in files] + + def info(self, path, **kwargs): + # implement with direct method + path = self._strip_protocol(path) + if path == "/": + # special case, since this dir has no real entry + return {"name": "/", "size": 0, "type": "directory"} + files = self.ls(self._parent(path).lstrip("/"), True) + try: + out = next(f for f in files if f["name"] == path) + except StopIteration as exc: + raise FileNotFoundError(path) from exc + return out + + def get_file(self, rpath, lpath, **kwargs): + if self.isdir(rpath): + if not os.path.exists(lpath): + os.mkdir(lpath) + return + if isfilelike(lpath): + outfile = lpath + else: + outfile = open(lpath, "wb") + + def cb(x): + outfile.write(x) + + self.ftp.retrbinary( + f"RETR {rpath}", + blocksize=self.blocksize, + callback=cb, + ) + if not isfilelike(lpath): + outfile.close() + + def cat_file(self, path, start=None, end=None, **kwargs): + if end is not None: + return super().cat_file(path, start, end, **kwargs) + out = [] + + def cb(x): + out.append(x) + + try: + self.ftp.retrbinary( + f"RETR {path}", + blocksize=self.blocksize, + rest=start, + callback=cb, + ) + except (Error, error_perm) as orig_exc: + raise FileNotFoundError(path) from orig_exc + return b"".join(out) + + def _open( + self, + path, + mode="rb", + block_size=None, + cache_options=None, + autocommit=True, + **kwargs, + ): + path = self._strip_protocol(path) + block_size = block_size or self.blocksize + return FTPFile( + self, + path, + mode=mode, + block_size=block_size, + tempdir=self.tempdir, + autocommit=autocommit, + cache_options=cache_options, + ) + + def _rm(self, path): + path = self._strip_protocol(path) + self.ftp.delete(path) + self.invalidate_cache(self._parent(path)) + + def rm(self, path, recursive=False, maxdepth=None): + paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth) + for p in reversed(paths): + if self.isfile(p): + self.rm_file(p) + else: + self.rmdir(p) + + def mkdir(self, path: str, create_parents: bool = True, **kwargs: Any) -> None: + path = self._strip_protocol(path) + parent = self._parent(path) + if parent != self.root_marker and not self.exists(parent) and create_parents: + self.mkdir(parent, create_parents=create_parents) + + self.ftp.mkd(path) + self.invalidate_cache(self._parent(path)) + + def makedirs(self, path: str, exist_ok: bool = False) -> None: + path = self._strip_protocol(path) + if self.exists(path): + # NB: "/" does not "exist" as it has no directory entry + if not exist_ok: + raise FileExistsError(f"{path} exists without `exist_ok`") + # exists_ok=True -> no-op + else: + self.mkdir(path, create_parents=True) + + def rmdir(self, path): + path = self._strip_protocol(path) + self.ftp.rmd(path) + self.invalidate_cache(self._parent(path)) + + def mv(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1) + path2 = self._strip_protocol(path2) + self.ftp.rename(path1, path2) + self.invalidate_cache(self._parent(path1)) + self.invalidate_cache(self._parent(path2)) + + def __del__(self): + self.ftp.close() + + def invalidate_cache(self, path=None): + if path is None: + self.dircache.clear() + else: + self.dircache.pop(path, None) + super().invalidate_cache(path) + + +class TransferDone(Exception): + """Internal exception to break out of transfer""" + + pass + + +class FTPFile(AbstractBufferedFile): + """Interact with a remote FTP file with read/write buffering""" + + def __init__( + self, + fs, + path, + mode="rb", + block_size="default", + autocommit=True, + cache_type="readahead", + cache_options=None, + **kwargs, + ): + super().__init__( + fs, + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_type=cache_type, + cache_options=cache_options, + **kwargs, + ) + if not autocommit: + self.target = self.path + self.path = "/".join([kwargs["tempdir"], str(uuid.uuid4())]) + + def commit(self): + self.fs.mv(self.path, self.target) + + def discard(self): + self.fs.rm(self.path) + + def _fetch_range(self, start, end): + """Get bytes between given byte limits + + Implemented by raising an exception in the fetch callback when the + number of bytes received reaches the requested amount. + + Will fail if the server does not respect the REST command on + retrieve requests. + """ + out = [] + total = [0] + + def callback(x): + total[0] += len(x) + if total[0] > end - start: + out.append(x[: (end - start) - total[0]]) + if end < self.size: + raise TransferDone + else: + out.append(x) + + if total[0] == end - start and end < self.size: + raise TransferDone + + try: + self.fs.ftp.retrbinary( + f"RETR {self.path}", + blocksize=self.blocksize, + rest=start, + callback=callback, + ) + except TransferDone: + try: + # stop transfer, we got enough bytes for this block + self.fs.ftp.abort() + self.fs.ftp.getmultiline() + except Error: + self.fs._connect() + + return b"".join(out) + + def _upload_chunk(self, final=False): + self.buffer.seek(0) + self.fs.ftp.storbinary( + f"STOR {self.path}", self.buffer, blocksize=self.blocksize, rest=self.offset + ) + return True + + +def _mlsd2(ftp, path="."): + """ + Fall back to using `dir` instead of `mlsd` if not supported. + + This parses a Linux style `ls -l` response to `dir`, but the response may + be platform dependent. + + Parameters + ---------- + ftp: ftplib.FTP + path: str + Expects to be given path, but defaults to ".". + """ + lines = [] + minfo = [] + ftp.dir(path, lines.append) + for line in lines: + split_line = line.split(maxsplit=8) + if len(split_line) < 9: + continue + name = split_line[8] + unix_mode = split_line[0] + if unix_mode[0] == "l" and " -> " in name: + # Symbolic link: " -> "; keep only the link name. + name = name.split(" -> ", 1)[0] + this = ( + name, + { + "modify": " ".join(split_line[5:8]), + "unix.owner": split_line[2], + "unix.group": split_line[3], + "unix.mode": unix_mode, + "size": split_line[4], + }, + ) + if this[1]["unix.mode"][0] == "d": + this[1]["type"] = "dir" + else: + this[1]["type"] = "file" + minfo.append(this) + return minfo diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/gist.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/gist.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9ac0b6a1cdbcfba6188e2cdeab2350bb9aad0a --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/gist.py @@ -0,0 +1,241 @@ +import requests + +from ..spec import AbstractFileSystem +from ..utils import infer_storage_options +from .memory import MemoryFile + + +class GistFileSystem(AbstractFileSystem): + """ + Interface to files in a single GitHub Gist. + + Provides read-only access to a gist's files. Gists do not contain + subdirectories, so file listing is straightforward. + + Parameters + ---------- + gist_id: str + The ID of the gist you want to access (the long hex value from the URL). + filenames: list[str] (optional) + If provided, only make a file system representing these files, and do not fetch + the list of all files for this gist. + sha: str (optional) + If provided, fetch a particular revision of the gist. If omitted, + the latest revision is used. + username: str (optional) + GitHub username for authentication. + token: str (optional) + GitHub personal access token (required if username is given), or. + timeout: (float, float) or float, optional + Connect and read timeouts for requests (default 60s each). + kwargs: dict + Stored on `self.request_kw` and passed to `requests.get` when fetching Gist + metadata or reading ("opening") a file. + """ + + protocol = "gist" + gist_url = "https://api.github.com/gists/{gist_id}" + gist_rev_url = "https://api.github.com/gists/{gist_id}/{sha}" + + def __init__( + self, + gist_id, + filenames=None, + sha=None, + username=None, + token=None, + timeout=None, + **kwargs, + ): + super().__init__() + self.gist_id = gist_id + self.filenames = filenames + self.sha = sha # revision of the gist (optional) + if username is not None and token is None: + raise ValueError("User auth requires a token") + self.username = username + self.token = token + self.request_kw = kwargs + # Default timeouts to 60s connect/read if none provided + self.timeout = timeout if timeout is not None else (60, 60) + + # We use a single-level "directory" cache, because a gist is essentially flat + self.dircache[""] = self._fetch_file_list() + + @property + def kw(self): + """Auth parameters passed to 'requests' if we have username/token.""" + kw = { + "headers": { + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + } + } + kw.update(self.request_kw) + if self.username and self.token: + kw["auth"] = (self.username, self.token) + elif self.token: + kw["headers"]["Authorization"] = f"Bearer {self.token}" + return kw + + def _fetch_gist_metadata(self): + """ + Fetch the JSON metadata for this gist (possibly for a specific revision). + """ + if self.sha: + url = self.gist_rev_url.format(gist_id=self.gist_id, sha=self.sha) + else: + url = self.gist_url.format(gist_id=self.gist_id) + + r = requests.get(url, timeout=self.timeout, **self.kw) + if r.status_code == 404: + raise FileNotFoundError( + f"Gist not found: {self.gist_id}@{self.sha or 'latest'}" + ) + r.raise_for_status() + return r.json() + + def _fetch_file_list(self): + """ + Returns a list of dicts describing each file in the gist. These get stored + in self.dircache[""]. + """ + meta = self._fetch_gist_metadata() + if self.filenames: + available_files = meta.get("files", {}) + files = {} + for fn in self.filenames: + if fn not in available_files: + raise FileNotFoundError(fn) + files[fn] = available_files[fn] + else: + files = meta.get("files", {}) + + out = [] + for fname, finfo in files.items(): + if finfo is None: + # Occasionally GitHub returns a file entry with null if it was deleted + continue + # Build a directory entry + out.append( + { + "name": fname, # file's name + "type": "file", # gists have no subdirectories + "size": finfo.get("size", 0), # file size in bytes + "raw_url": finfo.get("raw_url"), + } + ) + return out + + @classmethod + def _strip_protocol(cls, path): + """ + Remove 'gist://' from the path, if present. + """ + # The default infer_storage_options can handle gist://username:token@id/file + # or gist://id/file, but let's ensure we handle a normal usage too. + # We'll just strip the protocol prefix if it exists. + path = infer_storage_options(path).get("path", path) + return path.lstrip("/") + + @staticmethod + def _get_kwargs_from_urls(path): + """ + Parse 'gist://' style URLs into GistFileSystem constructor kwargs. + For example: + gist://:TOKEN@/file.txt + gist://username:TOKEN@/file.txt + """ + so = infer_storage_options(path) + out = {} + if "username" in so and so["username"]: + out["username"] = so["username"] + if "password" in so and so["password"]: + out["token"] = so["password"] + if "host" in so and so["host"]: + # We interpret 'host' as the gist ID + out["gist_id"] = so["host"] + + # Extract SHA and filename from path + if "path" in so and so["path"]: + path_parts = so["path"].rsplit("/", 2)[-2:] + if len(path_parts) == 2: + if path_parts[0]: # SHA present + out["sha"] = path_parts[0] + if path_parts[1]: # filename also present + out["filenames"] = [path_parts[1]] + + return out + + def ls(self, path="", detail=False, **kwargs): + """ + List files in the gist. Gists are single-level, so any 'path' is basically + the filename, or empty for all files. + + Parameters + ---------- + path : str, optional + The filename to list. If empty, returns all files in the gist. + detail : bool, default False + If True, return a list of dicts; if False, return a list of filenames. + """ + path = self._strip_protocol(path or "") + # If path is empty, return all + if path == "": + results = self.dircache[""] + else: + # We want just the single file with this name + all_files = self.dircache[""] + results = [f for f in all_files if f["name"] == path] + if not results: + raise FileNotFoundError(path) + if detail: + return results + else: + return sorted(f["name"] for f in results) + + def _open(self, path, mode="rb", block_size=None, **kwargs): + """ + Read a single file from the gist. + """ + if mode != "rb": + raise NotImplementedError("GitHub Gist FS is read-only (no write).") + + path = self._strip_protocol(path) + # Find the file entry in our dircache + matches = [f for f in self.dircache[""] if f["name"] == path] + if not matches: + raise FileNotFoundError(path) + finfo = matches[0] + + raw_url = finfo.get("raw_url") + if not raw_url: + raise FileNotFoundError(f"No raw_url for file: {path}") + + r = requests.get(raw_url, timeout=self.timeout, **self.kw) + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + return MemoryFile(path, None, r.content) + + def cat(self, path, recursive=False, on_error="raise", **kwargs): + """ + Return {path: contents} for the given file or files. If 'recursive' is True, + and path is empty, returns all files in the gist. + """ + paths = self.expand_path(path, recursive=recursive) + out = {} + for p in paths: + try: + with self.open(p, "rb") as f: + out[p] = f.read() + except FileNotFoundError as e: + if on_error == "raise": + raise e + elif on_error == "omit": + pass # skip + else: + out[p] = e + if len(paths) == 1 and paths[0] == path: + return out[path] + return out diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/git.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/git.py new file mode 100644 index 0000000000000000000000000000000000000000..808d293a1c991ea87d19a2129f3e56d9b813daaa --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/git.py @@ -0,0 +1,114 @@ +import os + +import pygit2 + +from fsspec.spec import AbstractFileSystem + +from .memory import MemoryFile + + +class GitFileSystem(AbstractFileSystem): + """Browse the files of a local git repo at any hash/tag/branch + + (experimental backend) + """ + + root_marker = "" + cachable = True + + def __init__(self, path=None, fo=None, ref=None, **kwargs): + """ + + Parameters + ---------- + path: str (optional) + Local location of the repo (uses current directory if not given). + May be deprecated in favour of ``fo``. When used with a higher + level function such as fsspec.open(), may be of the form + "git://[path-to-repo[:]][ref@]path/to/file" (but the actual + file path should not contain "@" or ":"). + fo: str (optional) + Same as ``path``, but passed as part of a chained URL. This one + takes precedence if both are given. + ref: str (optional) + Reference to work with, could be a hash, tag or branch name. Defaults + to current working tree. Note that ``ls`` and ``open`` also take hash, + so this becomes the default for those operations + kwargs + """ + super().__init__(**kwargs) + self.repo = pygit2.Repository(fo or path or os.getcwd()) + self.ref = ref or "master" + + @classmethod + def _strip_protocol(cls, path): + path = super()._strip_protocol(path).lstrip("/") + if ":" in path: + path = path.split(":", 1)[1] + if "@" in path: + path = path.split("@", 1)[1] + return path.lstrip("/") + + def _path_to_object(self, path, ref): + comm, ref = self.repo.resolve_refish(ref or self.ref) + parts = path.split("/") + tree = comm.tree + for part in parts: + if part and isinstance(tree, pygit2.Tree): + if part not in tree: + raise FileNotFoundError(path) + tree = tree[part] + return tree + + @staticmethod + def _get_kwargs_from_urls(path): + path = path.removeprefix("git://") + out = {} + if ":" in path: + out["path"], path = path.split(":", 1) + if "@" in path: + out["ref"], path = path.split("@", 1) + return out + + @staticmethod + def _object_to_info(obj, path=None): + # obj.name and obj.filemode are None for the root tree! + is_dir = isinstance(obj, pygit2.Tree) + return { + "type": "directory" if is_dir else "file", + "name": ( + "/".join([path, obj.name or ""]).lstrip("/") if path else obj.name + ), + "hex": str(obj.id), + "mode": "100644" if obj.filemode is None else f"{obj.filemode:o}", + "size": 0 if is_dir else obj.size, + } + + def ls(self, path, detail=True, ref=None, **kwargs): + tree = self._path_to_object(self._strip_protocol(path), ref) + return [ + GitFileSystem._object_to_info(obj, path) + if detail + else GitFileSystem._object_to_info(obj, path)["name"] + for obj in (tree if isinstance(tree, pygit2.Tree) else [tree]) + ] + + def info(self, path, ref=None, **kwargs): + tree = self._path_to_object(self._strip_protocol(path), ref) + return GitFileSystem._object_to_info(tree, path) + + def ukey(self, path, ref=None): + return self.info(path, ref=ref)["hex"] + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + ref=None, + **kwargs, + ): + obj = self._path_to_object(path, ref or self.ref) + return MemoryFile(data=obj.data) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/github.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/github.py new file mode 100644 index 0000000000000000000000000000000000000000..3630f6db54413e2c396f6cc1b6b10cd379200043 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/github.py @@ -0,0 +1,333 @@ +import base64 +import re + +import requests + +from ..spec import AbstractFileSystem +from ..utils import infer_storage_options +from .memory import MemoryFile + + +class GithubFileSystem(AbstractFileSystem): + """Interface to files in github + + An instance of this class provides the files residing within a remote github + repository. You may specify a point in the repos history, by SHA, branch + or tag (default is current master). + + For files less than 1 MB in size, file content is returned directly in a + MemoryFile. For larger files, or for files tracked by git-lfs, file content + is returned as an HTTPFile wrapping the ``download_url`` provided by the + GitHub API. + + When using fsspec.open, allows URIs of the form: + + - "github://path/file", in which case you must specify org, repo and + may specify sha in the extra args + - 'github://org:repo@/precip/catalog.yml', where the org and repo are + part of the URI + - 'github://org:repo@sha/precip/catalog.yml', where the sha is also included + + ``sha`` can be the full or abbreviated hex of the commit you want to fetch + from, or a branch or tag name (so long as it doesn't contain special characters + like "/", "?", which would have to be HTTP-encoded). + + For authorised access, you must provide username and token, which can be made + at https://github.com/settings/tokens + """ + + url = "https://api.github.com/repos/{org}/{repo}/git/trees/{sha}" + content_url = "https://api.github.com/repos/{org}/{repo}/contents/{path}?ref={sha}" + protocol = "github" + timeout = (60, 60) # connect, read timeouts + + def __init__( + self, org, repo, sha=None, username=None, token=None, timeout=None, **kwargs + ): + super().__init__(**kwargs) + self.org = org + self.repo = repo + if (username is None) ^ (token is None): + raise ValueError("Auth required both username and token") + self.username = username + self.token = token + if timeout is not None: + self.timeout = timeout + if sha is None: + # look up default branch (not necessarily "master") + u = "https://api.github.com/repos/{org}/{repo}" + r = requests.get( + u.format(org=org, repo=repo), timeout=self.timeout, **self.kw + ) + r.raise_for_status() + sha = r.json()["default_branch"] + + self.root = sha + self.ls("") + try: + from .http import HTTPFileSystem + + self.http_fs = HTTPFileSystem(**kwargs) + except ImportError: + self.http_fs = None + + @property + def kw(self): + if self.username: + return {"auth": (self.username, self.token)} + return {} + + @classmethod + def repos(cls, org_or_user, is_org=True): + """List repo names for given org or user + + This may become the top level of the FS + + Parameters + ---------- + org_or_user: str + Name of the github org or user to query + is_org: bool (default True) + Whether the name is an organisation (True) or user (False) + + Returns + ------- + List of string + """ + r = requests.get( + f"https://api.github.com/{['users', 'orgs'][is_org]}/{org_or_user}/repos", + timeout=cls.timeout, + ) + r.raise_for_status() + return [repo["name"] for repo in r.json()] + + @property + def tags(self): + """Names of tags in the repo""" + r = requests.get( + f"https://api.github.com/repos/{self.org}/{self.repo}/tags", + timeout=self.timeout, + **self.kw, + ) + r.raise_for_status() + return [t["name"] for t in r.json()] + + @property + def branches(self): + """Names of branches in the repo""" + r = requests.get( + f"https://api.github.com/repos/{self.org}/{self.repo}/branches", + timeout=self.timeout, + **self.kw, + ) + r.raise_for_status() + return [t["name"] for t in r.json()] + + @property + def refs(self): + """Named references, tags and branches""" + return {"tags": self.tags, "branches": self.branches} + + def ls(self, path, detail=False, sha=None, _sha=None, **kwargs): + """List files at given path + + Parameters + ---------- + path: str + Location to list, relative to repo root + detail: bool + If True, returns list of dicts, one per file; if False, returns + list of full filenames only + sha: str (optional) + List at the given point in the repo history, branch or tag name or commit + SHA + _sha: str (optional) + List this specific tree object (used internally to descend into trees) + """ + path = self._strip_protocol(path) + if path == "": + _sha = sha or self.root + if _sha is None: + parts = path.rstrip("/").split("/") + so_far = "" + _sha = sha or self.root + for part in parts: + out = self.ls(so_far, True, sha=sha, _sha=_sha) + so_far += "/" + part if so_far else part + out = [o for o in out if o["name"] == so_far] + if not out: + raise FileNotFoundError(path) + out = out[0] + if out["type"] == "file": + if detail: + return [out] + else: + return path + _sha = out["sha"] + if path not in self.dircache or sha not in [self.root, None]: + r = requests.get( + self.url.format(org=self.org, repo=self.repo, sha=_sha), + timeout=self.timeout, + **self.kw, + ) + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + types = {"blob": "file", "tree": "directory"} + out = [ + { + "name": path + "/" + f["path"] if path else f["path"], + "mode": f["mode"], + "type": types[f["type"]], + "size": f.get("size", 0), + "sha": f["sha"], + } + for f in r.json()["tree"] + if f["type"] in types + ] + if sha in [self.root, None]: + self.dircache[path] = out + else: + out = self.dircache[path] + if detail: + return out + else: + return sorted([f["name"] for f in out]) + + def invalidate_cache(self, path=None): + self.dircache.clear() + + @classmethod + def _strip_protocol(cls, path): + opts = infer_storage_options(path) + if "username" not in opts: + return super()._strip_protocol(path) + return opts["path"].lstrip("/") + + @staticmethod + def _get_kwargs_from_urls(path): + opts = infer_storage_options(path) + if "username" not in opts: + return {} + out = {"org": opts["username"], "repo": opts["password"]} + if opts["host"]: + out["sha"] = opts["host"] + return out + + def _open( + self, + path, + mode="rb", + block_size=None, + cache_options=None, + sha=None, + **kwargs, + ): + if mode != "rb": + raise NotImplementedError + + # construct a url to hit the GitHub API's repo contents API + url = self.content_url.format( + org=self.org, repo=self.repo, path=path, sha=sha or self.root + ) + + # make a request to this API, and parse the response as JSON + r = requests.get(url, timeout=self.timeout, **self.kw) + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + content_json = r.json() + + # if the response's content key is not empty, try to parse it as base64 + if content_json["content"]: + content = base64.b64decode(content_json["content"]) + + # as long as the content does not start with the string + # "version https://git-lfs.github.com/" + # then it is probably not a git-lfs pointer and we can just return + # the content directly + if not content.startswith(b"version https://git-lfs.github.com/"): + return MemoryFile(None, None, content) + + # we land here if the content was not present in the first response + # (regular file over 1MB or git-lfs tracked file) + # in this case, we get let the HTTPFileSystem handle the download + if self.http_fs is None: + raise ImportError( + "Please install fsspec[http] to access github files >1 MB " + "or git-lfs tracked files." + ) + return self.http_fs.open( + content_json["download_url"], + mode=mode, + block_size=block_size, + cache_options=cache_options, + **kwargs, + ) + + def rm(self, path, recursive=False, maxdepth=None, message=None): + path = self.expand_path(path, recursive=recursive, maxdepth=maxdepth) + for p in reversed(path): + self.rm_file(p, message=message) + + def rm_file(self, path, message=None, **kwargs): + """ + Remove a file from a specified branch using a given commit message. + + Since Github DELETE operation requires a branch name, and we can't reliably + determine whether the provided SHA refers to a branch, tag, or commit, we + assume it's a branch. If it's not, the user will encounter an error when + attempting to retrieve the file SHA or delete the file. + + Parameters + ---------- + path: str + The file's location relative to the repository root. + message: str, optional + The commit message for the deletion. + """ + + if not self.username: + raise ValueError("Authentication required") + + path = self._strip_protocol(path) + + # Attempt to get SHA from cache or Github API + sha = self._get_sha_from_cache(path) + if not sha: + url = self.content_url.format( + org=self.org, repo=self.repo, path=path.lstrip("/"), sha=self.root + ) + r = requests.get(url, timeout=self.timeout, **self.kw) + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + sha = r.json()["sha"] + + # Delete the file + delete_url = self.content_url.format( + org=self.org, repo=self.repo, path=path, sha=self.root + ) + branch = self.root + data = { + "message": message or f"Delete {path}", + "sha": sha, + **({"branch": branch} if branch else {}), + } + + r = requests.delete(delete_url, json=data, timeout=self.timeout, **self.kw) + error_message = r.json().get("message", "") + if re.search(r"Branch .+ not found", error_message): + error = "Remove only works when the filesystem is initialised from a branch or default (None)" + raise ValueError(error) + r.raise_for_status() + + self.invalidate_cache(path) + + def _get_sha_from_cache(self, path): + for entries in self.dircache.values(): + for entry in entries: + entry_path = entry.get("name") + if entry_path and entry_path == path and "sha" in entry: + return entry["sha"] + return None diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/http.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/http.py new file mode 100644 index 0000000000000000000000000000000000000000..aff1a955c27091229513b988627de9e806dca8c5 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/http.py @@ -0,0 +1,902 @@ +import asyncio +import io +import logging +import re +import weakref +from copy import copy +from urllib.parse import urlparse + +import aiohttp +import yarl + +from fsspec.asyn import AbstractAsyncStreamedFile, AsyncFileSystem, sync, sync_wrapper +from fsspec.callbacks import DEFAULT_CALLBACK +from fsspec.exceptions import FSTimeoutError +from fsspec.spec import AbstractBufferedFile +from fsspec.utils import ( + DEFAULT_BLOCK_SIZE, + glob_translate, + isfilelike, + nullcontext, + tokenize, +) + +from ..caching import AllBytes + +# https://stackoverflow.com/a/15926317/3821154 +ex = re.compile(r"""<(a|A)\s+(?:[^>]*?\s+)?(href|HREF)=["'](?P[^"']+)""") +ex2 = re.compile(r"""(?Phttp[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""") +logger = logging.getLogger("fsspec.http") + + +async def get_client(**kwargs): + return aiohttp.ClientSession(**kwargs) + + +class HTTPFileSystem(AsyncFileSystem): + """ + Simple File-System for fetching data via HTTP(S) + + ``ls()`` is implemented by loading the parent page and doing a regex + match on the result. If simple_link=True, anything of the form + "http(s)://server.com/stuff?thing=other"; otherwise only links within + HTML href tags will be used. + + URLs are passed unfiltered to aiohttp, so all addresses are accessible. Where URLs are + supplied by a user, the calling application may wish to filter to prevent scanning. + """ + + protocol = ("http", "https") + sep = "/" + + def __init__( + self, + simple_links=True, + block_size=None, + same_scheme=True, + size_policy=None, + cache_type="bytes", + cache_options=None, + asynchronous=False, + loop=None, + client_kwargs=None, + get_client=get_client, + encoded=False, + **storage_options, + ): + """ + NB: if this is called async, you must await set_client + + Parameters + ---------- + block_size: int + Blocks to read bytes; if 0, will default to raw requests file-like + objects instead of HTTPFile instances + simple_links: bool + If True, will consider both HTML tags and anything that looks + like a URL; if False, will consider only the former. + same_scheme: True + When doing ls/glob, if this is True, only consider paths that have + http/https matching the input URLs. + size_policy: this argument is deprecated + client_kwargs: dict + Passed to aiohttp.ClientSession, see + https://docs.aiohttp.org/en/stable/client_reference.html + For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}`` + get_client: Callable[..., aiohttp.ClientSession] + A callable, which takes keyword arguments and constructs + an aiohttp.ClientSession. Its state will be managed by + the HTTPFileSystem class. + storage_options: key-value + Any other parameters passed on to requests + cache_type, cache_options: defaults used in open() + """ + super().__init__(self, asynchronous=asynchronous, loop=loop, **storage_options) + self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE + self.simple_links = simple_links + self.same_schema = same_scheme + self.cache_type = cache_type + self.cache_options = cache_options + self.client_kwargs = client_kwargs or {} + self.get_client = get_client + self.encoded = encoded + self.kwargs = storage_options + self._session = None + + # Clean caching-related parameters from `storage_options` + # before propagating them as `request_options` through `self.kwargs`. + # TODO: Maybe rename `self.kwargs` to `self.request_options` to make + # it clearer. + request_options = copy(storage_options) + self.use_listings_cache = request_options.pop("use_listings_cache", False) + request_options.pop("listings_expiry_time", None) + request_options.pop("max_paths", None) + request_options.pop("skip_instance_cache", None) + self.kwargs = request_options + + @property + def fsid(self): + return "http" + + def encode_url(self, url): + return yarl.URL(url, encoded=self.encoded) + + @staticmethod + def close_session(loop, session): + if loop is not None and loop.is_running(): + try: + sync(loop, session.close, timeout=0.1) + return + except (TimeoutError, FSTimeoutError, NotImplementedError): + pass + connector = getattr(session, "_connector", None) + if connector is not None: + # close after loop is dead + connector._close() + + async def set_session(self): + if self._session is None: + self._session = await self.get_client(loop=self.loop, **self.client_kwargs) + if not self.asynchronous: + weakref.finalize(self, self.close_session, self.loop, self._session) + return self._session + + @classmethod + def _strip_protocol(cls, path): + """For HTTP, we always want to keep the full URL""" + return path + + @classmethod + def _parent(cls, path): + # override, since _strip_protocol is different for URLs + par = super()._parent(path) + if len(par) > 7: # "http://..." + return par + return "" + + async def _ls_real(self, url, detail=True, **kwargs): + # ignoring URL-encoded arguments + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(url) + session = await self.set_session() + async with session.get(self.encode_url(url), **self.kwargs) as r: + self._raise_not_found_for_status(r, url) + + if "Content-Type" in r.headers: + mimetype = r.headers["Content-Type"].partition(";")[0] + else: + mimetype = None + + if mimetype in ("text/html", None): + try: + text = await r.text(errors="ignore") + if self.simple_links: + links = ex2.findall(text) + [u[2] for u in ex.findall(text)] + else: + links = [u[2] for u in ex.findall(text)] + except UnicodeDecodeError: + links = [] # binary, not HTML + else: + links = [] + + out = set() + parts = urlparse(url) + for l in links: + if isinstance(l, tuple): + l = l[1] + if l.startswith("/") and len(l) > 1: + # absolute URL on this server + l = f"{parts.scheme}://{parts.netloc}{l}" + if l.startswith("http"): + if self.same_schema and l.startswith(url.rstrip("/") + "/"): + out.add(l) + elif l.replace("https", "http").startswith( + url.replace("https", "http").rstrip("/") + "/" + ): + # allowed to cross http <-> https + out.add(l) + else: + if l not in ["..", "../"]: + # Ignore FTP-like "parent" + out.add("/".join([url.rstrip("/"), l.lstrip("/")])) + if not out and url.endswith("/"): + out = await self._ls_real(url.rstrip("/"), detail=False) + if detail: + return [ + { + "name": u, + "size": None, + "type": "directory" if u.endswith("/") else "file", + } + for u in out + ] + else: + return sorted(out) + + async def _ls(self, url, detail=True, **kwargs): + if self.use_listings_cache and url in self.dircache: + out = self.dircache[url] + else: + out = await self._ls_real(url, detail=detail, **kwargs) + self.dircache[url] = out + return out + + ls = sync_wrapper(_ls) + + def _raise_not_found_for_status(self, response, url): + """ + Raises FileNotFoundError for 404s, otherwise uses raise_for_status. + """ + if response.status == 404: + raise FileNotFoundError(url) + response.raise_for_status() + + async def _cat_file(self, url, start=None, end=None, **kwargs): + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(url) + + if start is not None or end is not None: + if start == end: + return b"" + headers = kw.pop("headers", {}).copy() + + headers["Range"] = await self._process_limits(url, start, end) + kw["headers"] = headers + session = await self.set_session() + async with session.get(self.encode_url(url), **kw) as r: + out = await r.read() + self._raise_not_found_for_status(r, url) + return out + + async def _get_file( + self, rpath, lpath, chunk_size=5 * 2**20, callback=DEFAULT_CALLBACK, **kwargs + ): + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(rpath) + session = await self.set_session() + async with session.get(self.encode_url(rpath), **kw) as r: + try: + size = int(r.headers["content-length"]) + except (ValueError, KeyError): + size = None + + callback.set_size(size) + self._raise_not_found_for_status(r, rpath) + if isfilelike(lpath): + outfile = lpath + else: + outfile = open(lpath, "wb") # noqa: ASYNC230 + + try: + chunk = True + while chunk: + chunk = await r.content.read(chunk_size) + outfile.write(chunk) + callback.relative_update(len(chunk)) + finally: + if not isfilelike(lpath): + outfile.close() + + async def _put_file( + self, + lpath, + rpath, + chunk_size=5 * 2**20, + callback=DEFAULT_CALLBACK, + method="post", + mode="overwrite", + **kwargs, + ): + if mode != "overwrite": + raise NotImplementedError("Exclusive write") + + async def gen_chunks(): + # Support passing arbitrary file-like objects + # and use them instead of streams. + if isinstance(lpath, io.IOBase): + context = nullcontext(lpath) + use_seek = False # might not support seeking + else: + context = open(lpath, "rb") # noqa: ASYNC230 + use_seek = True + + with context as f: + if use_seek: + callback.set_size(f.seek(0, 2)) + f.seek(0) + else: + callback.set_size(getattr(f, "size", None)) + + chunk = f.read(chunk_size) + while chunk: + yield chunk + callback.relative_update(len(chunk)) + chunk = f.read(chunk_size) + + kw = self.kwargs.copy() + kw.update(kwargs) + session = await self.set_session() + + method = method.lower() + if method not in ("post", "put"): + raise ValueError( + f"method has to be either 'post' or 'put', not: {method!r}" + ) + + meth = getattr(session, method) + async with meth(self.encode_url(rpath), data=gen_chunks(), **kw) as resp: + self._raise_not_found_for_status(resp, rpath) + + async def _exists(self, path, strict=False, **kwargs): + kw = self.kwargs.copy() + kw.update(kwargs) + try: + logger.debug(path) + session = await self.set_session() + r = await session.get(self.encode_url(path), **kw) + async with r: + if strict: + self._raise_not_found_for_status(r, path) + return r.status < 400 + except FileNotFoundError: + return False + except aiohttp.ClientError: + if strict: + raise + return False + + async def _isfile(self, path, **kwargs): + return await self._exists(path, **kwargs) + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=None, # XXX: This differs from the base class. + cache_type=None, + cache_options=None, + size=None, + **kwargs, + ): + """Make a file-like object + + Parameters + ---------- + path: str + Full URL with protocol + mode: string + must be "rb" + block_size: int or None + Bytes to download in one request; use instance value if None. If + zero, will return a streaming Requests file-like instance. + kwargs: key-value + Any other parameters, passed to requests calls + """ + if mode != "rb": + raise NotImplementedError + block_size = block_size if block_size is not None else self.block_size + kw = self.kwargs.copy() + kw["asynchronous"] = self.asynchronous + kw.update(kwargs) + info = {} + size = size or info.update(self.info(path, **kwargs)) or info["size"] + session = sync(self.loop, self.set_session) + if block_size and size and info.get("partial", True): + return HTTPFile( + self, + path, + session=session, + block_size=block_size, + mode=mode, + size=size, + cache_type=cache_type or self.cache_type, + cache_options=cache_options or self.cache_options, + loop=self.loop, + **kw, + ) + else: + return HTTPStreamFile( + self, + path, + mode=mode, + loop=self.loop, + session=session, + **kw, + ) + + async def open_async(self, path, mode="rb", size=None, **kwargs): + session = await self.set_session() + if size is None: + try: + size = (await self._info(path, **kwargs))["size"] + except FileNotFoundError: + pass + return AsyncStreamFile( + self, + path, + loop=self.loop, + session=session, + size=size, + **kwargs, + ) + + def ukey(self, url): + """Unique identifier; assume HTTP files are static, unchanging""" + return tokenize(url, self.kwargs, self.protocol) + + async def _info(self, url, **kwargs): + """Get info of URL + + Tries to access location via HEAD, and then GET methods, but does + not fetch the data. + + It is possible that the server does not supply any size information, in + which case size will be given as None (and certain operations on the + corresponding file will not work). + """ + info = {} + session = await self.set_session() + + for policy in ["head", "get"]: + try: + info.update( + await _file_info( + self.encode_url(url), + size_policy=policy, + session=session, + **self.kwargs, + **kwargs, + ) + ) + if info.get("size") is not None: + break + except Exception as exc: + if policy == "get": + # If get failed, then raise a FileNotFoundError + raise FileNotFoundError(url) from exc + logger.debug("", exc_info=exc) + + return {"name": url, "size": None, **info, "type": "file"} + + async def _glob(self, path, maxdepth=None, **kwargs): + """ + Find files by glob-matching. + + This implementation is idntical to the one in AbstractFileSystem, + but "?" is not considered as a character for globbing, because it is + so common in URLs, often identifying the "query" part. + """ + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + import re + + ends_with_slash = path.endswith("/") # _strip_protocol strips trailing slash + path = self._strip_protocol(path) + append_slash_to_dirname = ends_with_slash or path.endswith(("/**", "/*")) + idx_star = path.find("*") if path.find("*") >= 0 else len(path) + idx_brace = path.find("[") if path.find("[") >= 0 else len(path) + + min_idx = min(idx_star, idx_brace) + + detail = kwargs.pop("detail", False) + + if not has_magic(path): + if await self._exists(path, **kwargs): + if not detail: + return [path] + else: + return {path: await self._info(path, **kwargs)} + else: + if not detail: + return [] # glob of non-existent returns empty + else: + return {} + elif "/" in path[:min_idx]: + min_idx = path[:min_idx].rindex("/") + root = path[: min_idx + 1] + depth = path[min_idx + 1 :].count("/") + 1 + else: + root = "" + depth = path[min_idx + 1 :].count("/") + 1 + + if "**" in path: + if maxdepth is not None: + idx_double_stars = path.find("**") + depth_double_stars = path[idx_double_stars:].count("/") + 1 + depth = depth - depth_double_stars + maxdepth + else: + depth = None + + allpaths = await self._find( + root, maxdepth=depth, withdirs=True, detail=True, **kwargs + ) + + pattern = glob_translate(path + ("/" if ends_with_slash else "")) + pattern = re.compile(pattern) + + out = { + ( + p.rstrip("/") + if not append_slash_to_dirname + and info["type"] == "directory" + and p.endswith("/") + else p + ): info + for p, info in sorted(allpaths.items()) + if pattern.match(p.rstrip("/")) + } + + if detail: + return out + else: + return list(out) + + async def _isdir(self, path): + # override, since all URLs are (also) files + try: + return bool(await self._ls(path)) + except (FileNotFoundError, ValueError): + return False + + async def _pipe_file(self, path, value, mode="overwrite", **kwargs): + """ + Write bytes to a remote file over HTTP. + + Parameters + ---------- + path : str + Target URL where the data should be written + value : bytes + Data to be written + mode : str + How to write to the file - 'overwrite' or 'append' + **kwargs : dict + Additional parameters to pass to the HTTP request + """ + url = self._strip_protocol(path) + headers = kwargs.pop("headers", {}) + headers["Content-Length"] = str(len(value)) + + session = await self.set_session() + + async with session.put( + self.encode_url(url), data=value, headers=headers, **kwargs + ) as r: + r.raise_for_status() + + +class HTTPFile(AbstractBufferedFile): + """ + A file-like object pointing to a remote HTTP(S) resource + + Supports only reading, with read-ahead of a predetermined block-size. + + In the case that the server does not supply the filesize, only reading of + the complete file in one go is supported. + + Parameters + ---------- + url: str + Full URL of the remote resource, including the protocol + session: aiohttp.ClientSession or None + All calls will be made within this session, to avoid restarting + connections where the server allows this + block_size: int or None + The amount of read-ahead to do, in bytes. Default is 5MB, or the value + configured for the FileSystem creating this file + size: None or int + If given, this is the size of the file in bytes, and we don't attempt + to call the server to find the value. + kwargs: all other key-values are passed to requests calls. + """ + + def __init__( + self, + fs, + url, + session=None, + block_size=None, + mode="rb", + cache_type="bytes", + cache_options=None, + size=None, + loop=None, + asynchronous=False, + **kwargs, + ): + if mode != "rb": + raise NotImplementedError("File mode not supported") + self.asynchronous = asynchronous + self.loop = loop + self.url = url + self.session = session + self.details = {"name": url, "size": size, "type": "file"} + super().__init__( + fs=fs, + path=url, + mode=mode, + block_size=block_size, + cache_type=cache_type, + cache_options=cache_options, + **kwargs, + ) + + def read(self, length=-1): + """Read bytes from file + + Parameters + ---------- + length: int + Read up to this many bytes. If negative, read all content to end of + file. If the server has not supplied the filesize, attempting to + read only part of the data will raise a ValueError. + """ + if ( + (length < 0 and self.loc == 0) # explicit read all + # but not when the size is known and fits into a block anyways + and not (self.size is not None and self.size <= self.blocksize) + ): + self._fetch_all() + if self.size is None: + if length < 0: + self._fetch_all() + else: + length = min(self.size - self.loc, length) + return super().read(length) + + async def async_fetch_all(self): + """Read whole file in one shot, without caching + + This is only called when position is still at zero, + and read() is called without a byte-count. + """ + logger.debug(f"Fetch all for {self}") + if not isinstance(self.cache, AllBytes): + r = await self.session.get(self.fs.encode_url(self.url), **self.kwargs) + async with r: + r.raise_for_status() + out = await r.read() + self.cache = AllBytes( + size=len(out), fetcher=None, blocksize=None, data=out + ) + self.size = len(out) + + _fetch_all = sync_wrapper(async_fetch_all) + + def _parse_content_range(self, headers): + """Parse the Content-Range header""" + s = headers.get("Content-Range", "") + m = re.match(r"bytes (\d+-\d+|\*)/(\d+|\*)", s) + if not m: + return None, None, None + + if m[1] == "*": + start = end = None + else: + start, end = [int(x) for x in m[1].split("-")] + total = None if m[2] == "*" else int(m[2]) + return start, end, total + + async def async_fetch_range(self, start, end): + """Download a block of data + + The expectation is that the server returns only the requested bytes, + with HTTP code 206. If this is not the case, we first check the headers, + and then stream the output - if the data size is bigger than we + requested, an exception is raised. + """ + logger.debug(f"Fetch range for {self}: {start}-{end}") + kwargs = self.kwargs.copy() + headers = kwargs.pop("headers", {}).copy() + headers["Range"] = f"bytes={start}-{end - 1}" + logger.debug(f"{self.url} : {headers['Range']}") + r = await self.session.get( + self.fs.encode_url(self.url), headers=headers, **kwargs + ) + async with r: + if r.status == 416: + # range request outside file + return b"" + r.raise_for_status() + + # If the server has handled the range request, it should reply + # with status 206 (partial content). But we'll guess that a suitable + # Content-Range header or a Content-Length no more than the + # requested range also mean we have got the desired range. + response_is_range = ( + r.status == 206 + or self._parse_content_range(r.headers)[0] == start + or int(r.headers.get("Content-Length", end + 1)) <= end - start + ) + + if response_is_range: + # partial content, as expected + out = await r.read() + elif start > 0: + raise ValueError( + "The HTTP server doesn't appear to support range requests. " + "Only reading this file from the beginning is supported. " + "Open with block_size=0 for a streaming file interface." + ) + else: + # Response is not a range, but we want the start of the file, + # so we can read the required amount anyway. + cl = 0 + out = [] + while True: + chunk = await r.content.read(2**20) + # data size unknown, let's read until we have enough + if chunk: + out.append(chunk) + cl += len(chunk) + if cl > end - start: + break + else: + break + out = b"".join(out)[: end - start] + return out + + _fetch_range = sync_wrapper(async_fetch_range) + + +magic_check = re.compile("([*[])") + + +def has_magic(s): + match = magic_check.search(s) + return match is not None + + +class HTTPStreamFile(AbstractBufferedFile): + def __init__(self, fs, url, mode="rb", loop=None, session=None, **kwargs): + self.asynchronous = kwargs.pop("asynchronous", False) + self.url = url + self.loop = loop + self.session = session + if mode != "rb": + raise ValueError + self.details = {"name": url, "size": None} + super().__init__(fs=fs, path=url, mode=mode, cache_type="none", **kwargs) + + async def cor(): + r = await self.session.get(self.fs.encode_url(url), **kwargs).__aenter__() + self.fs._raise_not_found_for_status(r, url) + return r + + self.r = sync(self.loop, cor) + self.loop = fs.loop + + def seek(self, loc, whence=0): + if loc == 0 and whence == 1: + return + if loc == self.loc and whence == 0: + return + raise ValueError("Cannot seek streaming HTTP file") + + async def _read(self, num=-1): + out = await self.r.content.read(num) + self.loc += len(out) + return out + + read = sync_wrapper(_read) + + async def _close(self): + self.r.close() + + def close(self): + asyncio.run_coroutine_threadsafe(self._close(), self.loop) + super().close() + + +class AsyncStreamFile(AbstractAsyncStreamedFile): + def __init__( + self, fs, url, mode="rb", loop=None, session=None, size=None, **kwargs + ): + self.url = url + self.session = session + self.r = None + if mode != "rb": + raise ValueError + self.details = {"name": url, "size": None} + self.kwargs = kwargs + super().__init__(fs=fs, path=url, mode=mode, cache_type="none") + self.size = size + + async def read(self, num=-1): + if self.r is None: + r = await self.session.get( + self.fs.encode_url(self.url), **self.kwargs + ).__aenter__() + self.fs._raise_not_found_for_status(r, self.url) + self.r = r + out = await self.r.content.read(num) + self.loc += len(out) + return out + + async def close(self): + if self.r is not None: + self.r.close() + self.r = None + await super().close() + + +async def get_range(session, url, start, end, file=None, **kwargs): + # explicit get a range when we know it must be safe + kwargs = kwargs.copy() + headers = kwargs.pop("headers", {}).copy() + headers["Range"] = f"bytes={start}-{end - 1}" + r = await session.get(url, headers=headers, **kwargs) + r.raise_for_status() + async with r: + out = await r.read() + if file: + with open(file, "r+b") as f: # noqa: ASYNC230 + f.seek(start) + f.write(out) + else: + return out + + +async def _file_info(url, session, size_policy="head", **kwargs): + """Call HEAD on the server to get details about the file (size/checksum etc.) + + Default operation is to explicitly allow redirects and use encoding + 'identity' (no compression) to get the true size of the target. + """ + logger.debug("Retrieve file size for %s", url) + kwargs = kwargs.copy() + ar = kwargs.pop("allow_redirects", True) + head = kwargs.get("headers", {}).copy() + head["Accept-Encoding"] = "identity" + kwargs["headers"] = head + + info = {} + if size_policy == "head": + r = await session.head(url, allow_redirects=ar, **kwargs) + elif size_policy == "get": + r = await session.get(url, allow_redirects=ar, **kwargs) + else: + raise TypeError(f'size_policy must be "head" or "get", got {size_policy}') + async with r: + r.raise_for_status() + + if "Content-Length" in r.headers: + # Some servers may choose to ignore Accept-Encoding and return + # compressed content, in which case the returned size is unreliable. + if "Content-Encoding" not in r.headers or r.headers["Content-Encoding"] in [ + "identity", + "", + ]: + info["size"] = int(r.headers["Content-Length"]) + elif "Content-Range" in r.headers: + info["size"] = int(r.headers["Content-Range"].split("/")[1]) + + if "Content-Type" in r.headers: + info["mimetype"] = r.headers["Content-Type"].partition(";")[0] + + if r.headers.get("Accept-Ranges") == "none": + # Some servers may explicitly discourage partial content requests, but + # the lack of "Accept-Ranges" does not always indicate they would fail + info["partial"] = False + + info["url"] = str(r.url) + + for checksum_field in ["ETag", "Content-MD5", "Digest", "Last-Modified"]: + if r.headers.get(checksum_field): + info[checksum_field] = r.headers[checksum_field] + + return info + + +async def _file_size(url, session=None, *args, **kwargs): + if session is None: + session = await get_client() + info = await _file_info(url, session=session, *args, **kwargs) + return info.get("size") + + +file_size = sync_wrapper(_file_size) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/http_sync.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/http_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..a67ea3ea5fee9e6b51f7f3f66773e8cf65735e52 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/http_sync.py @@ -0,0 +1,937 @@ +"""This file is largely copied from http.py""" + +import io +import logging +import re +import urllib.error +import urllib.parse +from copy import copy +from json import dumps, loads +from urllib.parse import urlparse + +try: + import yarl +except (ImportError, ModuleNotFoundError, OSError): + yarl = False + +from fsspec.callbacks import _DEFAULT_CALLBACK +from fsspec.registry import register_implementation +from fsspec.spec import AbstractBufferedFile, AbstractFileSystem +from fsspec.utils import DEFAULT_BLOCK_SIZE, isfilelike, nullcontext, tokenize + +from ..caching import AllBytes + +# https://stackoverflow.com/a/15926317/3821154 +ex = re.compile(r"""<(a|A)\s+(?:[^>]*?\s+)?(href|HREF)=["'](?P[^"']+)""") +ex2 = re.compile(r"""(?Phttp[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""") +logger = logging.getLogger("fsspec.http") + + +class JsHttpException(urllib.error.HTTPError): ... + + +class StreamIO(io.BytesIO): + # fake class, so you can set attributes on it + # will eventually actually stream + ... + + +class ResponseProxy: + """Looks like a requests response""" + + def __init__(self, req, stream=False): + self.request = req + self.stream = stream + self._data = None + self._headers = None + + @property + def raw(self): + if self._data is None: + b = self.request.response.to_bytes() + if self.stream: + self._data = StreamIO(b) + else: + self._data = b + return self._data + + def close(self): + if hasattr(self, "_data"): + del self._data + + @property + def headers(self): + if self._headers is None: + self._headers = dict( + [ + _.split(": ") + for _ in self.request.getAllResponseHeaders().strip().split("\r\n") + ] + ) + return self._headers + + @property + def status_code(self): + return int(self.request.status) + + def raise_for_status(self): + if not self.ok: + raise JsHttpException( + self.url, self.status_code, self.reason, self.headers, None + ) + + def iter_content(self, chunksize, *_, **__): + while True: + out = self.raw.read(chunksize) + if out: + yield out + else: + break + + @property + def reason(self): + return self.request.statusText + + @property + def ok(self): + return self.status_code < 400 + + @property + def url(self): + return self.request.response.responseURL + + @property + def text(self): + # TODO: encoding from headers + return self.content.decode() + + @property + def content(self): + self.stream = False + return self.raw + + def json(self): + return loads(self.text) + + +class RequestsSessionShim: + def __init__(self): + self.headers = {} + + def request( + self, + method, + url, + params=None, + data=None, + headers=None, + cookies=None, + files=None, + auth=None, + timeout=None, + allow_redirects=None, + proxies=None, + hooks=None, + stream=None, + verify=None, + cert=None, + json=None, + ): + from js import Blob, XMLHttpRequest + + logger.debug("JS request: %s %s", method, url) + + if cert or verify or proxies or files or cookies or hooks: + raise NotImplementedError + if data and json: + raise ValueError("Use json= or data=, not both") + req = XMLHttpRequest.new() + extra = auth if auth else () + if params: + url = f"{url}?{urllib.parse.urlencode(params)}" + req.open(method, url, False, *extra) + if timeout: + req.timeout = timeout + if headers: + for k, v in headers.items(): + req.setRequestHeader(k, v) + + req.setRequestHeader("Accept", "application/octet-stream") + req.responseType = "arraybuffer" + if json: + blob = Blob.new([dumps(data)], {type: "application/json"}) + req.send(blob) + elif data: + if isinstance(data, io.IOBase): + data = data.read() + blob = Blob.new([data], {type: "application/octet-stream"}) + req.send(blob) + else: + req.send(None) + return ResponseProxy(req, stream=stream) + + def get(self, url, **kwargs): + return self.request("GET", url, **kwargs) + + def head(self, url, **kwargs): + return self.request("HEAD", url, **kwargs) + + def post(self, url, **kwargs): + return self.request("POST}", url, **kwargs) + + def put(self, url, **kwargs): + return self.request("PUT", url, **kwargs) + + def patch(self, url, **kwargs): + return self.request("PATCH", url, **kwargs) + + def delete(self, url, **kwargs): + return self.request("DELETE", url, **kwargs) + + +class HTTPFileSystem(AbstractFileSystem): + """ + Simple File-System for fetching data via HTTP(S) + + This is the BLOCKING version of the normal HTTPFileSystem. It uses + requests in normal python and the JS runtime in pyodide. + + ***This implementation is extremely experimental, do not use unless + you are testing pyodide/pyscript integration*** + """ + + protocol = ("http", "https", "sync-http", "sync-https") + sep = "/" + + def __init__( + self, + simple_links=True, + block_size=None, + same_scheme=True, + cache_type="readahead", + cache_options=None, + client_kwargs=None, + encoded=False, + **storage_options, + ): + """ + + Parameters + ---------- + block_size: int + Blocks to read bytes; if 0, will default to raw requests file-like + objects instead of HTTPFile instances + simple_links: bool + If True, will consider both HTML tags and anything that looks + like a URL; if False, will consider only the former. + same_scheme: True + When doing ls/glob, if this is True, only consider paths that have + http/https matching the input URLs. + size_policy: this argument is deprecated + client_kwargs: dict + Passed to aiohttp.ClientSession, see + https://docs.aiohttp.org/en/stable/client_reference.html + For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}`` + storage_options: key-value + Any other parameters passed on to requests + cache_type, cache_options: defaults used in open + """ + super().__init__(self, **storage_options) + self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE + self.simple_links = simple_links + self.same_schema = same_scheme + self.cache_type = cache_type + self.cache_options = cache_options + self.client_kwargs = client_kwargs or {} + self.encoded = encoded + self.kwargs = storage_options + + try: + import js # noqa: F401 + + logger.debug("Starting JS session") + self.session = RequestsSessionShim() + self.js = True + except Exception as e: + import requests + + logger.debug("Starting cpython session because of: %s", e) + self.session = requests.Session(**(client_kwargs or {})) + self.js = False + + request_options = copy(storage_options) + self.use_listings_cache = request_options.pop("use_listings_cache", False) + request_options.pop("listings_expiry_time", None) + request_options.pop("max_paths", None) + request_options.pop("skip_instance_cache", None) + self.kwargs = request_options + + @property + def fsid(self): + return "sync-http" + + def encode_url(self, url): + if yarl: + return yarl.URL(url, encoded=self.encoded) + return url + + @classmethod + def _strip_protocol(cls, path: str) -> str: + """For HTTP, we always want to keep the full URL""" + path = path.replace("sync-http://", "http://").replace( + "sync-https://", "https://" + ) + return path + + @classmethod + def _parent(cls, path): + # override, since _strip_protocol is different for URLs + par = super()._parent(path) + if len(par) > 7: # "http://..." + return par + return "" + + def _ls_real(self, url, detail=True, **kwargs): + # ignoring URL-encoded arguments + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(url) + r = self.session.get(self.encode_url(url), **self.kwargs) + self._raise_not_found_for_status(r, url) + text = r.text + if self.simple_links: + links = ex2.findall(text) + [u[2] for u in ex.findall(text)] + else: + links = [u[2] for u in ex.findall(text)] + out = set() + parts = urlparse(url) + for l in links: + if isinstance(l, tuple): + l = l[1] + if l.startswith("/") and len(l) > 1: + # absolute URL on this server + l = parts.scheme + "://" + parts.netloc + l + if l.startswith("http"): + if self.same_schema and l.startswith(url.rstrip("/") + "/"): + out.add(l) + elif l.replace("https", "http").startswith( + url.replace("https", "http").rstrip("/") + "/" + ): + # allowed to cross http <-> https + out.add(l) + else: + if l not in ["..", "../"]: + # Ignore FTP-like "parent" + out.add("/".join([url.rstrip("/"), l.lstrip("/")])) + if not out and url.endswith("/"): + out = self._ls_real(url.rstrip("/"), detail=False) + if detail: + return [ + { + "name": u, + "size": None, + "type": "directory" if u.endswith("/") else "file", + } + for u in out + ] + else: + return sorted(out) + + def ls(self, url, detail=True, **kwargs): + if self.use_listings_cache and url in self.dircache: + out = self.dircache[url] + else: + out = self._ls_real(url, detail=detail, **kwargs) + self.dircache[url] = out + return out + + def _raise_not_found_for_status(self, response, url): + """ + Raises FileNotFoundError for 404s, otherwise uses raise_for_status. + """ + if response.status_code == 404: + raise FileNotFoundError(url) + response.raise_for_status() + + def cat_file(self, url, start=None, end=None, **kwargs): + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(url) + + if start is not None or end is not None: + if start == end: + return b"" + headers = kw.pop("headers", {}).copy() + + headers["Range"] = self._process_limits(url, start, end) + kw["headers"] = headers + r = self.session.get(self.encode_url(url), **kw) + self._raise_not_found_for_status(r, url) + return r.content + + def get_file( + self, rpath, lpath, chunk_size=5 * 2**20, callback=_DEFAULT_CALLBACK, **kwargs + ): + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(rpath) + r = self.session.get(self.encode_url(rpath), **kw) + try: + size = int( + r.headers.get("content-length", None) + or r.headers.get("Content-Length", None) + ) + except (ValueError, KeyError, TypeError): + size = None + + callback.set_size(size) + self._raise_not_found_for_status(r, rpath) + if not isfilelike(lpath): + lpath = open(lpath, "wb") + for chunk in r.iter_content(chunk_size, decode_unicode=False): + lpath.write(chunk) + callback.relative_update(len(chunk)) + + def put_file( + self, + lpath, + rpath, + chunk_size=5 * 2**20, + callback=_DEFAULT_CALLBACK, + method="post", + **kwargs, + ): + def gen_chunks(): + # Support passing arbitrary file-like objects + # and use them instead of streams. + if isinstance(lpath, io.IOBase): + context = nullcontext(lpath) + use_seek = False # might not support seeking + else: + context = open(lpath, "rb") + use_seek = True + + with context as f: + if use_seek: + callback.set_size(f.seek(0, 2)) + f.seek(0) + else: + callback.set_size(getattr(f, "size", None)) + + chunk = f.read(chunk_size) + while chunk: + yield chunk + callback.relative_update(len(chunk)) + chunk = f.read(chunk_size) + + kw = self.kwargs.copy() + kw.update(kwargs) + + method = method.lower() + if method not in ("post", "put"): + raise ValueError( + f"method has to be either 'post' or 'put', not: {method!r}" + ) + + meth = getattr(self.session, method) + resp = meth(rpath, data=gen_chunks(), **kw) + self._raise_not_found_for_status(resp, rpath) + + def _process_limits(self, url, start, end): + """Helper for "Range"-based _cat_file""" + size = None + suff = False + if start is not None and start < 0: + # if start is negative and end None, end is the "suffix length" + if end is None: + end = -start + start = "" + suff = True + else: + size = size or self.info(url)["size"] + start = size + start + elif start is None: + start = 0 + if not suff: + if end is not None and end < 0: + if start is not None: + size = size or self.info(url)["size"] + end = size + end + elif end is None: + end = "" + if isinstance(end, int): + end -= 1 # bytes range is inclusive + return f"bytes={start}-{end}" + + def exists(self, path, strict=False, **kwargs): + kw = self.kwargs.copy() + kw.update(kwargs) + try: + logger.debug(path) + r = self.session.get(self.encode_url(path), **kw) + if strict: + self._raise_not_found_for_status(r, path) + return r.status_code < 400 + except FileNotFoundError: + return False + except Exception: + if strict: + raise + return False + + def isfile(self, path, **kwargs): + return self.exists(path, **kwargs) + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=None, # XXX: This differs from the base class. + cache_type=None, + cache_options=None, + size=None, + **kwargs, + ): + """Make a file-like object + + Parameters + ---------- + path: str + Full URL with protocol + mode: string + must be "rb" + block_size: int or None + Bytes to download in one request; use instance value if None. If + zero, will return a streaming Requests file-like instance. + kwargs: key-value + Any other parameters, passed to requests calls + """ + if mode != "rb": + raise NotImplementedError + block_size = block_size if block_size is not None else self.block_size + kw = self.kwargs.copy() + kw.update(kwargs) + size = size or self.info(path, **kwargs)["size"] + if block_size and size: + return HTTPFile( + self, + path, + session=self.session, + block_size=block_size, + mode=mode, + size=size, + cache_type=cache_type or self.cache_type, + cache_options=cache_options or self.cache_options, + **kw, + ) + else: + return HTTPStreamFile( + self, + path, + mode=mode, + session=self.session, + **kw, + ) + + def ukey(self, url): + """Unique identifier; assume HTTP files are static, unchanging""" + return tokenize(url, self.kwargs, self.protocol) + + def info(self, url, **kwargs): + """Get info of URL + + Tries to access location via HEAD, and then GET methods, but does + not fetch the data. + + It is possible that the server does not supply any size information, in + which case size will be given as None (and certain operations on the + corresponding file will not work). + """ + info = {} + for policy in ["head", "get"]: + try: + info.update( + _file_info( + self.encode_url(url), + size_policy=policy, + session=self.session, + **self.kwargs, + **kwargs, + ) + ) + if info.get("size") is not None: + break + except Exception as exc: + if policy == "get": + # If get failed, then raise a FileNotFoundError + raise FileNotFoundError(url) from exc + logger.debug(str(exc)) + + return {"name": url, "size": None, **info, "type": "file"} + + def glob(self, path, maxdepth=None, **kwargs): + """ + Find files by glob-matching. + + This implementation is idntical to the one in AbstractFileSystem, + but "?" is not considered as a character for globbing, because it is + so common in URLs, often identifying the "query" part. + """ + import re + + ends = path.endswith("/") + path = self._strip_protocol(path) + indstar = path.find("*") if path.find("*") >= 0 else len(path) + indbrace = path.find("[") if path.find("[") >= 0 else len(path) + + ind = min(indstar, indbrace) + + detail = kwargs.pop("detail", False) + + if not has_magic(path): + root = path + depth = 1 + if ends: + path += "/*" + elif self.exists(path): + if not detail: + return [path] + else: + return {path: self.info(path)} + else: + if not detail: + return [] # glob of non-existent returns empty + else: + return {} + elif "/" in path[:ind]: + ind2 = path[:ind].rindex("/") + root = path[: ind2 + 1] + depth = None if "**" in path else path[ind2 + 1 :].count("/") + 1 + else: + root = "" + depth = None if "**" in path else path[ind + 1 :].count("/") + 1 + + allpaths = self.find( + root, maxdepth=maxdepth or depth, withdirs=True, detail=True, **kwargs + ) + # Escape characters special to python regex, leaving our supported + # special characters in place. + # See https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html + # for shell globbing details. + pattern = ( + "^" + + ( + path.replace("\\", r"\\") + .replace(".", r"\.") + .replace("+", r"\+") + .replace("//", "/") + .replace("(", r"\(") + .replace(")", r"\)") + .replace("|", r"\|") + .replace("^", r"\^") + .replace("$", r"\$") + .replace("{", r"\{") + .replace("}", r"\}") + .rstrip("/") + ) + + "$" + ) + pattern = re.sub("[*]{2}", "=PLACEHOLDER=", pattern) + pattern = re.sub("[*]", "[^/]*", pattern) + pattern = re.compile(pattern.replace("=PLACEHOLDER=", ".*")) + out = { + p: allpaths[p] + for p in sorted(allpaths) + if pattern.match(p.replace("//", "/").rstrip("/")) + } + if detail: + return out + else: + return list(out) + + def isdir(self, path): + # override, since all URLs are (also) files + try: + return bool(self.ls(path)) + except (FileNotFoundError, ValueError): + return False + + +class HTTPFile(AbstractBufferedFile): + """ + A file-like object pointing to a remove HTTP(S) resource + + Supports only reading, with read-ahead of a predermined block-size. + + In the case that the server does not supply the filesize, only reading of + the complete file in one go is supported. + + Parameters + ---------- + url: str + Full URL of the remote resource, including the protocol + session: requests.Session or None + All calls will be made within this session, to avoid restarting + connections where the server allows this + block_size: int or None + The amount of read-ahead to do, in bytes. Default is 5MB, or the value + configured for the FileSystem creating this file + size: None or int + If given, this is the size of the file in bytes, and we don't attempt + to call the server to find the value. + kwargs: all other key-values are passed to requests calls. + """ + + def __init__( + self, + fs, + url, + session=None, + block_size=None, + mode="rb", + cache_type="bytes", + cache_options=None, + size=None, + **kwargs, + ): + if mode != "rb": + raise NotImplementedError("File mode not supported") + self.url = url + self.session = session + self.details = {"name": url, "size": size, "type": "file"} + super().__init__( + fs=fs, + path=url, + mode=mode, + block_size=block_size, + cache_type=cache_type, + cache_options=cache_options, + **kwargs, + ) + + def read(self, length=-1): + """Read bytes from file + + Parameters + ---------- + length: int + Read up to this many bytes. If negative, read all content to end of + file. If the server has not supplied the filesize, attempting to + read only part of the data will raise a ValueError. + """ + if ( + (length < 0 and self.loc == 0) # explicit read all + # but not when the size is known and fits into a block anyways + and not (self.size is not None and self.size <= self.blocksize) + ): + self._fetch_all() + if self.size is None: + if length < 0: + self._fetch_all() + else: + length = min(self.size - self.loc, length) + return super().read(length) + + def _fetch_all(self): + """Read whole file in one shot, without caching + + This is only called when position is still at zero, + and read() is called without a byte-count. + """ + logger.debug(f"Fetch all for {self}") + if not isinstance(self.cache, AllBytes): + r = self.session.get(self.fs.encode_url(self.url), **self.kwargs) + r.raise_for_status() + out = r.content + self.cache = AllBytes(size=len(out), fetcher=None, blocksize=None, data=out) + self.size = len(out) + + def _parse_content_range(self, headers): + """Parse the Content-Range header""" + s = headers.get("Content-Range", "") + m = re.match(r"bytes (\d+-\d+|\*)/(\d+|\*)", s) + if not m: + return None, None, None + + if m[1] == "*": + start = end = None + else: + start, end = [int(x) for x in m[1].split("-")] + total = None if m[2] == "*" else int(m[2]) + return start, end, total + + def _fetch_range(self, start, end): + """Download a block of data + + The expectation is that the server returns only the requested bytes, + with HTTP code 206. If this is not the case, we first check the headers, + and then stream the output - if the data size is bigger than we + requested, an exception is raised. + """ + logger.debug(f"Fetch range for {self}: {start}-{end}") + kwargs = self.kwargs.copy() + headers = kwargs.pop("headers", {}).copy() + headers["Range"] = f"bytes={start}-{end - 1}" + logger.debug("%s : %s", self.url, headers["Range"]) + r = self.session.get(self.fs.encode_url(self.url), headers=headers, **kwargs) + if r.status_code == 416: + # range request outside file + return b"" + r.raise_for_status() + + # If the server has handled the range request, it should reply + # with status 206 (partial content). But we'll guess that a suitable + # Content-Range header or a Content-Length no more than the + # requested range also mean we have got the desired range. + cl = r.headers.get("Content-Length", r.headers.get("content-length", end + 1)) + response_is_range = ( + r.status_code == 206 + or self._parse_content_range(r.headers)[0] == start + or int(cl) <= end - start + ) + + if response_is_range: + # partial content, as expected + out = r.content + elif start > 0: + raise ValueError( + "The HTTP server doesn't appear to support range requests. " + "Only reading this file from the beginning is supported. " + "Open with block_size=0 for a streaming file interface." + ) + else: + # Response is not a range, but we want the start of the file, + # so we can read the required amount anyway. + cl = 0 + out = [] + for chunk in r.iter_content(2**20, False): + out.append(chunk) + cl += len(chunk) + out = b"".join(out)[: end - start] + return out + + +magic_check = re.compile("([*[])") + + +def has_magic(s): + match = magic_check.search(s) + return match is not None + + +class HTTPStreamFile(AbstractBufferedFile): + def __init__(self, fs, url, mode="rb", session=None, **kwargs): + self.url = url + self.session = session + if mode != "rb": + raise ValueError + self.details = {"name": url, "size": None} + super().__init__(fs=fs, path=url, mode=mode, cache_type="readahead", **kwargs) + + r = self.session.get(self.fs.encode_url(url), stream=True, **kwargs) + self.fs._raise_not_found_for_status(r, url) + self.it = r.iter_content(1024, False) + self.leftover = b"" + + self.r = r + + def seek(self, *args, **kwargs): + raise ValueError("Cannot seek streaming HTTP file") + + def read(self, num=-1): + bufs = [self.leftover] + leng = len(self.leftover) + while leng < num or num < 0: + try: + out = self.it.__next__() + except StopIteration: + break + if out: + bufs.append(out) + else: + break + leng += len(out) + out = b"".join(bufs) + if num >= 0: + self.leftover = out[num:] + out = out[:num] + else: + self.leftover = b"" + self.loc += len(out) + return out + + def close(self): + self.r.close() + self.closed = True + + +def get_range(session, url, start, end, **kwargs): + # explicit get a range when we know it must be safe + kwargs = kwargs.copy() + headers = kwargs.pop("headers", {}).copy() + headers["Range"] = f"bytes={start}-{end - 1}" + r = session.get(url, headers=headers, **kwargs) + r.raise_for_status() + return r.content + + +def _file_info(url, session, size_policy="head", **kwargs): + """Call HEAD on the server to get details about the file (size/checksum etc.) + + Default operation is to explicitly allow redirects and use encoding + 'identity' (no compression) to get the true size of the target. + """ + logger.debug("Retrieve file size for %s", url) + kwargs = kwargs.copy() + ar = kwargs.pop("allow_redirects", True) + head = kwargs.get("headers", {}).copy() + # TODO: not allowed in JS + # head["Accept-Encoding"] = "identity" + kwargs["headers"] = head + + info = {} + if size_policy == "head": + r = session.head(url, allow_redirects=ar, **kwargs) + elif size_policy == "get": + r = session.get(url, allow_redirects=ar, **kwargs) + else: + raise TypeError(f'size_policy must be "head" or "get", got {size_policy}') + r.raise_for_status() + + # TODO: + # recognise lack of 'Accept-Ranges', + # or 'Accept-Ranges': 'none' (not 'bytes') + # to mean streaming only, no random access => return None + if "Content-Length" in r.headers: + info["size"] = int(r.headers["Content-Length"]) + elif "Content-Range" in r.headers: + info["size"] = int(r.headers["Content-Range"].split("/")[1]) + elif "content-length" in r.headers: + info["size"] = int(r.headers["content-length"]) + elif "content-range" in r.headers: + info["size"] = int(r.headers["content-range"].split("/")[1]) + + for checksum_field in ["ETag", "Content-MD5", "Digest"]: + if r.headers.get(checksum_field): + info[checksum_field] = r.headers[checksum_field] + + return info + + +# importing this is enough to register it +def register(): + register_implementation("http", HTTPFileSystem, clobber=True) + register_implementation("https", HTTPFileSystem, clobber=True) + register_implementation("sync-http", HTTPFileSystem, clobber=True) + register_implementation("sync-https", HTTPFileSystem, clobber=True) + + +register() + + +def unregister(): + from fsspec.implementations.http import HTTPFileSystem + + register_implementation("http", HTTPFileSystem, clobber=True) + register_implementation("https", HTTPFileSystem, clobber=True) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/jupyter.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/jupyter.py new file mode 100644 index 0000000000000000000000000000000000000000..e5571ed56582170051f3b7cd903093eed4c65244 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/jupyter.py @@ -0,0 +1,129 @@ +import base64 +import io +import re + +import requests + +import fsspec + + +class JupyterFileSystem(fsspec.AbstractFileSystem): + """View of the files as seen by a Jupyter server (notebook or lab)""" + + protocol = ("jupyter", "jlab") + + def __init__(self, url, tok=None, **kwargs): + """ + + Parameters + ---------- + url : str + Base URL of the server, like "http://127.0.0.1:8888". May include + token in the string, which is given by the process when starting up + tok : str + If the token is obtained separately, can be given here + kwargs + """ + if "?" in url: + if tok is None: + try: + tok = re.findall("token=([a-z0-9]+)", url)[0] + except IndexError as e: + raise ValueError("Could not determine token") from e + url = url.split("?", 1)[0] + self.url = url.rstrip("/") + "/api/contents" + self.session = requests.Session() + if tok: + self.session.headers["Authorization"] = f"token {tok}" + + super().__init__(**kwargs) + + def ls(self, path, detail=True, **kwargs): + path = self._strip_protocol(path) + r = self.session.get(f"{self.url}/{path}") + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + out = r.json() + + if out["type"] == "directory": + out = out["content"] + else: + out = [out] + for o in out: + o["name"] = o.pop("path") + o.pop("content") + if o["type"] == "notebook": + o["type"] = "file" + if detail: + return out + return [o["name"] for o in out] + + def cat_file(self, path, start=None, end=None, **kwargs): + path = self._strip_protocol(path) + r = self.session.get(f"{self.url}/{path}") + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + out = r.json() + if out["format"] == "text": + # data should be binary + b = out["content"].encode() + else: + b = base64.b64decode(out["content"]) + return b[start:end] + + def pipe_file(self, path, value, **_): + path = self._strip_protocol(path) + json = { + "name": path.rsplit("/", 1)[-1], + "path": path, + "size": len(value), + "content": base64.b64encode(value).decode(), + "format": "base64", + "type": "file", + } + self.session.put(f"{self.url}/{path}", json=json) + + def mkdir(self, path, create_parents=True, **kwargs): + path = self._strip_protocol(path) + if create_parents and "/" in path: + self.mkdir(path.rsplit("/", 1)[0], True) + json = { + "name": path.rsplit("/", 1)[-1], + "path": path, + "size": None, + "content": None, + "type": "directory", + } + self.session.put(f"{self.url}/{path}", json=json) + + def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs): + if path1 == path2: + return + self.session.patch(f"{self.url}/{path1}", json={"path": path2}) + + def _rm(self, path): + path = self._strip_protocol(path) + self.session.delete(f"{self.url}/{path}") + + def _open(self, path, mode="rb", **kwargs): + path = self._strip_protocol(path) + if mode == "rb": + data = self.cat_file(path) + return io.BytesIO(data) + else: + return SimpleFileWriter(self, path, mode="wb") + + +class SimpleFileWriter(fsspec.spec.AbstractBufferedFile): + def _upload_chunk(self, final=False): + """Never uploads a chunk until file is done + + Not suitable for large files + """ + if final is False: + return False + self.buffer.seek(0) + data = self.buffer.read() + self.fs.pipe_file(self.path, data) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/libarchive.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/libarchive.py new file mode 100644 index 0000000000000000000000000000000000000000..6f8e750002df72865d611b48022e6634f9572614 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/libarchive.py @@ -0,0 +1,213 @@ +from contextlib import contextmanager +from ctypes import ( + CFUNCTYPE, + POINTER, + c_int, + c_longlong, + c_void_p, + cast, + create_string_buffer, +) + +import libarchive +import libarchive.ffi as ffi + +from fsspec import open_files +from fsspec.archive import AbstractArchiveFileSystem +from fsspec.implementations.memory import MemoryFile +from fsspec.utils import DEFAULT_BLOCK_SIZE + +# Libarchive requires seekable files or memory only for certain archive +# types. However, since we read the directory first to cache the contents +# and also allow random access to any file, the file-like object needs +# to be seekable no matter what. + +# Seek call-backs (not provided in the libarchive python wrapper) +SEEK_CALLBACK = CFUNCTYPE(c_longlong, c_int, c_void_p, c_longlong, c_int) +read_set_seek_callback = ffi.ffi( + "read_set_seek_callback", [ffi.c_archive_p, SEEK_CALLBACK], c_int, ffi.check_int +) +new_api = hasattr(ffi, "NO_OPEN_CB") + + +@contextmanager +def custom_reader(file, format_name="all", filter_name="all", block_size=ffi.page_size): + """Read an archive from a seekable file-like object. + + The `file` object must support the standard `readinto` and 'seek' methods. + """ + buf = create_string_buffer(block_size) + buf_p = cast(buf, c_void_p) + + def read_func(archive_p, context, ptrptr): + # readinto the buffer, returns number of bytes read + length = file.readinto(buf) + # write the address of the buffer into the pointer + ptrptr = cast(ptrptr, POINTER(c_void_p)) + ptrptr[0] = buf_p + # tell libarchive how much data was written into the buffer + return length + + def seek_func(archive_p, context, offset, whence): + file.seek(offset, whence) + # tell libarchvie the current position + return file.tell() + + read_cb = ffi.READ_CALLBACK(read_func) + seek_cb = SEEK_CALLBACK(seek_func) + + if new_api: + open_cb = ffi.NO_OPEN_CB + close_cb = ffi.NO_CLOSE_CB + else: + open_cb = libarchive.read.OPEN_CALLBACK(ffi.VOID_CB) + close_cb = libarchive.read.CLOSE_CALLBACK(ffi.VOID_CB) + + with libarchive.read.new_archive_read(format_name, filter_name) as archive_p: + read_set_seek_callback(archive_p, seek_cb) + ffi.read_open(archive_p, None, open_cb, read_cb, close_cb) + yield libarchive.read.ArchiveRead(archive_p) + + +class LibArchiveFileSystem(AbstractArchiveFileSystem): + """Compressed archives as a file-system (read-only) + + Supports the following formats: + tar, pax , cpio, ISO9660, zip, mtree, shar, ar, raw, xar, lha/lzh, rar + Microsoft CAB, 7-Zip, WARC + + See the libarchive documentation for further restrictions. + https://www.libarchive.org/ + + Keeps file object open while instance lives. It only works in seekable + file-like objects. In case the filesystem does not support this kind of + file object, it is recommended to cache locally. + + This class is pickleable, but not necessarily thread-safe (depends on the + platform). See libarchive documentation for details. + """ + + root_marker = "" + protocol = "libarchive" + cachable = False + + def __init__( + self, + fo="", + mode="r", + target_protocol=None, + target_options=None, + block_size=DEFAULT_BLOCK_SIZE, + **kwargs, + ): + """ + Parameters + ---------- + fo: str or file-like + Contains ZIP, and must exist. If a str, will fetch file using + :meth:`~fsspec.open_files`, which must return one file exactly. + mode: str + Currently, only 'r' accepted + target_protocol: str (optional) + If ``fo`` is a string, this value can be used to override the + FS protocol inferred from a URL + target_options: dict (optional) + Kwargs passed when instantiating the target FS, if ``fo`` is + a string. + """ + super().__init__(self, **kwargs) + if mode != "r": + raise ValueError("Only read from archive files accepted") + if isinstance(fo, str): + files = open_files(fo, protocol=target_protocol, **(target_options or {})) + if len(files) != 1: + raise ValueError( + f'Path "{fo}" did not resolve to exactly one file: "{files}"' + ) + fo = files[0] + self.of = fo + self.fo = fo.__enter__() # the whole instance is a context + self.block_size = block_size + self.dir_cache = None + + @contextmanager + def _open_archive(self): + self.fo.seek(0) + with custom_reader(self.fo, block_size=self.block_size) as arc: + yield arc + + @classmethod + def _strip_protocol(cls, path): + # file paths are always relative to the archive root + return super()._strip_protocol(path).lstrip("/") + + def _get_dirs(self): + fields = { + "name": "pathname", + "size": "size", + "created": "ctime", + "mode": "mode", + "uid": "uid", + "gid": "gid", + "mtime": "mtime", + } + + if self.dir_cache is not None: + return + + self.dir_cache = {} + list_names = [] + with self._open_archive() as arc: + for entry in arc: + if not entry.isdir and not entry.isfile: + # Skip symbolic links, fifo entries, etc. + continue + self.dir_cache.update( + { + dirname: {"name": dirname, "size": 0, "type": "directory"} + for dirname in self._all_dirnames(set(entry.name)) + } + ) + f = {key: getattr(entry, fields[key]) for key in fields} + f["type"] = "directory" if entry.isdir else "file" + list_names.append(entry.name) + + self.dir_cache[f["name"]] = f + # libarchive does not seem to return an entry for the directories (at least + # not in all formats), so get the directories names from the files names + self.dir_cache.update( + { + dirname: {"name": dirname, "size": 0, "type": "directory"} + for dirname in self._all_dirnames(list_names) + } + ) + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + path = self._strip_protocol(path) + if mode != "rb": + raise NotImplementedError + + data = b"" + with self._open_archive() as arc: + for entry in arc: + if entry.pathname != path: + continue + + if entry.size == 0: + # empty file, so there are no blocks + break + + for block in entry.get_blocks(entry.size): + data = block + break + else: + raise ValueError + return MemoryFile(fs=self, path=path, data=data) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/local.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/local.py new file mode 100644 index 0000000000000000000000000000000000000000..fd7531e7e9744a66a978d71b91ff93a2444d7510 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/local.py @@ -0,0 +1,517 @@ +import datetime +import io +import logging +import os +import os.path as osp +import shutil +import stat +import tempfile +from functools import lru_cache + +from fsspec import AbstractFileSystem +from fsspec.compression import compr +from fsspec.core import get_compression +from fsspec.utils import isfilelike, stringify_path + +logger = logging.getLogger("fsspec.local") + + +class LocalFileSystem(AbstractFileSystem): + """Interface to files on local storage + + Parameters + ---------- + auto_mkdir: bool + Whether, when opening a file, the directory containing it should + be created (if it doesn't already exist). This is assumed by pyarrow + code. + """ + + root_marker = "/" + protocol = "file", "local" + local_file = True + + def __init__(self, auto_mkdir=False, **kwargs): + super().__init__(**kwargs) + self.auto_mkdir = auto_mkdir + + @property + def fsid(self): + return "local" + + def mkdir(self, path, create_parents=True, **kwargs): + path = self._strip_protocol(path) + if self.exists(path): + raise FileExistsError(path) + if create_parents: + self.makedirs(path, exist_ok=True) + else: + os.mkdir(path, **kwargs) + + def makedirs(self, path, exist_ok=False): + path = self._strip_protocol(path) + os.makedirs(path, exist_ok=exist_ok) + + def rmdir(self, path): + path = self._strip_protocol(path) + os.rmdir(path) + + def ls(self, path, detail=False, **kwargs): + path = self._strip_protocol(path) + path_info = self.info(path) + infos = [] + if path_info["type"] == "directory": + with os.scandir(path) as it: + for f in it: + try: + # Only get the info if requested since it is a bit expensive (the stat call inside) + # The strip_protocol is also used in info() and calls make_path_posix to always return posix paths + info = self.info(f) if detail else self._strip_protocol(f.path) + infos.append(info) + except FileNotFoundError: + pass + else: + infos = [path_info] if detail else [path_info["name"]] + + return infos + + def info(self, path, **kwargs): + if isinstance(path, os.DirEntry): + # scandir DirEntry + out = path.stat(follow_symlinks=False) + link = path.is_symlink() + if path.is_dir(follow_symlinks=False): + t = "directory" + elif path.is_file(follow_symlinks=False): + t = "file" + else: + t = "other" + + size = out.st_size + if link: + try: + out2 = path.stat(follow_symlinks=True) + size = out2.st_size + except OSError: + size = 0 + path = self._strip_protocol(path.path) + else: + # str or path-like + path = self._strip_protocol(path) + out = os.stat(path, follow_symlinks=False) + link = stat.S_ISLNK(out.st_mode) + if link: + out = os.stat(path, follow_symlinks=True) + size = out.st_size + if stat.S_ISDIR(out.st_mode): + t = "directory" + elif stat.S_ISREG(out.st_mode): + t = "file" + else: + t = "other" + + # Check for the 'st_birthtime' attribute, which is not always present; fallback to st_ctime + created_time = getattr(out, "st_birthtime", out.st_ctime) + + result = { + "name": path, + "size": size, + "type": t, + "created": created_time, + "islink": link, + } + for field in ["mode", "uid", "gid", "mtime", "ino", "nlink"]: + result[field] = getattr(out, f"st_{field}") + if link: + result["destination"] = os.readlink(path) + return result + + def lexists(self, path, **kwargs): + return osp.lexists(path) + + def cp_file(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1) + path2 = self._strip_protocol(path2) + if self.auto_mkdir: + self.makedirs(self._parent(path2), exist_ok=True) + if self.isfile(path1): + shutil.copyfile(path1, path2) + elif self.isdir(path1): + self.mkdirs(path2, exist_ok=True) + else: + raise FileNotFoundError(path1) + + def isfile(self, path): + path = self._strip_protocol(path) + return os.path.isfile(path) + + def isdir(self, path): + path = self._strip_protocol(path) + return os.path.isdir(path) + + def get_file(self, path1, path2, callback=None, **kwargs): + if isfilelike(path2): + with open(path1, "rb") as f: + shutil.copyfileobj(f, path2) + else: + return self.cp_file(path1, path2, **kwargs) + + def put_file(self, path1, path2, callback=None, **kwargs): + return self.cp_file(path1, path2, **kwargs) + + def mv(self, path1, path2, recursive: bool = True, **kwargs): + """Move files/directories + For the specific case of local, all ops on directories are recursive and + the recursive= kwarg is ignored. + """ + path1 = self._strip_protocol(path1) + path2 = self._strip_protocol(path2) + + if self.auto_mkdir: + self.makedirs(self._parent(path2), exist_ok=True) + + shutil.move(path1, path2) + + def link(self, src, dst, **kwargs): + src = self._strip_protocol(src) + dst = self._strip_protocol(dst) + os.link(src, dst, **kwargs) + + def symlink(self, src, dst, **kwargs): + src = self._strip_protocol(src) + dst = self._strip_protocol(dst) + os.symlink(src, dst, **kwargs) + + def islink(self, path) -> bool: + return os.path.islink(self._strip_protocol(path)) + + def rm_file(self, path): + os.remove(self._strip_protocol(path)) + + def rm(self, path, recursive=False, maxdepth=None): + if not isinstance(path, list): + path = [path] + + for p in path: + p = self._strip_protocol(p) + if self.isdir(p) and not self.islink(p): + if not recursive: + raise ValueError("Cannot delete directory, set recursive=True") + if osp.abspath(p) == os.getcwd(): + raise ValueError("Cannot delete current working directory") + shutil.rmtree(p) + else: + os.remove(p) + + def unstrip_protocol(self, name): + protocol = self.protocol if isinstance(self.protocol, str) else self.protocol[0] + name = self._strip_protocol(name) # normalise for local/win/... + return f"{protocol}://{name}" + + def _open(self, path, mode="rb", block_size=None, **kwargs): + path = self._strip_protocol(path) + if self.auto_mkdir and ("w" in mode or "x" in mode or "a" in mode): + self.makedirs(self._parent(path), exist_ok=True) + return LocalFileOpener(path, mode, fs=self, **kwargs) + + def touch(self, path, truncate=True, **kwargs): + path = self._strip_protocol(path) + if self.auto_mkdir: + self.makedirs(self._parent(path), exist_ok=True) + if self.exists(path): + os.utime(path, None) + else: + open(path, "a").close() + if truncate: + os.truncate(path, 0) + + def created(self, path): + info = self.info(path=path) + return datetime.datetime.fromtimestamp( + info["created"], tz=datetime.timezone.utc + ) + + def modified(self, path): + info = self.info(path=path) + return datetime.datetime.fromtimestamp(info["mtime"], tz=datetime.timezone.utc) + + @classmethod + def _parent(cls, path): + path = cls._strip_protocol(path) + if os.sep == "/": + # posix native + return path.rsplit("/", 1)[0] or "/" + else: + # NT + path_ = path.rsplit("/", 1)[0] + if len(path_) <= 3: + if path_[1:2] == ":": + # nt root (something like c:/) + return path_[0] + ":/" + # More cases may be required here + return path_ + + @classmethod + def _strip_protocol(cls, path): + path = stringify_path(path) + protos = (cls.protocol,) if isinstance(cls.protocol, str) else cls.protocol + prefixes = (protocol + sep for protocol in protos for sep in ("://", ":")) + for prefix in prefixes: + if path.startswith(prefix): + path = path.removeprefix(prefix) + break + + path = make_path_posix(path) + if os.sep != "/": + # This code-path is a stripped down version of + # > drive, path = ntpath.splitdrive(path) + if path[1:2] == ":": + # Absolute drive-letter path, e.g. X:\Windows + # Relative path with drive, e.g. X:Windows + drive, path = path[:2], path[2:] + elif path[:2] == "//": + # UNC drives, e.g. \\server\share or \\?\UNC\server\share + # Device drives, e.g. \\.\device or \\?\device + if (index1 := path.find("/", 2)) == -1 or ( + index2 := path.find("/", index1 + 1) + ) == -1: + drive, path = path, "" + else: + drive, path = path[:index2], path[index2:] + else: + # Relative path, e.g. Windows + drive = "" + + path = path.rstrip("/") or cls.root_marker + return drive + path + + else: + return path.rstrip("/") or cls.root_marker + + def _isfilestore(self): + # Inheriting from DaskFileSystem makes this False (S3, etc. were) + # the original motivation. But we are a posix-like file system. + # See https://github.com/dask/dask/issues/5526 + return True + + def chmod(self, path, mode): + path = stringify_path(path) + return os.chmod(path, mode) + + +def make_path_posix(path): + """Make path generic and absolute for current OS""" + if not isinstance(path, str): + if isinstance(path, (list, set, tuple)): + return type(path)(make_path_posix(p) for p in path) + else: + path = stringify_path(path) + if not isinstance(path, str): + raise TypeError(f"could not convert {path!r} to string") + if os.sep == "/": + # Native posix + if path.startswith("/"): + # most common fast case for posix + return path + elif path.startswith("~"): + return osp.expanduser(path) + elif path.startswith("./"): + path = path[2:] + elif path == ".": + path = "" + return f"{os.getcwd()}/{path}" + else: + # NT handling + if path[0:1] == "/" and path[2:3] == ":": + # path is like "/c:/local/path" + path = path[1:] + if path[1:2] == ":": + # windows full path like "C:\\local\\path" + if len(path) <= 3: + # nt root (something like c:/) + return path[0] + ":/" + path = path.replace("\\", "/") + return path + elif path[0:1] == "~": + return make_path_posix(osp.expanduser(path)) + elif path.startswith(("\\\\", "//")): + # windows UNC/DFS-style paths + return "//" + path[2:].replace("\\", "/") + elif path.startswith(("\\", "/")): + # windows relative path with root + path = path.replace("\\", "/") + return f"{osp.splitdrive(os.getcwd())[0]}{path}" + else: + path = path.replace("\\", "/") + if path.startswith("./"): + path = path[2:] + elif path == ".": + path = "" + return f"{make_path_posix(os.getcwd())}/{path}" + + +def trailing_sep(path): + """Return True if the path ends with a path separator. + + A forward slash is always considered a path separator, even on Operating + Systems that normally use a backslash. + """ + # TODO: if all incoming paths were posix-compliant then separator would + # always be a forward slash, simplifying this function. + # See https://github.com/fsspec/filesystem_spec/pull/1250 + return path.endswith(os.sep) or (os.altsep is not None and path.endswith(os.altsep)) + + +@lru_cache(maxsize=1) +def get_umask(mask: int = 0o666) -> int: + """Get the current umask. + + Follows https://stackoverflow.com/a/44130549 to get the umask. + Temporarily sets the umask to the given value, and then resets it to the + original value. + """ + value = os.umask(mask) + os.umask(value) + return value + + +class LocalFileOpener(io.IOBase): + def __init__( + self, path, mode, autocommit=True, fs=None, compression=None, **kwargs + ): + logger.debug("open file: %s", path) + self.path = path + self.mode = mode + self.fs = fs + self.f = None + self.autocommit = autocommit + self.compression = get_compression(path, compression) + self.blocksize = io.DEFAULT_BUFFER_SIZE + self._open() + + def _open(self): + if self.f is None or self.f.closed: + if self.autocommit or "w" not in self.mode: + self.f = open(self.path, mode=self.mode) + if self.compression: + compress = compr[self.compression] + self.f = compress(self.f, mode=self.mode) + else: + # TODO: check if path is writable? + i, name = tempfile.mkstemp() + os.close(i) # we want normal open and normal buffered file + self.temp = name + self.f = open(name, mode=self.mode) + if "w" not in self.mode: + self.size = self.f.seek(0, 2) + self.f.seek(0) + self.f.size = self.size + + def _fetch_range(self, start, end): + # probably only used by cached FS + if "r" not in self.mode: + raise ValueError + self._open() + self.f.seek(start) + return self.f.read(end - start) + + def __setstate__(self, state): + self.f = None + loc = state.pop("loc", None) + self.__dict__.update(state) + if "r" in state["mode"]: + self.f = None + self._open() + self.f.seek(loc) + + def __getstate__(self): + d = self.__dict__.copy() + d.pop("f") + if "r" in self.mode: + d["loc"] = self.f.tell() + else: + if not self.f.closed: + raise ValueError("Cannot serialise open write-mode local file") + return d + + def commit(self): + if self.autocommit: + raise RuntimeError("Can only commit if not already set to autocommit") + try: + shutil.move(self.temp, self.path) + except PermissionError as e: + # shutil.move raises PermissionError if os.rename + # and the default copy2 fallback with shutil.copystats fail. + # The file should be there nonetheless, but without copied permissions. + # If it doesn't exist, there was no permission to create the file. + if not os.path.exists(self.path): + raise e + else: + # If PermissionError is not raised, permissions can be set. + try: + mask = 0o666 + os.chmod(self.path, mask & ~get_umask(mask)) + except RuntimeError: + pass + + def discard(self): + if self.autocommit: + raise RuntimeError("Cannot discard if set to autocommit") + os.remove(self.temp) + + def readable(self) -> bool: + return True + + def writable(self) -> bool: + return "r" not in self.mode + + def read(self, *args, **kwargs): + return self.f.read(*args, **kwargs) + + def write(self, *args, **kwargs): + return self.f.write(*args, **kwargs) + + def tell(self, *args, **kwargs): + return self.f.tell(*args, **kwargs) + + def seek(self, *args, **kwargs): + return self.f.seek(*args, **kwargs) + + def seekable(self, *args, **kwargs): + return self.f.seekable(*args, **kwargs) + + def readline(self, *args, **kwargs): + return self.f.readline(*args, **kwargs) + + def readlines(self, *args, **kwargs): + return self.f.readlines(*args, **kwargs) + + def close(self): + return self.f.close() + + def truncate(self, size=None) -> int: + return self.f.truncate(size) + + @property + def closed(self): + return self.f.closed + + def fileno(self): + return self.raw.fileno() + + def flush(self) -> None: + self.f.flush() + + def __iter__(self): + return self.f.__iter__() + + def __getattr__(self, item): + return getattr(self.f, item) + + def __enter__(self): + self._incontext = True + return self + + def __exit__(self, exc_type, exc_value, traceback): + self._incontext = False + self.f.__exit__(exc_type, exc_value, traceback) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/memory.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..378eb1e15a21d3ff8b7820f562c805ee37289492 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/memory.py @@ -0,0 +1,393 @@ +from __future__ import annotations + +import logging +from datetime import datetime, timezone +from errno import ENOTEMPTY +from io import BytesIO +from pathlib import PurePath, PureWindowsPath +from typing import Any, ClassVar + +from fsspec import AbstractFileSystem +from fsspec.implementations.local import LocalFileSystem +from fsspec.utils import stringify_path + +logger = logging.getLogger("fsspec.memoryfs") + + +class MemoryFileSystem(AbstractFileSystem): + """A filesystem based on a dict of BytesIO objects + + This is a global filesystem so instances of this class all point to the same + in memory filesystem. + """ + + store: ClassVar[dict[str, Any]] = {} # global, do not overwrite! + pseudo_dirs = [""] # global, do not overwrite! + protocol = "memory" + root_marker = "/" + + @classmethod + def _strip_protocol(cls, path): + if isinstance(path, PurePath): + if isinstance(path, PureWindowsPath): + return LocalFileSystem._strip_protocol(path) + else: + path = stringify_path(path) + + path = path.removeprefix("memory://") + if "::" in path or "://" in path: + return path.rstrip("/") + path = path.lstrip("/").rstrip("/") + return "/" + path if path else "" + + def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs): + # The base implementation calls ls() once per directory, and each ls() + # scans the whole (global) store, giving O(n_dirs * n_entries) behaviour + # for a tree. Since the store is a flat mapping of every path, the same + # result can be produced with a single pass over it. + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + path = self._strip_protocol(path) + if path in self.store: + # path is itself a file + if not detail: + return [path] + filelike = self.store[path] + return { + path: { + "name": path, + "size": filelike.size, + "type": "file", + "created": filelike.created.timestamp(), + } + } + + # Uniform prefix so that the search root "" (the filesystem root) and a + # nested path are handled the same way; rel depth is rel.count("/") + 1. + prefix = path + "/" if path else "/" + out = {} + dirs = {} + + def add_ancestor_dirs(name): + # Register every directory implied between ``path`` and ``name`` that + # is within maxdepth, mirroring how walk() surfaces implied dirs. + idx = name.rfind("/") + while idx > len(path): + parent = name[:idx] + if parent in dirs: + break + rel = parent[len(prefix) :] + if maxdepth is None or rel.count("/") + 1 <= maxdepth: + dirs[parent] = {"name": parent, "size": 0, "type": "directory"} + idx = parent.rfind("/") + + # `store` is shared by every MemoryFileSystem instance, so iterate a + # snapshot: a concurrent create/delete would otherwise raise + # "dictionary changed size during iteration". ls() does the same. + for name, filelike in tuple(self.store.items()): + if not name.startswith(prefix): + continue + rel = name[len(prefix) :] + if withdirs: + add_ancestor_dirs(name) + if maxdepth is not None and rel.count("/") + 1 > maxdepth: + continue + out[name] = { + "name": name, + "size": filelike.size, + "type": "file", + "created": filelike.created.timestamp(), + } + + if withdirs: + # Explicitly-created (possibly empty) directories live in pseudo_dirs. + for pdir in self.pseudo_dirs: + if pdir and pdir.startswith(prefix): + add_ancestor_dirs(pdir + "/") + out.update(dirs) + # Mirror the base find(): include the search root itself when it is + # a directory (needed for posix glob compliance). + if path != "" and self.isdir(path): + out[path] = self.info(path) + + names = sorted(out) + return {name: out[name] for name in names} if detail else names + + def ls(self, path, detail=True, **kwargs): + path = self._strip_protocol(path) + if path in self.store: + # there is a key with this exact name + if not detail: + return [path] + return [ + { + "name": path, + "size": self.store[path].size, + "type": "file", + "created": self.store[path].created.timestamp(), + } + ] + paths = set() + starter = path + "/" + out = [] + for p2 in tuple(self.store): + if p2.startswith(starter): + if "/" not in p2[len(starter) :]: + # exact child + out.append( + { + "name": p2, + "size": self.store[p2].size, + "type": "file", + "created": self.store[p2].created.timestamp(), + } + ) + elif len(p2) > len(starter): + # implied child directory + ppath = starter + p2[len(starter) :].split("/", 1)[0] + if ppath not in paths: + out = out or [] + out.append( + { + "name": ppath, + "size": 0, + "type": "directory", + } + ) + paths.add(ppath) + for p2 in self.pseudo_dirs: + if p2.startswith(starter): + if "/" not in p2[len(starter) :]: + # exact child pdir + if p2 not in paths: + out.append({"name": p2, "size": 0, "type": "directory"}) + paths.add(p2) + else: + # directory implied by deeper pdir + ppath = starter + p2[len(starter) :].split("/", 1)[0] + if ppath not in paths: + out.append({"name": ppath, "size": 0, "type": "directory"}) + paths.add(ppath) + if not out: + if path in self.pseudo_dirs: + # empty dir + return [] + raise FileNotFoundError(path) + if detail: + return out + return sorted([f["name"] for f in out]) + + def mkdir(self, path, create_parents=True, **kwargs): + path = self._strip_protocol(path) + if path in self.store or path in self.pseudo_dirs: + raise FileExistsError(path) + if self._parent(path).strip("/") and self.isfile(self._parent(path)): + raise NotADirectoryError(self._parent(path)) + if create_parents and self._parent(path).strip("/"): + try: + self.mkdir(self._parent(path), create_parents, **kwargs) + except FileExistsError: + pass + if path and path not in self.pseudo_dirs: + self.pseudo_dirs.append(path) + + def makedirs(self, path, exist_ok=False): + try: + self.mkdir(path, create_parents=True) + except FileExistsError: + if not exist_ok: + raise + + def pipe_file(self, path, value, mode="overwrite", **kwargs): + """Set the bytes of given file + + Avoids copies of the data if possible + """ + mode = "xb" if mode == "create" else "wb" + self.open(path, mode=mode, data=value) + + def rmdir(self, path): + path = self._strip_protocol(path) + if path == "": + # silently avoid deleting FS root + return + if path in self.pseudo_dirs: + if not self.ls(path): + self.pseudo_dirs.remove(path) + else: + raise OSError(ENOTEMPTY, "Directory not empty", path) + else: + raise FileNotFoundError(path) + + def info(self, path, **kwargs): + logger.debug("info: %s", path) + path = self._strip_protocol(path) + if path in self.pseudo_dirs or any( + p.startswith(path + "/") for p in list(self.store) + self.pseudo_dirs + ): + return { + "name": path, + "size": 0, + "type": "directory", + } + elif path in self.store: + filelike = self.store[path] + return { + "name": path, + "size": filelike.size, + "type": "file", + "created": getattr(filelike, "created", None), + } + else: + raise FileNotFoundError(path) + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + path = self._strip_protocol(path) + if "x" in mode and self.exists(path): + raise FileExistsError + if path in self.pseudo_dirs: + raise IsADirectoryError(path) + parent = path + while len(parent) > 1: + parent = self._parent(parent) + if self.isfile(parent): + raise FileExistsError(parent) + if mode in ["rb", "ab", "r+b", "a+b"]: + if path in self.store: + f = self.store[path] + if "a" in mode: + # position at the end of file + f.seek(0, 2) + else: + # position at the beginning of file + f.seek(0) + return f + elif "a" in mode: + # append modes create the file if it does not exist, matching + # builtin open() and LocalFileSystem + m = MemoryFile(self, path, kwargs.get("data")) + if not self._intrans: + m.commit() + # position at the end of file, like the existing-file path above + m.seek(0, 2) + return m + else: + raise FileNotFoundError(path) + elif mode in {"wb", "w+b", "xb", "x+b"}: + if "x" in mode and self.exists(path): + raise FileExistsError + m = MemoryFile(self, path, kwargs.get("data")) + if not self._intrans: + m.commit() + return m + else: + name = self.__class__.__name__ + raise ValueError(f"unsupported file mode for {name}: {mode!r}") + + def cp_file(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1) + path2 = self._strip_protocol(path2) + if self.isfile(path1): + self.store[path2] = MemoryFile( + self, path2, self.store[path1].getvalue() + ) # implicit copy + elif self.isdir(path1): + if path2 not in self.pseudo_dirs: + self.pseudo_dirs.append(path2) + else: + raise FileNotFoundError(path1) + + def cat_file(self, path, start=None, end=None, **kwargs): + logger.debug("cat: %s", path) + path = self._strip_protocol(path) + try: + return bytes(self.store[path].getbuffer()[start:end]) + except KeyError as e: + raise FileNotFoundError(path) from e + + def _rm(self, path): + path = self._strip_protocol(path) + try: + del self.store[path] + except KeyError as e: + raise FileNotFoundError(path) from e + + def modified(self, path): + path = self._strip_protocol(path) + try: + return self.store[path].modified + except KeyError as e: + raise FileNotFoundError(path) from e + + def created(self, path): + path = self._strip_protocol(path) + try: + return self.store[path].created + except KeyError as e: + raise FileNotFoundError(path) from e + + def isfile(self, path): + path = self._strip_protocol(path) + return path in self.store + + def rm(self, path, recursive=False, maxdepth=None): + if isinstance(path, str): + path = self._strip_protocol(path) + else: + path = [self._strip_protocol(p) for p in path] + paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth) + for p in reversed(paths): + if self.isfile(p): + self.rm_file(p) + # If the expanded path doesn't exist, it is only because the expanded + # path was a directory that does not exist in self.pseudo_dirs. This + # is possible if you directly create files without making the + # directories first. + elif not self.exists(p): + continue + else: + self.rmdir(p) + + +class MemoryFile(BytesIO): + """A BytesIO which can't close and works as a context manager + + Can initialise with data. Each path should only be active once at any moment. + + No need to provide fs, path if auto-committing (default) + """ + + def __init__(self, fs=None, path=None, data=None): + logger.debug("open file %s", path) + self.fs = fs + self.path = path + self.created = datetime.now(tz=timezone.utc) + self.modified = datetime.now(tz=timezone.utc) + if data: + super().__init__(data) + self.seek(0) + + @property + def size(self): + return self.getbuffer().nbytes + + def __enter__(self): + return self + + def close(self): + pass + + def discard(self): + pass + + def commit(self): + self.fs.store[self.path] = self + self.modified = datetime.now(tz=timezone.utc) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/reference.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..1b5e1b1b6bc938f1cbc1c595e761e4d062aea31d --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/reference.py @@ -0,0 +1,1339 @@ +import base64 +import collections +import io +import itertools +import logging +import math +import os +from functools import lru_cache +from itertools import chain +from typing import TYPE_CHECKING, Literal + +import fsspec.core +from fsspec.spec import AbstractBufferedFile + +try: + import ujson as json +except ImportError: + if not TYPE_CHECKING: + import json + +from fsspec.asyn import AsyncFileSystem +from fsspec.callbacks import DEFAULT_CALLBACK +from fsspec.core import filesystem, open, split_protocol +from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper +from fsspec.utils import ( + isfilelike, + merge_offset_ranges, + other_paths, +) + +logger = logging.getLogger("fsspec.reference") + + +class ReferenceNotReachable(RuntimeError): + def __init__(self, reference, target, *args): + super().__init__(*args) + self.reference = reference + self.target = target + + def __str__(self): + return f'Reference "{self.reference}" failed to fetch target {self.target}' + + +def _first(d): + return next(iter(d.values())) + + +def _prot_in_references(path, references): + ref = references.get(path) + if isinstance(ref, (list, tuple)) and isinstance(ref[0], str): + return split_protocol(ref[0])[0] if ref[0] else ref[0] + + +def _protocol_groups(paths, references): + if isinstance(paths, str): + return {_prot_in_references(paths, references): [paths]} + out = {} + for path in paths: + protocol = _prot_in_references(path, references) + out.setdefault(protocol, []).append(path) + return out + + +class RefsValuesView(collections.abc.ValuesView): + def __iter__(self): + for val in self._mapping.zmetadata.values(): + yield json.dumps(val).encode() + yield from self._mapping._items.values() + for field in self._mapping.listdir(): + chunk_sizes = self._mapping._get_chunk_sizes(field) + if len(chunk_sizes) == 0: + yield self._mapping[field + "/0"] + continue + yield from self._mapping._generate_all_records(field) + + +class RefsItemsView(collections.abc.ItemsView): + def __iter__(self): + return zip(self._mapping.keys(), self._mapping.values()) + + +def ravel_multi_index(idx, sizes): + val = 0 + mult = 1 + for i, s in zip(idx[::-1], sizes[::-1]): + val += i * mult + mult *= s + return val + + +class LazyReferenceMapper(collections.abc.MutableMapping): + """This interface can be used to read/write references from Parquet stores. + It is not intended for other types of references. + It can be used with Kerchunk's MultiZarrToZarr method to combine + references into a parquet store. + Examples of this use-case can be found here: + https://fsspec.github.io/kerchunk/advanced.html?highlight=parquet#parquet-storage""" + + # import is class level to prevent numpy dep requirement for fsspec + @property + def np(self): + import numpy as np + + return np + + @property + def pd(self): + import pandas as pd + + return pd + + def __init__( + self, + root, + fs=None, + out_root=None, + cache_size=128, + categorical_threshold=10, + engine: Literal["fastparquet", "pyarrow"] = "fastparquet", + ): + """ + + This instance will be writable, storing changes in memory until full partitions + are accumulated or .flush() is called. + + To create an empty lazy store, use .create() + + Parameters + ---------- + root : str + Root of parquet store + fs : fsspec.AbstractFileSystem + fsspec filesystem object, default is local filesystem. + cache_size : int, default=128 + Maximum size of LRU cache, where cache_size*record_size denotes + the total number of references that can be loaded in memory at once. + categorical_threshold : int + Encode urls as pandas.Categorical to reduce memory footprint if the ratio + of the number of unique urls to total number of refs for each variable + is greater than or equal to this number. (default 10) + engine: Literal["fastparquet","pyarrow"] + Engine choice for reading parquet files. (default is "fastparquet") + """ + + self.root = root + self.chunk_sizes = {} + self.cat_thresh = categorical_threshold + self.engine = engine + self.cache_size = cache_size + self.url = self.root + "/{field}/refs.{record}.parq" + # TODO: derive fs from `root` + self.fs = fsspec.filesystem("file") if fs is None else fs + self.out_root = self.fs.unstrip_protocol(out_root or self.root) + + from importlib.util import find_spec + + if self.engine == "pyarrow" and find_spec("pyarrow") is None: + raise ImportError("engine choice `pyarrow` is not installed.") + + # Apply `lru_cache` decorator manually per instance. + # This way `self` reference is not held on class level. + # WARNING: However, this means that self and its members are not reflected + # in the cache key, so we expect they won't be mutated once a value is cached. + self.listdir = lru_cache()(self.listdir) + self._key_to_record = lru_cache(maxsize=4096)(self._key_to_record) + + def __getattr__(self, item): + if item in ("_items", "record_size", "zmetadata"): + self.setup() + # avoid possible recursion if setup fails somehow + return self.__dict__[item] + raise AttributeError(item) + + def setup(self): + self._items = {} + self._items[".zmetadata"] = self.fs.cat_file( + "/".join([self.root, ".zmetadata"]) + ) + met = json.loads(self._items[".zmetadata"]) + self.record_size = met["record_size"] + self.zmetadata = met["metadata"] + + # Define function to open and decompress refs + @lru_cache(maxsize=self.cache_size) + def open_refs(field, record): + """cached parquet file loader""" + path = self.url.format(field=field, record=record) + data = io.BytesIO(self.fs.cat_file(path)) + try: + df = self.pd.read_parquet(data, engine=self.engine) + refs = {c: df[c].to_numpy(copy=True) for c in df.columns} + except OSError: + refs = None + return refs + + self.open_refs = open_refs + + @staticmethod + def create(root, storage_options=None, fs=None, record_size=10000, **kwargs): + """Make empty parquet reference set + + First deletes the contents of the given directory, if it exists. + + Parameters + ---------- + root: str + Directory to contain the output; will be created + storage_options: dict | None + For making the filesystem to use for writing is fs is None + fs: FileSystem | None + Filesystem for writing + record_size: int + Number of references per parquet file + kwargs: passed to __init__ + + Returns + ------- + LazyReferenceMapper instance + """ + met = {"metadata": {}, "record_size": record_size} + if fs is None: + fs, root = fsspec.core.url_to_fs(root, **(storage_options or {})) + if fs.exists(root): + fs.rm(root, recursive=True) + fs.makedirs(root, exist_ok=True) + fs.pipe("/".join([root, ".zmetadata"]), json.dumps(met).encode()) + return LazyReferenceMapper(root, fs, **kwargs) + + def listdir(self): + """List top-level directories""" + dirs = (p.rsplit("/", 1)[0] for p in self.zmetadata if not p.startswith(".z")) + return set(dirs) + + def ls(self, path="", detail=True): + """Shortcut file listings""" + path = path.rstrip("/") + pathdash = path + "/" if path else "" + dirnames = self.listdir() + dirs = [ + d + for d in dirnames + if d.startswith(pathdash) and "/" not in d.lstrip(pathdash) + ] + if dirs: + others = { + f + for f in chain( + [".zmetadata"], + (name for name in self.zmetadata), + (name for name in self._items), + ) + if f.startswith(pathdash) and "/" not in f.lstrip(pathdash) + } + if detail is False: + others.update(dirs) + return sorted(others) + dirinfo = [{"name": name, "type": "directory", "size": 0} for name in dirs] + fileinfo = [ + { + "name": name, + "type": "file", + "size": len( + json.dumps(self.zmetadata[name]) + if name in self.zmetadata + else self._items[name] + ), + } + for name in others + ] + return sorted(dirinfo + fileinfo, key=lambda s: s["name"]) + field = path + others = set( + [name for name in self.zmetadata if name.startswith(f"{path}/")] + + [name for name in self._items if name.startswith(f"{path}/")] + ) + fileinfo = [ + { + "name": name, + "type": "file", + "size": len( + json.dumps(self.zmetadata[name]) + if name in self.zmetadata + else self._items[name] + ), + } + for name in others + ] + keys = self._keys_in_field(field) + + if detail is False: + return list(others) + list(keys) + recs = self._generate_all_records(field) + recinfo = [ + {"name": name, "type": "file", "size": rec[-1]} + for name, rec in zip(keys, recs) + if rec[0] # filters out path==None, deleted/missing + ] + return fileinfo + recinfo + + def _load_one_key(self, key): + """Get the reference for one key + + Returns bytes, one-element list or three-element list. + """ + if key in self._items: + return self._items[key] + elif key in self.zmetadata: + return json.dumps(self.zmetadata[key]).encode() + elif "/" not in key or self._is_meta(key): + raise KeyError(key) + field, _ = key.rsplit("/", 1) + record, ri, chunk_size = self._key_to_record(key) + maybe = self._items.get((field, record), {}).get(ri, False) + if maybe is None: + # explicitly deleted + raise KeyError + elif maybe: + return maybe + elif chunk_size == 0: + return b"" + + # Chunk keys can be loaded from row group and cached in LRU cache + try: + refs = self.open_refs(field, record) + except (ValueError, TypeError, FileNotFoundError) as exc: + raise KeyError(key) from exc + columns = ["path", "offset", "size", "raw"] + selection = [refs[c][ri] if c in refs else None for c in columns] + raw = selection[-1] + if raw is not None: + return raw + if selection[0] is None: + raise KeyError("This reference does not exist or has been deleted") + if selection[1:3] == [0, 0]: + # URL only + return selection[:1] + # URL, offset, size + return selection[:3] + + def _key_to_record(self, key): + """Details needed to construct a reference for one key""" + field, chunk = key.rsplit("/", 1) + chunk_sizes = self._get_chunk_sizes(field) + if len(chunk_sizes) == 0: + return 0, 0, 0 + chunk_idx = [int(c) for c in chunk.split(".")] + chunk_number = ravel_multi_index(chunk_idx, chunk_sizes) + record = chunk_number // self.record_size + ri = chunk_number % self.record_size + return record, ri, len(chunk_sizes) + + def _get_chunk_sizes(self, field): + """The number of chunks along each axis for a given field""" + if field not in self.chunk_sizes: + zarray = self.zmetadata[f"{field}/.zarray"] + size_ratio = [ + math.ceil(s / c) for s, c in zip(zarray["shape"], zarray["chunks"]) + ] + self.chunk_sizes[field] = size_ratio or [1] + return self.chunk_sizes[field] + + def _generate_record(self, field, record): + """The references for a given parquet file of a given field""" + refs = self.open_refs(field, record) + it = iter(zip(*refs.values())) + if len(refs) == 3: + # All urls + return (list(t) for t in it) + elif len(refs) == 1: + # All raws + return refs["raw"] + else: + # Mix of urls and raws + return (list(t[:3]) if not t[3] else t[3] for t in it) + + def _generate_all_records(self, field): + """Load all the references within a field by iterating over the parquet files""" + nrec = 1 + for ch in self._get_chunk_sizes(field): + nrec *= ch + nrec = math.ceil(nrec / self.record_size) + for record in range(nrec): + yield from self._generate_record(field, record) + + def values(self): + return RefsValuesView(self) + + def items(self): + return RefsItemsView(self) + + def __hash__(self): + return id(self) + + def __getitem__(self, key): + return self._load_one_key(key) + + def __setitem__(self, key, value): + if "/" in key and not self._is_meta(key): + field, chunk = key.rsplit("/", 1) + record, i, _ = self._key_to_record(key) + subdict = self._items.setdefault((field, record), {}) + subdict[i] = value + if len(subdict) == self.record_size: + self.write(field, record) + else: + # metadata or top-level + if hasattr(value, "to_bytes"): + val = value.to_bytes().decode() + elif isinstance(value, bytes): + val = value.decode() + else: + val = value + self._items[key] = val + new_value = json.loads(val) + self.zmetadata[key] = {**self.zmetadata.get(key, {}), **new_value} + + @staticmethod + def _is_meta(key): + return key.startswith(".z") or "/.z" in key + + def __delitem__(self, key): + if key in self._items: + del self._items[key] + elif key in self.zmetadata: + del self.zmetadata[key] + else: + if "/" in key and not self._is_meta(key): + field, _ = key.rsplit("/", 1) + record, i, _ = self._key_to_record(key) + subdict = self._items.setdefault((field, record), {}) + subdict[i] = None + if len(subdict) == self.record_size: + self.write(field, record) + else: + # metadata or top-level + self._items[key] = None + + def write(self, field, record, base_url=None, storage_options=None): + # extra requirements if writing + import kerchunk.df + import numpy as np + import pandas as pd + + partition = self._items[(field, record)] + original = False + if len(partition) < self.record_size: + try: + original = self.open_refs(field, record) + except OSError: + pass + + if original: + paths = original["path"] + offsets = original["offset"] + sizes = original["size"] + raws = original["raw"] + else: + paths = np.full(self.record_size, np.nan, dtype="O") + offsets = np.zeros(self.record_size, dtype="int64") + sizes = np.zeros(self.record_size, dtype="int64") + raws = np.full(self.record_size, np.nan, dtype="O") + for j, data in partition.items(): + if isinstance(data, list): + if ( + str(paths.dtype) == "category" + and data[0] not in paths.dtype.categories + ): + paths = paths.add_categories(data[0]) + paths[j] = data[0] + if len(data) > 1: + offsets[j] = data[1] + sizes[j] = data[2] + elif data is None: + # delete + paths[j] = None + offsets[j] = 0 + sizes[j] = 0 + raws[j] = None + else: + # this is the only call into kerchunk, could remove + raws[j] = kerchunk.df._proc_raw(data) + # TODO: only save needed columns + df = pd.DataFrame( + { + "path": paths, + "offset": offsets, + "size": sizes, + "raw": raws, + }, + copy=False, + ) + if df.path.count() / (df.path.nunique() or 1) > self.cat_thresh: + df["path"] = df["path"].astype("category") + object_encoding = {"raw": "bytes", "path": "utf8"} + has_nulls = ["path", "raw"] + + fn = f"{base_url or self.out_root}/{field}/refs.{record}.parq" + self.fs.mkdirs(f"{base_url or self.out_root}/{field}", exist_ok=True) + + if self.engine == "pyarrow": + df_backend_kwargs = {"write_statistics": False} + elif self.engine == "fastparquet": + df_backend_kwargs = { + "stats": False, + "object_encoding": object_encoding, + "has_nulls": has_nulls, + } + else: + raise NotImplementedError(f"{self.engine} not supported") + df.to_parquet( + fn, + engine=self.engine, + storage_options=storage_options + or getattr(self.fs, "storage_options", None), + compression="zstd", + index=False, + **df_backend_kwargs, + ) + + partition.clear() + self._items.pop((field, record)) + + def flush(self, base_url=None, storage_options=None): + """Output any modified or deleted keys + + Parameters + ---------- + base_url: str + Location of the output + """ + + # write what we have so far and clear sub chunks + for thing in list(self._items): + if isinstance(thing, tuple): + field, record = thing + self.write( + field, + record, + base_url=base_url, + storage_options=storage_options, + ) + + # gather .zmetadata from self._items and write that too + for k in list(self._items): + if k != ".zmetadata" and ".z" in k: + self.zmetadata[k] = json.loads(self._items.pop(k)) + met = {"metadata": self.zmetadata, "record_size": self.record_size} + self._items.clear() + self._items[".zmetadata"] = json.dumps(met).encode() + self.fs.pipe( + "/".join([base_url or self.out_root, ".zmetadata"]), + self._items[".zmetadata"], + ) + + # TODO: only clear those that we wrote to? + self.open_refs.cache_clear() + + def __len__(self): + # Caveat: This counts expected references, not actual - but is fast + count = 0 + for field in self.listdir(): + if field.startswith("."): + count += 1 + else: + count += math.prod(self._get_chunk_sizes(field)) + count += len(self.zmetadata) # all metadata keys + # any other files not in reference partitions + count += sum(1 for _ in self._items if not isinstance(_, tuple)) + return count + + def __iter__(self): + # Caveat: returns only existing keys, so the number of these does not + # match len(self) + metas = set(self.zmetadata) + metas.update(self._items) + for bit in metas: + if isinstance(bit, str): + yield bit + for field in self.listdir(): + for k in self._keys_in_field(field): + if k in self: + yield k + + def __contains__(self, item): + try: + self._load_one_key(item) + return True + except KeyError: + return False + + def _keys_in_field(self, field): + """List key names in given field + + Produces strings like "field/x.y" appropriate from the chunking of the array + """ + chunk_sizes = self._get_chunk_sizes(field) + if len(chunk_sizes) == 0: + yield field + "/0" + return + inds = itertools.product(*(range(i) for i in chunk_sizes)) + for ind in inds: + yield field + "/" + ".".join([str(c) for c in ind]) + + +class ReferenceFileSystem(AsyncFileSystem): + """View byte ranges of some other file as a file system + Initial version: single file system target, which must support + async, and must allow start and end args in _cat_file. Later versions + may allow multiple arbitrary URLs for the targets. + This FileSystem is read-only. It is designed to be used with async + targets (for now). We do not get original file details from the target FS. + Configuration is by passing a dict of references at init, or a URL to + a JSON file containing the same; this dict + can also contain concrete data for some set of paths. + Reference dict format: + {path0: bytes_data, path1: (target_url, offset, size)} + https://github.com/fsspec/kerchunk/blob/main/README.md + + simple_references: if True (default), no jinja interpreting is done, + which is the safe option. + """ + + protocol = "reference" + cachable = False + + def __init__( + self, + fo, + target=None, + ref_storage_args=None, + target_protocol=None, + target_options=None, + remote_protocol=None, + remote_options=None, + fs=None, + template_overrides=None, + simple_templates=True, + max_gap=64_000, + max_block=256_000_000, + cache_size=128, + **kwargs, + ): + """ + Parameters + ---------- + fo : dict or str + The set of references to use for this instance, with a structure as above. + If str referencing a JSON file, will use fsspec.open, in conjunction + with target_options and target_protocol to open and parse JSON at this + location. If a directory, then assume references are a set of parquet + files to be loaded lazily. + target : str + For any references having target_url as None, this is the default file + target to use + ref_storage_args : dict + If references is a str, use these kwargs for loading the JSON file. + Deprecated: use target_options instead. + target_protocol : str + Used for loading the reference file, if it is a path. If None, protocol + will be derived from the given path + target_options : dict + Extra FS options for loading the reference file ``fo``, if given as a path + remote_protocol : str + The protocol of the filesystem on which the references will be evaluated + (unless fs is provided). If not given, will be derived from the first + URL that has a protocol in the templates or in the references, in that + order. + remote_options : dict + kwargs to go with remote_protocol + fs : AbstractFileSystem | dict(str, (AbstractFileSystem | dict)) + Directly provide a file system(s): + - a single filesystem instance + - a dict of protocol:filesystem, where each value is either a filesystem + instance, or a dict of kwargs that can be used to create in + instance for the given protocol + + If this is given, remote_options and remote_protocol are ignored. + template_overrides : dict + Swap out any templates in the references file with these - useful for + testing. + simple_templates: bool + Whether templates can be processed with simple replace (True) or if + jinja is needed (False, much slower). All reference sets produced by + ``kerchunk`` are simple in this sense, but the spec allows for complex. + max_gap, max_block: int + For merging multiple concurrent requests to the same remote file. + Neighboring byte ranges will only be merged when their + inter-range gap is <= ``max_gap``. Default is 64KB. Set to 0 + to only merge when it requires no extra bytes. Pass a negative + number to disable merging, appropriate for local target files. + Neighboring byte ranges will only be merged when the size of + the aggregated range is <= ``max_block``. Default is 256MB. + cache_size : int + Maximum size of LRU cache, where cache_size*record_size denotes + the total number of references that can be loaded in memory at once. + Only used for lazily loaded references. + kwargs : passed to parent class + """ + super().__init__(**kwargs) + self.target = target + self.template_overrides = template_overrides + self.simple_templates = simple_templates + self.templates = {} + self.fss = {} + self._dircache = {} + self.max_gap = max_gap + self.max_block = max_block + if isinstance(fo, str): + dic = dict( + **(ref_storage_args or target_options or {}), protocol=target_protocol + ) + ref_fs, fo2 = fsspec.core.url_to_fs(fo, **dic) + if ".json" not in fo2 and ( + fo.endswith(("parq", "parquet", "/")) or ref_fs.isdir(fo2) + ): + # Lazy parquet refs + logger.info("Open lazy reference dict from URL %s", fo) + self.references = LazyReferenceMapper( + fo2, + fs=ref_fs, + cache_size=cache_size, + ) + else: + # text JSON + with fsspec.open(fo, "rb", **dic) as f: + logger.info("Read reference from URL %s", fo) + text = json.load(f) + self._process_references(text, template_overrides) + else: + # dictionaries + self._process_references(fo, template_overrides) + if isinstance(fs, dict): + self.fss = { + k: ( + fsspec.filesystem(k.split(":", 1)[0], **opts) + if isinstance(opts, dict) + else opts + ) + for k, opts in fs.items() + } + if None not in self.fss: + self.fss[None] = filesystem("file") + return + if fs is not None: + # single remote FS + remote_protocol = ( + fs.protocol[0] if isinstance(fs.protocol, tuple) else fs.protocol + ) + self.fss[remote_protocol] = fs + + if remote_protocol is None: + # get single protocol from any templates + for ref in self.templates.values(): + if callable(ref): + ref = ref() + protocol, _ = fsspec.core.split_protocol(ref) + if protocol and protocol not in self.fss: + fs = filesystem(protocol, **(remote_options or {})) + self.fss[protocol] = fs + if remote_protocol is None: + # get single protocol from references + # TODO: warning here, since this can be very expensive? + for ref in self.references.values(): + if callable(ref): + ref = ref() + if isinstance(ref, list) and ref[0]: + protocol, _ = fsspec.core.split_protocol(ref[0]) + if protocol not in self.fss: + fs = filesystem(protocol, **(remote_options or {})) + self.fss[protocol] = fs + # only use first remote URL + break + + if remote_protocol and remote_protocol not in self.fss: + fs = filesystem(remote_protocol, **(remote_options or {})) + self.fss[remote_protocol] = fs + + self.fss[None] = fs or filesystem("file") # default one + # Wrap any non-async filesystems to ensure async methods are available below + for k, f in self.fss.items(): + if not f.async_impl: + self.fss[k] = AsyncFileSystemWrapper(f, asynchronous=self.asynchronous) + elif self.asynchronous ^ f.asynchronous: + raise ValueError( + "Reference-FS's target filesystem must have same value " + "of asynchronous" + ) + + def _cat_common(self, path, start=None, end=None): + path = self._strip_protocol(path) + logger.debug(f"cat: {path}") + try: + part = self.references[path] + except KeyError as exc: + raise FileNotFoundError(path) from exc + if isinstance(part, str): + part = part.encode() + if hasattr(part, "to_bytes"): + part = part.to_bytes() + if isinstance(part, bytes): + logger.debug(f"Reference: {path}, type bytes") + if part.startswith(b"base64:"): + part = base64.b64decode(part[7:]) + return part, None, None + + if len(part) == 1: + logger.debug(f"Reference: {path}, whole file => {part}") + url = part[0] + start1, end1 = start, end + else: + url, start0, size = part + logger.debug(f"Reference: {path} => {url}, offset {start0}, size {size}") + end0 = start0 + size + + if start is not None: + if start >= 0: + start1 = start0 + start + else: + start1 = end0 + start + else: + start1 = start0 + if end is not None: + if end >= 0: + end1 = start0 + end + else: + end1 = end0 + end + else: + end1 = end0 + if url is None: + url = self.target + return url, start1, end1 + + async def _cat_file(self, path, start=None, end=None, **kwargs): + part_or_url, start0, end0 = self._cat_common(path, start=start, end=end) + if isinstance(part_or_url, bytes): + return part_or_url[start:end] + protocol, _ = split_protocol(part_or_url) + try: + return await self.fss[protocol]._cat_file( + part_or_url, start=start0, end=end0 + ) + except Exception as e: + raise ReferenceNotReachable(path, part_or_url) from e + + def cat_file(self, path, start=None, end=None, **kwargs): + part_or_url, start0, end0 = self._cat_common(path, start=start, end=end) + if isinstance(part_or_url, bytes): + return part_or_url[start:end] + protocol, _ = split_protocol(part_or_url) + try: + return self.fss[protocol].cat_file(part_or_url, start=start0, end=end0) + except Exception as e: + raise ReferenceNotReachable(path, part_or_url) from e + + def pipe_file(self, path, value, **_): + """Temporarily add binary data or reference as a file""" + self.references[path] = value + + async def _get_file(self, rpath, lpath, **kwargs): + if self.isdir(rpath): + return os.makedirs(lpath, exist_ok=True) + data = await self._cat_file(rpath) + with open(lpath, "wb") as f: + f.write(data) + + def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, **kwargs): + if self.isdir(rpath): + return os.makedirs(lpath, exist_ok=True) + data = self.cat_file(rpath, **kwargs) + callback.set_size(len(data)) + if isfilelike(lpath): + lpath.write(data) + else: + with open(lpath, "wb") as f: + f.write(data) + callback.absolute_update(len(data)) + + def get(self, rpath, lpath, recursive=False, **kwargs): + if recursive: + # trigger directory build + self.ls("") + rpath = self.expand_path(rpath, recursive=recursive) + fs = fsspec.filesystem("file", auto_mkdir=True) + targets = other_paths(rpath, lpath) + if recursive: + data = self.cat([r for r in rpath if not self.isdir(r)]) + else: + data = self.cat(rpath) + for remote, local in zip(rpath, targets): + if remote in data: + fs.pipe_file(local, data[remote]) + + def cat(self, path, recursive=False, on_error="raise", **kwargs): + if isinstance(path, str) and recursive: + raise NotImplementedError + if isinstance(path, list) and (recursive or any("*" in p for p in path)): + raise NotImplementedError + # TODO: if references is lazy, pre-fetch all paths in batch before access + proto_dict = _protocol_groups(path, self.references) + out = {} + for proto, paths in proto_dict.items(): + fs = self.fss[proto] + urls, starts, ends, valid_paths = [], [], [], [] + for p in paths: + # find references or label not-found. Early exit if any not + # found and on_error is "raise" + try: + u, s, e = self._cat_common(p) + if not isinstance(u, (bytes, str)): + # nan/None from parquet + continue + except FileNotFoundError as err: + if on_error == "raise": + raise + if on_error != "omit": + out[p] = err + else: + urls.append(u) + starts.append(s) + ends.append(e) + valid_paths.append(p) + + # process references into form for merging + urls2 = [] + starts2 = [] + ends2 = [] + paths2 = [] + whole_files = set() + for u, s, e, p in zip(urls, starts, ends, valid_paths): + if isinstance(u, bytes): + # data + out[p] = u + elif s is None: + # whole file - limits are None, None, but no further + # entries take for this file + whole_files.add(u) + urls2.append(u) + starts2.append(s) + ends2.append(e) + paths2.append(p) + for u, s, e, p in zip(urls, starts, ends, valid_paths): + # second run to account for files that are to be loaded whole + if s is not None and u not in whole_files: + urls2.append(u) + starts2.append(s) + ends2.append(e) + paths2.append(p) + + # merge and fetch consolidated ranges + new_paths, new_starts, new_ends = merge_offset_ranges( + list(urls2), + list(starts2), + list(ends2), + sort=True, + max_gap=self.max_gap, + max_block=self.max_block, + ) + bytes_out = fs.cat_ranges(new_paths, new_starts, new_ends) + + # unbundle from merged bytes - simple approach + for u, s, e, p in zip(urls, starts, ends, valid_paths): + if p in out: + continue # was bytes, already handled + for np, ns, ne, b in zip(new_paths, new_starts, new_ends, bytes_out): + if np == u and (ns is None or ne is None): + if isinstance(b, Exception): + out[p] = b + else: + out[p] = b[s:e] + elif np == u and s >= ns and e <= ne: + if isinstance(b, Exception): + out[p] = b + else: + out[p] = b[s - ns : (e - ne) or None] + + for k, v in out.copy().items(): + # these were valid references, but fetch failed, so transform exc + if isinstance(v, Exception) and k in self.references: + ex = out[k] + new_ex = ReferenceNotReachable(k, self.references[k]) + new_ex.__cause__ = ex + if on_error == "raise": + raise new_ex + elif on_error != "omit": + out[k] = new_ex + + if len(out) == 1 and isinstance(path, str) and "*" not in path: + return _first(out) + return out + + def _process_references(self, references, template_overrides=None): + vers = references.get("version", None) + if vers is None: + self._process_references0(references) + elif vers == 1: + self._process_references1(references, template_overrides=template_overrides) + else: + raise ValueError(f"Unknown reference spec version: {vers}") + # TODO: we make dircache by iterating over all entries, but for Spec >= 1, + # can replace with programmatic. Is it even needed for mapper interface? + + def _process_references0(self, references): + """Make reference dict for Spec Version 0""" + if isinstance(references, dict): + # do not do this for lazy/parquet backend, which will not make dicts, + # but must remain writable in the original object + references = { + key: json.dumps(val) if isinstance(val, dict) else val + for key, val in references.items() + } + self.references = references + + def _process_references1(self, references, template_overrides=None): + if not self.simple_templates or self.templates: + import jinja2.sandbox + self.references = {} + self._process_templates(references.get("templates", {})) + + @lru_cache(1000) + def _render_jinja(u): + return ( + jinja2.sandbox.SandboxedEnvironment() + .from_string(u) + .render(**self.templates) + ) + + for k, v in references.get("refs", {}).items(): + if isinstance(v, str): + if v.startswith("base64:"): + self.references[k] = base64.b64decode(v[7:]) + self.references[k] = v + elif isinstance(v, dict): + self.references[k] = json.dumps(v) + elif self.templates: + u = v[0] + if "{{" in u: + if self.simple_templates: + u = ( + u.replace("{{", "{") + .replace("}}", "}") + .format(**self.templates) + ) + else: + u = _render_jinja(u) + self.references[k] = [u] if len(v) == 1 else [u, v[1], v[2]] + else: + self.references[k] = v + self.references.update(self._process_gen(references.get("gen", []))) + + def _process_templates(self, tmp): + self.templates = {} + if self.template_overrides is not None: + tmp.update(self.template_overrides) + for k, v in tmp.items(): + if "{{" in v: + import jinja2.sandbox + + self.templates[k] = ( + lambda temp=v, **kwargs: jinja2.sandbox.SandboxedEnvironment() + .from_string(temp) + .render(**kwargs) + ) + else: + self.templates[k] = v + + def _process_gen(self, gens): + out = {} + if self.simple_templates: + return out + for gen in gens: + dimension = { + k: ( + v + if isinstance(v, list) + else range(v.get("start", 0), v["stop"], v.get("step", 1)) + ) + for k, v in gen["dimensions"].items() + } + products = ( + dict(zip(dimension.keys(), values)) + for values in itertools.product(*dimension.values()) + ) + for pr in products: + import jinja2.sandbox + + key = ( + jinja2.sandbox.SandboxedEnvironment() + .from_string(gen["key"]) + .render(**pr, **self.templates) + ) + url = ( + jinja2.sandbox.SandboxedEnvironment() + .from_string(gen["url"]) + .render(**pr, **self.templates) + ) + if ("offset" in gen) and ("length" in gen): + offset = int( + jinja2.sandbox.SandboxedEnvironment() + .from_string(gen["offset"]) + .render(**pr, **self.templates) + ) + length = int( + jinja2.sandbox.SandboxedEnvironment() + .from_string(gen["length"]) + .render(**pr, **self.templates) + ) + out[key] = [url, offset, length] + elif ("offset" in gen) ^ ("length" in gen): + raise ValueError( + "Both 'offset' and 'length' are required for a " + "reference generator entry if either is provided." + ) + else: + out[key] = [url] + return out + + def _dircache_from_items(self): + self.dircache = {"": []} + it = self.references.items() + for path, part in it: + if isinstance(part, (bytes, str)) or hasattr(part, "to_bytes"): + size = len(part) + elif len(part) == 1: + size = None + else: + _, _, size = part + par = path.rsplit("/", 1)[0] if "/" in path else "" + par0 = par + subdirs = [par0] + while par0 and par0 not in self.dircache: + # collect parent directories + par0 = self._parent(par0) + subdirs.append(par0) + + subdirs.reverse() + for parent, child in zip(subdirs, subdirs[1:]): + # register newly discovered directories + assert child not in self.dircache + assert parent in self.dircache + self.dircache[parent].append( + {"name": child, "type": "directory", "size": 0} + ) + self.dircache[child] = [] + + self.dircache[par].append({"name": path, "type": "file", "size": size}) + + def _open(self, path, mode="rb", block_size=None, cache_options=None, **kwargs): + part_or_url, start0, end0 = self._cat_common(path) + # This logic is kept outside `ReferenceFile` to avoid unnecessary redirection. + # That does mean `_cat_common` gets called twice if it eventually reaches `ReferenceFile`. + if isinstance(part_or_url, bytes): + return io.BytesIO(part_or_url[start0:end0]) + + protocol, _ = split_protocol(part_or_url) + if start0 is None and end0 is None: + return self.fss[protocol]._open( + part_or_url, + mode, + block_size=block_size, + cache_options=cache_options, + **kwargs, + ) + + return ReferenceFile( + self, + path, + mode, + block_size=block_size, + cache_options=cache_options, + **kwargs, + ) + + def ls(self, path, detail=True, **kwargs): + logger.debug("list %s", path) + path = self._strip_protocol(path) + if isinstance(self.references, LazyReferenceMapper): + try: + return self.references.ls(path, detail) + except KeyError: + pass + raise FileNotFoundError(f"'{path}' is not a known key") + if not self.dircache: + self._dircache_from_items() + out = self._ls_from_cache(path) + if out is None: + raise FileNotFoundError(path) + if detail: + return out + return [o["name"] for o in out] + + def exists(self, path, **kwargs): # overwrite auto-sync version + return self.isdir(path) or self.isfile(path) + + def isdir(self, path): # overwrite auto-sync version + if self.dircache: + return path in self.dircache + elif isinstance(self.references, LazyReferenceMapper): + return path in self.references.listdir() + else: + # this may be faster than building dircache for single calls, but + # by looping will be slow for many calls; could cache it? + return any(_.startswith(f"{path}/") for _ in self.references) + + def isfile(self, path): # overwrite auto-sync version + return path in self.references + + async def _ls(self, path, detail=True, **kwargs): # calls fast sync code + return self.ls(path, detail, **kwargs) + + def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs): + if withdirs: + return super().find( + path, maxdepth=maxdepth, withdirs=withdirs, detail=detail, **kwargs + ) + if path: + path = self._strip_protocol(path) + r = sorted(k for k in self.references if k.startswith(path)) + else: + r = sorted(self.references) + if detail: + if not self.dircache: + self._dircache_from_items() + return {k: self._ls_from_cache(k)[0] for k in r} + else: + return r + + def info(self, path, **kwargs): + out = self.references.get(path) + if out is not None: + if isinstance(out, (str, bytes)): + # decode base64 here + return {"name": path, "type": "file", "size": len(out)} + elif len(out) > 1: + return {"name": path, "type": "file", "size": out[2]} + else: + out0 = [{"name": path, "type": "file", "size": None}] + else: + out = self.ls(path, True) + out0 = [o for o in out if o["name"] == path] + if not out0: + return {"name": path, "type": "directory", "size": 0} + if out0[0]["size"] is None: + # if this is a whole remote file, update size using remote FS + prot, _ = split_protocol(self.references[path][0]) + out0[0]["size"] = self.fss[prot].size(self.references[path][0]) + return out0[0] + + async def _info(self, path, **kwargs): # calls fast sync code + return self.info(path) + + async def _rm_file(self, path, **kwargs): + self.references.pop( + path, None + ) # ignores FileNotFound, just as well for directories + self.dircache.clear() # this is a bit heavy handed + + async def _pipe_file(self, path, data, mode="overwrite", **kwargs): + if mode == "create" and self.exists(path): + raise FileExistsError + # can be str or bytes + self.references[path] = data + self.dircache.clear() # this is a bit heavy handed + + async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs): + # puts binary + if mode == "create" and self.exists(rpath): + raise FileExistsError + with open(lpath, "rb") as f: + self.references[rpath] = f.read() + self.dircache.clear() # this is a bit heavy handed + + def save_json(self, url, **storage_options): + """Write modified references into new location""" + out = {} + for k, v in self.references.items(): + if isinstance(v, bytes): + try: + out[k] = v.decode("ascii") + except UnicodeDecodeError: + out[k] = (b"base64:" + base64.b64encode(v)).decode() + else: + out[k] = v + with fsspec.open(url, "wb", **storage_options) as f: + f.write(json.dumps({"version": 1, "refs": out}).encode()) + + +class ReferenceFile(AbstractBufferedFile): + def __init__( + self, + fs, + path, + mode="rb", + block_size="default", + autocommit=True, + cache_type="readahead", + cache_options=None, + size=None, + **kwargs, + ): + super().__init__( + fs, + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + size=size, + cache_type=cache_type, + cache_options=cache_options, + **kwargs, + ) + part_or_url, self.start, self.end = self.fs._cat_common(self.path) + protocol, _ = split_protocol(part_or_url) + self.src_fs = self.fs.fss[protocol] + self.src_path = part_or_url + self._f = None + + @property + def f(self): + if self._f is None or self._f.closed: + self._f = self.src_fs._open( + self.src_path, + mode=self.mode, + block_size=self.blocksize, + autocommit=self.autocommit, + cache_type="none", + **self.kwargs, + ) + return self._f + + def close(self): + if self._f is not None: + self._f.close() + return super().close() + + def _fetch_range(self, start, end): + start = start + self.start + end = min(end + self.start, self.end) + self.f.seek(start) + return self.f.read(end - start) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/sftp.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/sftp.py new file mode 100644 index 0000000000000000000000000000000000000000..7c347963d692d50390b131225a56477b328f7a3c --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/sftp.py @@ -0,0 +1,187 @@ +import datetime +import logging +import os +import types +import uuid +from stat import S_ISDIR, S_ISLNK + +import paramiko + +from .. import AbstractFileSystem +from ..utils import infer_storage_options + +logger = logging.getLogger("fsspec.sftp") + + +class SFTPFileSystem(AbstractFileSystem): + """Files over SFTP/SSH + + Peer-to-peer filesystem over SSH using paramiko. + + Note: if using this with the ``open`` or ``open_files``, with full URLs, + there is no way to tell if a path is relative, so all paths are assumed + to be absolute. + """ + + protocol = "sftp", "ssh" + + def __init__(self, host, **ssh_kwargs): + """ + + Parameters + ---------- + host: str + Hostname or IP as a string + temppath: str + Location on the server to put files, when within a transaction + ssh_kwargs: dict + Parameters passed on to connection. See details in + https://docs.paramiko.org/en/3.3/api/client.html#paramiko.client.SSHClient.connect + May include port, username, password... + """ + if self._cached: + return + super().__init__(**ssh_kwargs) + self.temppath = ssh_kwargs.pop("temppath", "/tmp") # remote temp directory + self.host = host + self.ssh_kwargs = ssh_kwargs + self._connect() + + def _connect(self): + logger.debug("Connecting to SFTP server %s", self.host) + self.client = paramiko.SSHClient() + self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + self.client.connect(self.host, **self.ssh_kwargs) + self.ftp = self.client.open_sftp() + + @classmethod + def _strip_protocol(cls, path): + return infer_storage_options(path)["path"] + + @staticmethod + def _get_kwargs_from_urls(urlpath): + out = infer_storage_options(urlpath) + out.pop("path", None) + out.pop("protocol", None) + return out + + def mkdir(self, path, create_parents=True, mode=511): + path = self._strip_protocol(path) + logger.debug("Creating folder %s", path) + if self.exists(path): + raise FileExistsError(f"File exists: {path}") + + if create_parents: + self.makedirs(path) + else: + self.ftp.mkdir(path, mode) + + def makedirs(self, path, exist_ok=False, mode=511): + if self.exists(path) and not exist_ok: + raise FileExistsError(f"File exists: {path}") + + parts = path.split("/") + new_path = "/" if path[:1] == "/" else "" + + for part in parts: + if part: + new_path = f"{new_path}/{part}" if new_path else part + if not self.exists(new_path): + self.ftp.mkdir(new_path, mode) + + def rmdir(self, path): + path = self._strip_protocol(path) + logger.debug("Removing folder %s", path) + self.ftp.rmdir(path) + + def info(self, path): + path = self._strip_protocol(path) + stat = self._decode_stat(self.ftp.stat(path)) + stat["name"] = path + return stat + + @staticmethod + def _decode_stat(stat, parent_path=None): + if S_ISDIR(stat.st_mode): + t = "directory" + elif S_ISLNK(stat.st_mode): + t = "link" + else: + t = "file" + out = { + "name": "", + "size": stat.st_size, + "type": t, + "uid": stat.st_uid, + "gid": stat.st_gid, + "time": datetime.datetime.fromtimestamp( + stat.st_atime, tz=datetime.timezone.utc + ), + "mtime": datetime.datetime.fromtimestamp( + stat.st_mtime, tz=datetime.timezone.utc + ), + } + if parent_path: + out["name"] = "/".join([parent_path.rstrip("/"), stat.filename]) + return out + + def ls(self, path, detail=False): + path = self._strip_protocol(path) + logger.debug("Listing folder %s", path) + stats = [self._decode_stat(stat, path) for stat in self.ftp.listdir_iter(path)] + if detail: + return stats + else: + paths = [stat["name"] for stat in stats] + return sorted(paths) + + def put_file(self, lpath, rpath, callback=None, **kwargs): + self.mkdirs(self._parent(os.fspath(rpath)), exist_ok=True) + logger.debug("Put file %s into %s", lpath, rpath) + self.ftp.put(lpath, rpath) + + def get_file(self, rpath, lpath, **kwargs): + if self.isdir(rpath): + os.makedirs(lpath, exist_ok=True) + else: + self.ftp.get(self._strip_protocol(rpath), lpath) + + def _open(self, path, mode="rb", block_size=None, **kwargs): + """ + block_size: int or None + If 0, no buffering, if 1, line buffering, if >1, buffer that many + bytes, if None use default from paramiko. + """ + logger.debug("Opening file %s", path) + if kwargs.get("autocommit", True) is False: + # writes to temporary file, move on commit + path2 = "/".join([self.temppath, str(uuid.uuid4())]) + f = self.ftp.open(path2, mode, bufsize=block_size if block_size else -1) + f.temppath = path2 + f.targetpath = path + f.fs = self + f.commit = types.MethodType(commit_a_file, f) + f.discard = types.MethodType(discard_a_file, f) + else: + f = self.ftp.open(path, mode, bufsize=block_size if block_size else -1) + return f + + def _rm(self, path): + if self.isdir(path): + self.ftp.rmdir(path) + else: + self.ftp.remove(path) + + def mv(self, old, new): + new = self._strip_protocol(new) + old = self._strip_protocol(old) + logger.debug("Renaming %s into %s", old, new) + self.ftp.posix_rename(old, new) + + +def commit_a_file(self): + self.fs.mv(self.temppath, self.targetpath) + + +def discard_a_file(self): + self.fs._rm(self.temppath) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/smb.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/smb.py new file mode 100644 index 0000000000000000000000000000000000000000..db6b3f5c3702de90cf121ccca49f3ca2b580df9f --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/smb.py @@ -0,0 +1,416 @@ +""" +This module contains SMBFileSystem class responsible for handling access to +Windows Samba network shares by using package smbprotocol +""" + +import datetime +import re +import uuid +from stat import S_ISDIR, S_ISLNK + +import smbclient +import smbprotocol.exceptions + +from .. import AbstractFileSystem +from ..utils import infer_storage_options + +# ! pylint: disable=bad-continuation + + +class SMBFileSystem(AbstractFileSystem): + """Allow reading and writing to Windows and Samba network shares. + + When using `fsspec.open()` for getting a file-like object the URI + should be specified as this format: + ``smb://workgroup;user:password@server:port/share/folder/file.csv``. + + Example:: + + >>> import fsspec + >>> with fsspec.open( + ... 'smb://myuser:mypassword@myserver.com/' 'share/folder/file.csv' + ... ) as smbfile: + ... df = pd.read_csv(smbfile, sep='|', header=None) + + Note that you need to pass in a valid hostname or IP address for the host + component of the URL. Do not use the Windows/NetBIOS machine name for the + host component. + + The first component of the path in the URL points to the name of the shared + folder. Subsequent path components will point to the directory/folder/file. + + The URL components ``workgroup`` , ``user``, ``password`` and ``port`` may be + optional. + + .. note:: + + For working this source require `smbprotocol`_ to be installed, e.g.:: + + $ pip install smbprotocol + # or + # pip install smbprotocol[kerberos] + + .. _smbprotocol: https://github.com/jborean93/smbprotocol#requirements + + Note: if using this with the ``open`` or ``open_files``, with full URLs, + there is no way to tell if a path is relative, so all paths are assumed + to be absolute. + """ + + protocol = "smb" + + # pylint: disable=too-many-arguments + def __init__( + self, + host, + port=None, + username=None, + password=None, + timeout=60, + encrypt=None, + share_access=None, + register_session_retries=4, + register_session_retry_wait=1, + register_session_retry_factor=10, + auto_mkdir=False, + **kwargs, + ): + """ + You can use _get_kwargs_from_urls to get some kwargs from + a reasonable SMB url. + + Authentication will be anonymous or integrated if username/password are not + given. + + Parameters + ---------- + host: str + The remote server name/ip to connect to + port: int or None + Port to connect with. Usually 445, sometimes 139. + username: str or None + Username to connect with. Required if Kerberos auth is not being used. + password: str or None + User's password on the server, if using username + timeout: int + Connection timeout in seconds + encrypt: bool + Whether to force encryption or not, once this has been set to True + the session cannot be changed back to False. + share_access: str or None + Specifies the default access applied to file open operations + performed with this file system object. + This affects whether other processes can concurrently open a handle + to the same file. + + - None (the default): exclusively locks the file until closed. + - 'r': Allow other handles to be opened with read access. + - 'w': Allow other handles to be opened with write access. + - 'd': Allow other handles to be opened with delete access. + register_session_retries: int + Number of retries to register a session with the server. Retries are not performed + for authentication errors, as they are considered as invalid credentials and not network + issues. If set to negative value, no register attempts will be performed. + register_session_retry_wait: int + Time in seconds to wait between each retry. Number must be non-negative. + register_session_retry_factor: int + Base factor for the wait time between each retry. The wait time + is calculated using exponential function. For factor=1 all wait times + will be equal to `register_session_retry_wait`. For any number of retries, + the last wait time will be equal to `register_session_retry_wait` and for retries>1 + the first wait time will be equal to `register_session_retry_wait / factor`. + Number must be equal to or greater than 1. Optimal factor is 10. + auto_mkdir: bool + Whether, when opening a file, the directory containing it should + be created (if it doesn't already exist). This is assumed by pyarrow + and zarr-python code. + """ + super().__init__(**kwargs) + self.host = host + self.port = port + self.username = username + self.password = password + self.timeout = timeout + self.encrypt = encrypt + self.temppath = kwargs.pop("temppath", "") + self.share_access = share_access + self.register_session_retries = register_session_retries + if register_session_retry_wait < 0: + raise ValueError( + "register_session_retry_wait must be a non-negative integer" + ) + self.register_session_retry_wait = register_session_retry_wait + if register_session_retry_factor < 1: + raise ValueError( + "register_session_retry_factor must be a positive " + "integer equal to or greater than 1" + ) + self.register_session_retry_factor = register_session_retry_factor + self.auto_mkdir = auto_mkdir + self._connect() + + @property + def _port(self): + return 445 if self.port is None else self.port + + def _connect(self): + import time + + if self.register_session_retries <= -1: + return + + retried_errors = [] + + wait_time = self.register_session_retry_wait + n_waits = ( + self.register_session_retries - 1 + ) # -1 = No wait time after the last retry + factor = self.register_session_retry_factor + + # Generate wait times for each retry attempt. + # Wait times are calculated using exponential function. For factor=1 all wait times + # will be equal to `wait`. For any number of retries the last wait time will be + # equal to `wait` and for retries>2 the first wait time will be equal to `wait / factor`. + wait_times = iter( + factor ** (n / n_waits - 1) * wait_time for n in range(0, n_waits + 1) + ) + + for attempt in range(self.register_session_retries + 1): + try: + smbclient.register_session( + self.host, + username=self.username, + password=self.password, + port=self._port, + encrypt=self.encrypt, + connection_timeout=self.timeout, + ) + return + except ( + smbprotocol.exceptions.SMBAuthenticationError, + smbprotocol.exceptions.LogonFailure, + ): + # These exceptions should not be repeated, as they clearly indicate + # that the credentials are invalid and not a network issue. + raise + except ValueError as exc: + if re.findall(r"\[Errno -\d+]", str(exc)): + # This exception is raised by the smbprotocol.transport:Tcp.connect + # and originates from socket.gaierror (OSError). These exceptions might + # be raised due to network instability. We will retry to connect. + retried_errors.append(exc) + else: + # All another ValueError exceptions should be raised, as they are not + # related to network issues. + raise + except Exception as exc: + # Save the exception and retry to connect. This except might be dropped + # in the future, once all exceptions suited for retry are identified. + retried_errors.append(exc) + + if attempt < self.register_session_retries: + time.sleep(next(wait_times)) + + # Raise last exception to inform user about the connection issues. + # Note: Should we use ExceptionGroup to raise all exceptions? + raise retried_errors[-1] + + @classmethod + def _strip_protocol(cls, path): + return infer_storage_options(path)["path"] + + @staticmethod + def _get_kwargs_from_urls(path): + # smb://workgroup;user:password@host:port/share/folder/file.csv + out = infer_storage_options(path) + out.pop("path", None) + out.pop("protocol", None) + return out + + def mkdir(self, path, create_parents=True, **kwargs): + wpath = _as_unc_path(self.host, path) + if create_parents: + smbclient.makedirs(wpath, exist_ok=False, port=self._port, **kwargs) + else: + smbclient.mkdir(wpath, port=self._port, **kwargs) + + def makedirs(self, path, exist_ok=False): + if _share_has_path(path): + wpath = _as_unc_path(self.host, path) + smbclient.makedirs(wpath, exist_ok=exist_ok, port=self._port) + + def rmdir(self, path): + if _share_has_path(path): + wpath = _as_unc_path(self.host, path) + smbclient.rmdir(wpath, port=self._port) + + def info(self, path, **kwargs): + wpath = _as_unc_path(self.host, path) + stats = smbclient.stat(wpath, port=self._port, **kwargs) + if S_ISDIR(stats.st_mode): + stype = "directory" + elif S_ISLNK(stats.st_mode): + stype = "link" + else: + stype = "file" + res = { + "name": path + "/" if stype == "directory" else path, + "size": stats.st_size, + "type": stype, + "uid": stats.st_uid, + "gid": stats.st_gid, + "time": stats.st_atime, + "mtime": stats.st_mtime, + } + return res + + def created(self, path): + """Return the created timestamp of a file as a datetime.datetime""" + wpath = _as_unc_path(self.host, path) + stats = smbclient.stat(wpath, port=self._port) + return datetime.datetime.fromtimestamp(stats.st_ctime, tz=datetime.timezone.utc) + + def modified(self, path): + """Return the modified timestamp of a file as a datetime.datetime""" + wpath = _as_unc_path(self.host, path) + stats = smbclient.stat(wpath, port=self._port) + return datetime.datetime.fromtimestamp(stats.st_mtime, tz=datetime.timezone.utc) + + def ls(self, path, detail=True, **kwargs): + unc = _as_unc_path(self.host, path) + listed = smbclient.listdir(unc, port=self._port, **kwargs) + dirs = ["/".join([path.rstrip("/"), p]) for p in listed] + if detail: + dirs = [self.info(d) for d in dirs] + return dirs + + # pylint: disable=too-many-arguments + def _open( + self, + path, + mode="rb", + block_size=-1, + autocommit=True, + cache_options=None, + **kwargs, + ): + """ + block_size: int or None + If 0, no buffering, 1, line buffering, >1, buffer that many bytes + + Notes + ----- + By specifying 'share_access' in 'kwargs' it is possible to override the + default shared access setting applied in the constructor of this object. + """ + if self.auto_mkdir and "w" in mode: + self.makedirs(self._parent(path), exist_ok=True) + bls = block_size if block_size is not None and block_size >= 0 else -1 + wpath = _as_unc_path(self.host, path) + share_access = kwargs.pop("share_access", self.share_access) + if "w" in mode and autocommit is False: + temp = _as_temp_path(self.host, path, self.temppath) + return SMBFileOpener( + wpath, temp, mode, port=self._port, block_size=bls, **kwargs + ) + return smbclient.open_file( + wpath, + mode, + buffering=bls, + share_access=share_access, + port=self._port, + **kwargs, + ) + + def copy(self, path1, path2, **kwargs): + """Copy within two locations in the same filesystem""" + wpath1 = _as_unc_path(self.host, path1) + wpath2 = _as_unc_path(self.host, path2) + if self.auto_mkdir: + self.makedirs(self._parent(path2), exist_ok=True) + smbclient.copyfile(wpath1, wpath2, port=self._port, **kwargs) + + def _rm(self, path): + if _share_has_path(path): + wpath = _as_unc_path(self.host, path) + stats = smbclient.stat(wpath, port=self._port) + if S_ISDIR(stats.st_mode): + smbclient.rmdir(wpath, port=self._port) + else: + smbclient.remove(wpath, port=self._port) + + def mv(self, path1, path2, recursive=None, maxdepth=None, **kwargs): + wpath1 = _as_unc_path(self.host, path1) + wpath2 = _as_unc_path(self.host, path2) + smbclient.rename(wpath1, wpath2, port=self._port, **kwargs) + + +def _as_unc_path(host, path): + rpath = path.replace("/", "\\") + unc = f"\\\\{host}{rpath}" + return unc + + +def _as_temp_path(host, path, temppath): + share = path.split("/")[1] + temp_file = f"/{share}{temppath}/{uuid.uuid4()}" + unc = _as_unc_path(host, temp_file) + return unc + + +def _share_has_path(path): + parts = path.count("/") + if path.endswith("/"): + return parts > 2 + return parts > 1 + + +class SMBFileOpener: + """writes to remote temporary file, move on commit""" + + def __init__(self, path, temp, mode, port=445, block_size=-1, **kwargs): + self.path = path + self.temp = temp + self.mode = mode + self.block_size = block_size + self.kwargs = kwargs + self.smbfile = None + self._incontext = False + self.port = port + self._open() + + def _open(self): + if self.smbfile is None or self.smbfile.closed: + self.smbfile = smbclient.open_file( + self.temp, + self.mode, + port=self.port, + buffering=self.block_size, + **self.kwargs, + ) + + def commit(self): + """Move temp file to definitive on success.""" + # TODO: use transaction support in SMB protocol + smbclient.replace(self.temp, self.path, port=self.port) + + def discard(self): + """Remove the temp file on failure.""" + smbclient.remove(self.temp, port=self.port) + + def __fspath__(self): + return self.path + + def __iter__(self): + return self.smbfile.__iter__() + + def __getattr__(self, item): + return getattr(self.smbfile, item) + + def __enter__(self): + self._incontext = True + return self.smbfile.__enter__() + + def __exit__(self, exc_type, exc_value, traceback): + self._incontext = False + self.smbfile.__exit__(exc_type, exc_value, traceback) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/tar.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/tar.py new file mode 100644 index 0000000000000000000000000000000000000000..e3ecaba691ace8dd4109c06dd0ab8a3b02e34634 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/tar.py @@ -0,0 +1,139 @@ +import logging +import re +import tarfile + +import fsspec +from fsspec.archive import AbstractArchiveFileSystem +from fsspec.compression import compr +from fsspec.utils import infer_compression + +typemap = {b"0": "file", b"5": "directory"} + +logger = logging.getLogger("tar") + + +class TarFileSystem(AbstractArchiveFileSystem): + """Compressed Tar archives as a file-system (read-only) + + Supports the following formats: + tar.gz, tar.bz2, tar.xz + """ + + root_marker = "" + protocol = "tar" + cachable = False + + def __init__( + self, + fo="", + index_store=None, + target_options=None, + target_protocol=None, + compression=None, + **kwargs, + ): + super().__init__(**kwargs) + target_options = target_options or {} + + if isinstance(fo, str): + self.of = fsspec.open(fo, protocol=target_protocol, **target_options) + fo = self.of.open() # keep the reference + + # Try to infer compression. + if compression is None: + name = None + + # Try different ways to get hold of the filename. `fo` might either + # be a `fsspec.LocalFileOpener`, an `io.BufferedReader` or an + # `fsspec.AbstractFileSystem` instance. + try: + # Amended io.BufferedReader or similar. + # This uses a "protocol extension" where original filenames are + # propagated to archive-like filesystems in order to let them + # infer the right compression appropriately. + if hasattr(fo, "original"): + name = fo.original + + # fsspec.LocalFileOpener + elif hasattr(fo, "path"): + name = fo.path + + # io.BufferedReader + elif hasattr(fo, "name"): + name = fo.name + + # fsspec.AbstractFileSystem + elif hasattr(fo, "info"): + name = fo.info()["name"] + + except Exception as ex: + logger.warning( + f"Unable to determine file name, not inferring compression: {ex}" + ) + + if name is not None: + compression = infer_compression(name) + logger.info(f"Inferred compression {compression} from file name {name}") + + if compression is not None: + # TODO: tarfile already implements compression with modes like "'r:gz'", + # but then would seek to offset in the file work? + fo = compr[compression](fo) + + self._fo_ref = fo + self.fo = fo # the whole instance is a context + self.tar = tarfile.TarFile(fileobj=self.fo) + self.dir_cache = None + + self.index_store = index_store + self.index = None + self._index() + + def _index(self): + # TODO: load and set saved index, if exists + out = {} + for ti in self.tar: + info = ti.get_info() + info["type"] = typemap.get(info["type"], "file") + orig_name = info["name"].rstrip("/") + # Collapse duplicate slashes in the filesystem-facing name. + name = re.sub("/+", "/", orig_name) + info["name"] = name + out[name] = (info, ti.offset_data, orig_name) + + self.index = out + # TODO: save index to self.index_store here, if set + + def _get_dirs(self): + if self.dir_cache is not None: + return + + # This enables ls to get directories as children as well as files + self.dir_cache = { + dirname: {"name": dirname, "size": 0, "type": "directory"} + for dirname in self._all_dirnames(self.index) + } + self.dir_cache.update( + {info["name"]: info for info, _, _ in self.index.values()} + ) + + def _open(self, path, mode="rb", **kwargs): + if mode != "rb": + raise ValueError("Read-only filesystem implementation") + # Accept paths containing the archive's duplicate slashes too. + path = re.sub("/+", "/", path) + details, _, orig_name = self.index[path] + if details["type"] != "file": + raise ValueError("Can only handle regular files") + return self.tar.extractfile(orig_name) + + def close(self): + """Commits any write changes to the file. Done on ``del`` too.""" + self.tar.close() + + def __del__(self): + if hasattr(self, "tar"): + self.close() + del self.tar + if hasattr(self, "of") and hasattr(self.of, "__exit__"): + self.of.__exit__(None, None, None) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/webhdfs.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/webhdfs.py new file mode 100644 index 0000000000000000000000000000000000000000..e3048b6a3638cf34e400804a3057521e720b6e81 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/webhdfs.py @@ -0,0 +1,503 @@ +# https://hadoop.apache.org/docs/r1.0.4/webhdfs.html + +import logging +import os +import secrets +import shutil +import tempfile +import uuid +from contextlib import suppress +from datetime import datetime +from urllib.parse import quote + +import requests + +from ..spec import AbstractBufferedFile, AbstractFileSystem +from ..utils import infer_storage_options, tokenize + +logger = logging.getLogger("webhdfs") + + +class WebHDFS(AbstractFileSystem): + """ + Interface to HDFS over HTTP using the WebHDFS API. Supports also HttpFS gateways. + + Four auth mechanisms are supported: + + insecure: no auth is done, and the user is assumed to be whoever they + say they are (parameter ``user``), or a predefined value such as + "dr.who" if not given + spnego: when kerberos authentication is enabled, auth is negotiated by + requests_kerberos https://github.com/requests/requests-kerberos . + This establishes a session based on existing kinit login and/or + specified principal/password; parameters are passed with ``kerb_kwargs`` + token: uses an existing Hadoop delegation token from another secured + service. Indeed, this client can also generate such tokens when + not insecure. Note that tokens expire, but can be renewed (by a + previously specified user) and may allow for proxying. + basic-auth: used when both parameter ``user`` and parameter ``password`` + are provided. + + """ + + tempdir = str(tempfile.gettempdir()) + protocol = "webhdfs", "webHDFS" + + def __init__( + self, + host, + port=50070, + kerberos=False, + token=None, + user=None, + password=None, + proxy_to=None, + kerb_kwargs=None, + data_proxy=None, + use_https=False, + session_cert=None, + session_verify=True, + **kwargs, + ): + """ + Parameters + ---------- + host: str + Name-node address + port: int + Port for webHDFS + kerberos: bool + Whether to authenticate with kerberos for this connection + token: str or None + If given, use this token on every call to authenticate. A user + and user-proxy may be encoded in the token and should not be also + given + user: str or None + If given, assert the user name to connect with + password: str or None + If given, assert the password to use for basic auth. If password + is provided, user must be provided also + proxy_to: str or None + If given, the user has the authority to proxy, and this value is + the user in who's name actions are taken + kerb_kwargs: dict + Any extra arguments for HTTPKerberosAuth, see + ``_ + data_proxy: dict, callable or None + If given, map data-node addresses. This can be necessary if the + HDFS cluster is behind a proxy, running on Docker or otherwise has + a mismatch between the host-names given by the name-node and the + address by which to refer to them from the client. If a dict, + maps host names ``host->data_proxy[host]``; if a callable, full + URLs are passed, and function must conform to + ``url->data_proxy(url)``. + use_https: bool + Whether to connect to the Name-node using HTTPS instead of HTTP + session_cert: str or Tuple[str, str] or None + Path to a certificate file, or tuple of (cert, key) files to use + for the requests.Session + session_verify: str, bool or None + Path to a certificate file to use for verifying the requests.Session. + kwargs + """ + if self._cached: + return + super().__init__(**kwargs) + self.url = f"{'https' if use_https else 'http'}://{host}:{port}/webhdfs/v1" + self.kerb = kerberos + self.kerb_kwargs = kerb_kwargs or {} + self.pars = {} + self.proxy = data_proxy or {} + if token is not None: + if user is not None or proxy_to is not None: + raise ValueError( + "If passing a delegation token, must not set " + "user or proxy_to, as these are encoded in the" + " token" + ) + self.pars["delegation"] = token + self.user = user + self.password = password + + if password is not None: + if user is None: + raise ValueError( + "If passing a password, the user must also be" + "set in order to set up the basic-auth" + ) + else: + if user is not None: + self.pars["user.name"] = user + + if proxy_to is not None: + self.pars["doas"] = proxy_to + if kerberos and user is not None: + raise ValueError( + "If using Kerberos auth, do not specify the " + "user, this is handled by kinit." + ) + + self.session_cert = session_cert + self.session_verify = session_verify + + self._connect() + + self._fsid = f"webhdfs_{tokenize(host, port)}" + + @property + def fsid(self): + return self._fsid + + def _connect(self): + self.session = requests.Session() + + if self.session_cert: + self.session.cert = self.session_cert + + self.session.verify = self.session_verify + + if self.kerb: + from requests_kerberos import HTTPKerberosAuth + + self.session.auth = HTTPKerberosAuth(**self.kerb_kwargs) + + if self.user is not None and self.password is not None: + from requests.auth import HTTPBasicAuth + + self.session.auth = HTTPBasicAuth(self.user, self.password) + + def _call(self, op, method="get", path=None, data=None, redirect=True, **kwargs): + path = self._strip_protocol(path) if path is not None else "" + url = self._apply_proxy(self.url + quote(path, safe="/=")) + args = kwargs.copy() + args.update(self.pars) + args["op"] = op.upper() + logger.debug("sending %s with %s", url, method) + out = self.session.request( + method=method.upper(), + url=url, + params=args, + data=data, + allow_redirects=redirect, + ) + if out.status_code in [400, 401, 403, 404, 500]: + try: + err = out.json() + msg = err["RemoteException"]["message"] + exp = err["RemoteException"]["exception"] + except (ValueError, KeyError): + pass + else: + if exp in ["IllegalArgumentException", "UnsupportedOperationException"]: + raise ValueError(msg) + elif exp in ["SecurityException", "AccessControlException"]: + raise PermissionError(msg) + elif exp in ["FileNotFoundException"]: + raise FileNotFoundError(msg) + else: + raise RuntimeError(msg) + out.raise_for_status() + return out + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + replication=None, + permissions=None, + **kwargs, + ): + """ + + Parameters + ---------- + path: str + File location + mode: str + 'rb', 'wb', etc. + block_size: int + Client buffer size for read-ahead or write buffer + autocommit: bool + If False, writes to temporary file that only gets put in final + location upon commit + replication: int + Number of copies of file on the cluster, write mode only + permissions: str or int + posix permissions, write mode only + kwargs + + Returns + ------- + WebHDFile instance + """ + block_size = block_size or self.blocksize + return WebHDFile( + self, + path, + mode=mode, + block_size=block_size, + tempdir=self.tempdir, + autocommit=autocommit, + replication=replication, + permissions=permissions, + ) + + @staticmethod + def _process_info(info): + info["type"] = info["type"].lower() + info["size"] = info["length"] + return info + + @classmethod + def _strip_protocol(cls, path): + return infer_storage_options(path)["path"] + + @staticmethod + def _get_kwargs_from_urls(urlpath): + out = infer_storage_options(urlpath) + out.pop("path", None) + out.pop("protocol", None) + if "username" in out: + out["user"] = out.pop("username") + return out + + def info(self, path): + out = self._call("GETFILESTATUS", path=path) + info = out.json()["FileStatus"] + info["name"] = path + return self._process_info(info) + + def created(self, path): + """Return the created timestamp of a file as a datetime.datetime""" + # The API does not provide creation time, so we use modification time + info = self.info(path) + mtime = info.get("modificationTime", None) + if mtime is not None: + return datetime.fromtimestamp(mtime / 1000) + raise RuntimeError("Could not retrieve creation time (modification time).") + + def modified(self, path): + """Return the modified timestamp of a file as a datetime.datetime""" + info = self.info(path) + mtime = info.get("modificationTime", None) + if mtime is not None: + return datetime.fromtimestamp(mtime / 1000) + raise RuntimeError("Could not retrieve modification time.") + + def ls(self, path, detail=False, **kwargs): + out = self._call("LISTSTATUS", path=path) + infos = out.json()["FileStatuses"]["FileStatus"] + for info in infos: + self._process_info(info) + info["name"] = path.rstrip("/") + "/" + info["pathSuffix"] + if detail: + return sorted(infos, key=lambda i: i["name"]) + else: + return sorted(info["name"] for info in infos) + + def content_summary(self, path): + """Total numbers of files, directories and bytes under path""" + out = self._call("GETCONTENTSUMMARY", path=path) + return out.json()["ContentSummary"] + + def ukey(self, path): + """Checksum info of file, giving method and result""" + out = self._call("GETFILECHECKSUM", path=path, redirect=False) + if "Location" in out.headers: + location = self._apply_proxy(out.headers["Location"]) + out2 = self.session.get(location) + out2.raise_for_status() + return out2.json()["FileChecksum"] + else: + out.raise_for_status() + return out.json()["FileChecksum"] + + def home_directory(self): + """Get user's home directory""" + out = self._call("GETHOMEDIRECTORY") + return out.json()["Path"] + + def get_delegation_token(self, renewer=None): + """Retrieve token which can give the same authority to other uses + + Parameters + ---------- + renewer: str or None + User who may use this token; if None, will be current user + """ + if renewer: + out = self._call("GETDELEGATIONTOKEN", renewer=renewer) + else: + out = self._call("GETDELEGATIONTOKEN") + t = out.json()["Token"] + if t is None: + raise ValueError("No token available for this user/security context") + return t["urlString"] + + def renew_delegation_token(self, token): + """Make token live longer. Returns new expiry time""" + out = self._call("RENEWDELEGATIONTOKEN", method="put", token=token) + return out.json()["long"] + + def cancel_delegation_token(self, token): + """Stop the token from being useful""" + self._call("CANCELDELEGATIONTOKEN", method="put", token=token) + + def chmod(self, path, mod): + """Set the permission at path + + Parameters + ---------- + path: str + location to set (file or directory) + mod: str or int + posix epresentation or permission, give as oct string, e.g, '777' + or 0o777 + """ + self._call("SETPERMISSION", method="put", path=path, permission=mod) + + def chown(self, path, owner=None, group=None): + """Change owning user and/or group""" + kwargs = {} + if owner is not None: + kwargs["owner"] = owner + if group is not None: + kwargs["group"] = group + self._call("SETOWNER", method="put", path=path, **kwargs) + + def set_replication(self, path, replication): + """ + Set file replication factor + + Parameters + ---------- + path: str + File location (not for directories) + replication: int + Number of copies of file on the cluster. Should be smaller than + number of data nodes; normally 3 on most systems. + """ + self._call("SETREPLICATION", path=path, method="put", replication=replication) + + def mkdir(self, path, **kwargs): + self._call("MKDIRS", method="put", path=path) + + def makedirs(self, path, exist_ok=False): + if exist_ok is False and self.exists(path): + raise FileExistsError(path) + self.mkdir(path) + + def mv(self, path1, path2, **kwargs): + self._call("RENAME", method="put", path=path1, destination=path2) + + def rm(self, path, recursive=False, **kwargs): + self._call( + "DELETE", + method="delete", + path=path, + recursive="true" if recursive else "false", + ) + + def rm_file(self, path, **kwargs): + self.rm(path) + + def cp_file(self, lpath, rpath, **kwargs): + with self.open(lpath) as lstream: + tmp_fname = "/".join([self._parent(rpath), f".tmp.{secrets.token_hex(16)}"]) + # Perform an atomic copy (stream to a temporary file and + # move it to the actual destination). + try: + with self.open(tmp_fname, "wb") as rstream: + shutil.copyfileobj(lstream, rstream) + self.mv(tmp_fname, rpath) + except BaseException: + with suppress(FileNotFoundError): + self.rm(tmp_fname) + raise + + def _apply_proxy(self, location): + if self.proxy and callable(self.proxy): + location = self.proxy(location) + elif self.proxy: + # as a dict + for k, v in self.proxy.items(): + location = location.replace(k, v, 1) + return location + + +class WebHDFile(AbstractBufferedFile): + """A file living in HDFS over webHDFS""" + + def __init__(self, fs, path, **kwargs): + super().__init__(fs, path, **kwargs) + kwargs = kwargs.copy() + if kwargs.get("permissions", None) is None: + kwargs.pop("permissions", None) + if kwargs.get("replication", None) is None: + kwargs.pop("replication", None) + self.permissions = kwargs.pop("permissions", 511) + tempdir = kwargs.pop("tempdir") + if kwargs.pop("autocommit", False) is False: + self.target = self.path + self.path = os.path.join(tempdir, str(uuid.uuid4())) + + def _upload_chunk(self, final=False): + """Write one part of a multi-block file upload + + Parameters + ========== + final: bool + This is the last block, so should complete file, if + self.autocommit is True. + """ + out = self.fs.session.post( + self.location, + data=self.buffer.getvalue(), + headers={"content-type": "application/octet-stream"}, + ) + out.raise_for_status() + return True + + def _initiate_upload(self): + """Create remote file/upload""" + kwargs = self.kwargs.copy() + if "a" in self.mode: + op, method = "APPEND", "POST" + else: + op, method = "CREATE", "PUT" + kwargs["overwrite"] = "true" + out = self.fs._call(op, method, self.path, redirect=False, **kwargs) + location = self.fs._apply_proxy(out.headers["Location"]) + if "w" in self.mode: + # create empty file to append to + out2 = self.fs.session.put( + location, headers={"content-type": "application/octet-stream"} + ) + out2.raise_for_status() + # after creating empty file, change location to append to + out2 = self.fs._call("APPEND", "POST", self.path, redirect=False, **kwargs) + self.location = self.fs._apply_proxy(out2.headers["Location"]) + + def _fetch_range(self, start, end): + start = max(start, 0) + end = min(self.size, end) + if start >= end or start >= self.size: + return b"" + out = self.fs._call( + "OPEN", path=self.path, offset=start, length=end - start, redirect=False + ) + out.raise_for_status() + if "Location" in out.headers: + location = out.headers["Location"] + out2 = self.fs.session.get(self.fs._apply_proxy(location)) + return out2.content + else: + return out.content + + def commit(self): + self.fs.mv(self.path, self.target) + + def discard(self): + self.fs.rm(self.path) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/zip.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/zip.py new file mode 100644 index 0000000000000000000000000000000000000000..485307a34f8daba70eb30bfda713c95893bbdb0b --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/implementations/zip.py @@ -0,0 +1,183 @@ +import os +import zipfile + +import fsspec +from fsspec.archive import AbstractArchiveFileSystem + + +class ZipFileSystem(AbstractArchiveFileSystem): + """Read/Write contents of ZIP archive as a file-system + + Keeps file object open while instance lives. + + This class is pickleable, but not necessarily thread-safe + """ + + root_marker = "" + protocol = "zip" + cachable = False + + def __init__( + self, + fo="", + mode="r", + target_protocol=None, + target_options=None, + compression=zipfile.ZIP_STORED, + allowZip64=True, + compresslevel=None, + **kwargs, + ): + """ + Parameters + ---------- + fo: str or file-like + Contains ZIP, and must exist. If a str, will fetch file using + :meth:`~fsspec.open_files`, which must return one file exactly. + mode: str + Accept: "r", "w", "a" + target_protocol: str (optional) + If ``fo`` is a string, this value can be used to override the + FS protocol inferred from a URL + target_options: dict (optional) + Kwargs passed when instantiating the target FS, if ``fo`` is + a string. + compression, allowZip64, compresslevel: passed to ZipFile + Only relevant when creating a ZIP + """ + super().__init__(self, **kwargs) + if mode not in set("rwa"): + raise ValueError(f"mode '{mode}' no understood") + self.mode = mode + if isinstance(fo, (str, os.PathLike)): + if mode == "a": + m = "r+b" + else: + m = mode + "b" + fo = fsspec.open( + fo, mode=m, protocol=target_protocol, **(target_options or {}) + ) + self.force_zip_64 = allowZip64 + self.of = fo + self.fo = fo.__enter__() # the whole instance is a context + self.zip = zipfile.ZipFile( + self.fo, + mode=mode, + compression=compression, + allowZip64=allowZip64, + compresslevel=compresslevel, + ) + self.dir_cache = None + + @classmethod + def _strip_protocol(cls, path): + # zip file paths are always relative to the archive root + return super()._strip_protocol(path).lstrip("/") + + def __del__(self): + if hasattr(self, "zip"): + self.close() + del self.zip + if hasattr(self, "of") and hasattr(self.of, "__exit__"): + self.of.__exit__(None, None, None) + + def close(self): + """Commits any write changes to the file. Done on ``del`` too.""" + self.zip.close() + + def _get_dirs(self): + if self.dir_cache is None or self.mode in set("wa"): + # when writing, dir_cache is always in the ZipFile's attributes, + # not read from the file. + files = self.zip.infolist() + self.dir_cache = { + dirname.rstrip("/"): { + "name": dirname.rstrip("/"), + "size": 0, + "type": "directory", + } + for dirname in self._all_dirnames(self.zip.namelist()) + } + for z in files: + f = {s: getattr(z, s, None) for s in zipfile.ZipInfo.__slots__} + f.update( + { + "name": z.filename.rstrip("/"), + "size": z.file_size, + "type": ("directory" if z.is_dir() else "file"), + } + ) + self.dir_cache[f["name"]] = f + + def pipe_file(self, path, value, **kwargs): + # override upstream, because we know the exact file size in this case + self.zip.writestr(path, value, **kwargs) + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + path = self._strip_protocol(path) + if "r" in mode and self.mode in set("wa"): + if self.exists(path): + raise OSError("ZipFS can only be open for reading or writing, not both") + raise FileNotFoundError(path) + if "r" in self.mode and "w" in mode: + raise OSError("ZipFS can only be open for reading or writing, not both") + out = self.zip.open(path, mode.strip("b"), force_zip64=self.force_zip_64) + if "r" in mode: + info = self.info(path) + out.size = info["size"] + out.name = info["name"] + return out + + def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs): + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + def to_parts(_path: str): + return list(filter(None, _path.replace("\\", "/").split("/"))) + + if not isinstance(path, str): + path = str(path) + + # Remove the leading slash, as the zip file paths are always + # given without a leading slash + path = path.lstrip("/") + path_parts = to_parts(path) + path_depth = len(path_parts) + + self._get_dirs() + + result = {} + # To match posix find, if an exact file name is given, we should + # return only that file + if path in self.dir_cache and self.dir_cache[path]["type"] == "file": + result[path] = self.dir_cache[path] + return result if detail else [path] + + for file_path, file_info in self.dir_cache.items(): + if len(file_parts := to_parts(file_path)) < path_depth or any( + a != b for a, b in zip(path_parts, file_parts) + ): + # skip parent folders and mismatching paths + continue + + if file_info["type"] == "directory": + if withdirs and file_path not in result: + result[file_path.strip("/")] = file_info + continue + + if file_path not in result: + result[file_path] = file_info if detail else None + + if maxdepth: + result = { + k: v for k, v in result.items() if k.count("/") < maxdepth + path_depth + } + return result if detail else sorted(result) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/json.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/json.py new file mode 100644 index 0000000000000000000000000000000000000000..5c53a24913d0b28f4b53a163b97ff8f58abeb031 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/json.py @@ -0,0 +1,112 @@ +import json +from collections.abc import Callable, Mapping, Sequence +from contextlib import suppress +from pathlib import PurePath +from typing import Any, ClassVar + +from .registry import _import_class, get_filesystem_class +from .spec import AbstractFileSystem + + +class FilesystemJSONEncoder(json.JSONEncoder): + include_password: ClassVar[bool] = True + + def default(self, o: Any) -> Any: + if isinstance(o, AbstractFileSystem): + return o.to_dict(include_password=self.include_password) + if isinstance(o, PurePath): + cls = type(o) + return {"cls": f"{cls.__module__}.{cls.__name__}", "str": str(o)} + + return super().default(o) + + def make_serializable(self, obj: Any) -> Any: + """ + Recursively converts an object so that it can be JSON serialized via + :func:`json.dumps` and :func:`json.dump`, without actually calling + said functions. + """ + if isinstance(obj, (str, int, float, bool)): + return obj + if isinstance(obj, Mapping): + return {k: self.make_serializable(v) for k, v in obj.items()} + if isinstance(obj, Sequence): + return [self.make_serializable(v) for v in obj] + + return self.default(obj) + + +class FilesystemJSONDecoder(json.JSONDecoder): + def __init__( + self, + *, + object_hook: Callable[[dict[str, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + strict: bool = True, + object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None, + ) -> None: + self.original_object_hook = object_hook + + super().__init__( + object_hook=self.custom_object_hook, + parse_float=parse_float, + parse_int=parse_int, + parse_constant=parse_constant, + strict=strict, + object_pairs_hook=object_pairs_hook, + ) + + @classmethod + def try_resolve_path_cls(cls, dct: dict[str, Any]): + with suppress(Exception): + fqp = dct["cls"] + + path_cls = _import_class(fqp) + + if issubclass(path_cls, PurePath): + return path_cls + + return None + + @classmethod + def try_resolve_fs_cls(cls, dct: dict[str, Any]): + with suppress(Exception): + if "cls" in dct: + try: + fs_cls = _import_class(dct["cls"]) + if issubclass(fs_cls, AbstractFileSystem): + return fs_cls + except Exception: + if "protocol" in dct: # Fallback if cls cannot be imported + return get_filesystem_class(dct["protocol"]) + + raise + + return None + + def custom_object_hook(self, dct: dict[str, Any]): + if "cls" in dct: + if (obj_cls := self.try_resolve_fs_cls(dct)) is not None: + return AbstractFileSystem.from_dict(dct) + if (obj_cls := self.try_resolve_path_cls(dct)) is not None: + return obj_cls(dct["str"]) + + if self.original_object_hook is not None: + return self.original_object_hook(dct) + + return dct + + def unmake_serializable(self, obj: Any) -> Any: + """ + Inverse function of :meth:`FilesystemJSONEncoder.make_serializable`. + """ + if isinstance(obj, dict): + obj = self.custom_object_hook(obj) + if isinstance(obj, dict): + return {k: self.unmake_serializable(v) for k, v in obj.items()} + if isinstance(obj, (list, tuple)): + return [self.unmake_serializable(v) for v in obj] + + return obj diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/mapping.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..752eef35273b13eded7297e2e801b58e436a25b1 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/mapping.py @@ -0,0 +1,251 @@ +import array +import logging +import posixpath +import warnings +from collections.abc import MutableMapping +from functools import cached_property + +from fsspec.core import url_to_fs + +logger = logging.getLogger("fsspec.mapping") + + +class FSMap(MutableMapping): + """Wrap a FileSystem instance as a mutable wrapping. + + The keys of the mapping become files under the given root, and the + values (which must be bytes) the contents of those files. + + Parameters + ---------- + root: string + prefix for all the files + fs: FileSystem instance + check: bool (=True) + performs a touch at the location, to check for write access. + + Examples + -------- + >>> fs = FileSystem(**parameters) # doctest: +SKIP + >>> d = FSMap('my-data/path/', fs) # doctest: +SKIP + or, more likely + >>> d = fs.get_mapper('my-data/path/') + + >>> d['loc1'] = b'Hello World' # doctest: +SKIP + >>> list(d.keys()) # doctest: +SKIP + ['loc1'] + >>> d['loc1'] # doctest: +SKIP + b'Hello World' + """ + + def __init__(self, root, fs, check=False, create=False, missing_exceptions=None): + self.fs = fs + self.root = fs._strip_protocol(root) + self._root_key_to_str = fs._strip_protocol(posixpath.join(root, "x"))[:-1] + if missing_exceptions is None: + missing_exceptions = ( + FileNotFoundError, + IsADirectoryError, + NotADirectoryError, + ) + self.missing_exceptions = missing_exceptions + self.check = check + self.create = create + if create: + if not self.fs.exists(root): + self.fs.mkdir(root) + if check: + if not self.fs.exists(root): + raise ValueError( + f"Path {root} does not exist. Create " + f" with the ``create=True`` keyword" + ) + self.fs.touch(root + "/a") + self.fs.rm(root + "/a") + + @cached_property + def dirfs(self): + """dirfs instance that can be used with the same keys as the mapper""" + from .implementations.dirfs import DirFileSystem + + return DirFileSystem(path=self._root_key_to_str, fs=self.fs) + + def clear(self): + """Remove all keys below root - empties out mapping""" + logger.info("Clear mapping at %s", self.root) + try: + self.fs.rm(self.root, True) + self.fs.mkdir(self.root) + except: # noqa: E722 + pass + + def getitems(self, keys, on_error="raise"): + """Fetch multiple items from the store + + If the backend is async-able, this might proceed concurrently + + Parameters + ---------- + keys: list(str) + They keys to be fetched + on_error : "raise", "omit", "return" + If raise, an underlying exception will be raised (converted to KeyError + if the type is in self.missing_exceptions); if omit, keys with exception + will simply not be included in the output; if "return", all keys are + included in the output, but the value will be bytes or an exception + instance. + + Returns + ------- + dict(key, bytes|exception) + """ + keys2 = [self._key_to_str(k) for k in keys] + oe = on_error if on_error == "raise" else "return" + try: + out = self.fs.cat(keys2, on_error=oe) + if isinstance(out, bytes): + out = {keys2[0]: out} + except self.missing_exceptions as e: + raise KeyError from e + out = { + k: (KeyError() if isinstance(v, self.missing_exceptions) else v) + for k, v in out.items() + } + return { + key: out[k2] if on_error == "raise" else out.get(k2, KeyError(k2)) + for key, k2 in zip(keys, keys2) + if on_error == "return" or not isinstance(out[k2], BaseException) + } + + def setitems(self, values_dict): + """Set the values of multiple items in the store + + Parameters + ---------- + values_dict: dict(str, bytes) + """ + values = {self._key_to_str(k): maybe_convert(v) for k, v in values_dict.items()} + self.fs.pipe(values) + + def delitems(self, keys): + """Remove multiple keys from the store""" + self.fs.rm([self._key_to_str(k) for k in keys]) + + def _key_to_str(self, key): + """Generate full path for the key""" + if not isinstance(key, str): + # raise TypeError("key must be of type `str`, got `{type(key).__name__}`" + warnings.warn( + "from fsspec 2023.5 onward FSMap non-str keys will raise TypeError", + DeprecationWarning, + ) + if isinstance(key, list): + key = tuple(key) + key = str(key) + return f"{self._root_key_to_str}{key}".rstrip("/") + + def _str_to_key(self, s): + """Strip path of to leave key name""" + return s[len(self.root) :].lstrip("/") + + def __getitem__(self, key, default=None): + """Retrieve data""" + k = self._key_to_str(key) + try: + result = self.fs.cat(k) + except self.missing_exceptions as exc: + if default is not None: + return default + raise KeyError(key) from exc + return result + + def pop(self, key, default=None): + """Pop data""" + result = self.__getitem__(key, default) + try: + del self[key] + except KeyError: + pass + return result + + def __setitem__(self, key, value): + """Store value in key""" + key = self._key_to_str(key) + self.fs.mkdirs(self.fs._parent(key), exist_ok=True) + self.fs.pipe_file(key, maybe_convert(value)) + + def __iter__(self): + return (self._str_to_key(x) for x in self.fs.find(self.root)) + + def __len__(self): + return len(self.fs.find(self.root)) + + def __delitem__(self, key): + """Remove key""" + try: + self.fs.rm(self._key_to_str(key)) + except Exception as exc: + raise KeyError from exc + + def __contains__(self, key): + """Does key exist in mapping?""" + path = self._key_to_str(key) + return self.fs.isfile(path) + + def __reduce__(self): + return FSMap, (self.root, self.fs, False, False, self.missing_exceptions) + + +def maybe_convert(value): + if isinstance(value, array.array) or hasattr(value, "__array__"): + # bytes-like things + if hasattr(value, "dtype") and value.dtype.kind in "Mm": + # The buffer interface doesn't support datetime64/timdelta64 numpy + # arrays + value = value.view("int64") + value = bytes(memoryview(value)) + return value + + +def get_mapper( + url="", + check=False, + create=False, + missing_exceptions=None, + alternate_root=None, + **kwargs, +): + """Create key-value interface for given URL and options + + The URL will be of the form "protocol://location" and point to the root + of the mapper required. All keys will be file-names below this location, + and their values the contents of each key. + + Also accepts compound URLs like zip::s3://bucket/file.zip , see ``fsspec.open``. + + Parameters + ---------- + url: str + Root URL of mapping + check: bool + Whether to attempt to read from the location before instantiation, to + check that the mapping does exist + create: bool + Whether to make the directory corresponding to the root before + instantiating + missing_exceptions: None or tuple + If given, these exception types will be regarded as missing keys and + return KeyError when trying to read data. By default, you get + (FileNotFoundError, IsADirectoryError, NotADirectoryError) + alternate_root: None or str + In cases of complex URLs, the parser may fail to pick the correct part + for the mapper root, so this arg can override + + Returns + ------- + ``FSMap`` instance, the dict-like key-value store. + """ + # Removing protocol here - could defer to each open() on the backend + fs, urlpath = url_to_fs(url, **kwargs) + root = alternate_root if alternate_root is not None else urlpath + return FSMap(root, fs, check, create, missing_exceptions=missing_exceptions) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/parquet.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/parquet.py new file mode 100644 index 0000000000000000000000000000000000000000..e6e03fb14f9ec9224804a2ccb77bb84fe3390952 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/parquet.py @@ -0,0 +1,572 @@ +import io +import json +import warnings + +import fsspec + +from .core import url_to_fs +from .spec import AbstractBufferedFile +from .utils import merge_offset_ranges + +# Parquet-Specific Utilities for fsspec +# +# Most of the functions defined in this module are NOT +# intended for public consumption. The only exception +# to this is `open_parquet_file`, which should be used +# place of `fs.open()` to open parquet-formatted files +# on remote file systems. + + +class AlreadyBufferedFile(AbstractBufferedFile): + def _fetch_range(self, start, end): + raise NotImplementedError + + +def open_parquet_files( + path: list[str], + fs: None | fsspec.AbstractFileSystem = None, + metadata=None, + columns: None | list[str] = None, + row_groups: None | list[int] = None, + storage_options: None | dict = None, + engine: str = "auto", + max_gap: int = 64_000, + max_block: int = 256_000_000, + footer_sample_size: int = 1_000_000, + filters: None | list[list[list[str]]] = None, + **kwargs, +): + """ + Return a file-like object for a single Parquet file. + + The specified parquet `engine` will be used to parse the + footer metadata, and determine the required byte ranges + from the file. The target path will then be opened with + the "parts" (`KnownPartsOfAFile`) caching strategy. + + Note that this method is intended for usage with remote + file systems, and is unlikely to improve parquet-read + performance on local file systems. + + Parameters + ---------- + path: str + Target file path. + metadata: Any, optional + Parquet metadata object. Object type must be supported + by the backend parquet engine. For now, only the "fastparquet" + engine supports an explicit `ParquetFile` metadata object. + If a metadata object is supplied, the remote footer metadata + will not need to be transferred into local memory. + fs: AbstractFileSystem, optional + Filesystem object to use for opening the file. If nothing is + specified, an `AbstractFileSystem` object will be inferred. + engine : str, default "auto" + Parquet engine to use for metadata parsing. Allowed options + include "fastparquet", "pyarrow", and "auto". The specified + engine must be installed in the current environment. If + "auto" is specified, and both engines are installed, + "fastparquet" will take precedence over "pyarrow". + columns: list, optional + List of all column names that may be read from the file. + row_groups : list, optional + List of all row-groups that may be read from the file. This + may be a list of row-group indices (integers), or it may be + a list of `RowGroup` metadata objects (if the "fastparquet" + engine is used). + storage_options : dict, optional + Used to generate an `AbstractFileSystem` object if `fs` was + not specified. + max_gap : int, optional + Neighboring byte ranges will only be merged when their + inter-range gap is <= `max_gap`. Default is 64KB. + max_block : int, optional + Neighboring byte ranges will only be merged when the size of + the aggregated range is <= `max_block`. Default is 256MB. + footer_sample_size : int, optional + Number of bytes to read from the end of the path to look + for the footer metadata. If the sampled bytes do not contain + the footer, a second read request will be required, and + performance will suffer. Default is 1MB. + filters : list[list], optional + List of filters to apply to prevent reading row groups, of the + same format as accepted by the loading engines. Ignored if + ``row_groups`` is specified. + **kwargs : + Optional key-word arguments to pass to `fs.open` + """ + + # Make sure we have an `AbstractFileSystem` object + # to work with + if fs is None: + path0 = path + if isinstance(path, (list, tuple)): + path = path[0] + fs, path = url_to_fs(path, **(storage_options or {})) + else: + path0 = path + + # For now, `columns == []` not supported, is the same + # as all columns + if columns is not None and len(columns) == 0: + columns = None + + # Set the engine + engine = _set_engine(engine) + + if isinstance(path0, (list, tuple)): + paths = path0 + elif "*" in path: + paths = fs.glob(path) + elif path0.endswith("/"): # or fs.isdir(path): + paths = [ + _ + for _ in fs.find(path, withdirs=False, detail=False) + if _.endswith((".parquet", ".parq")) + ] + else: + paths = [path] + + data = _get_parquet_byte_ranges( + paths, + fs, + metadata=metadata, + columns=columns, + row_groups=row_groups, + engine=engine, + max_gap=max_gap, + max_block=max_block, + footer_sample_size=footer_sample_size, + filters=filters, + ) + + # Call self.open with "parts" caching + options = kwargs.pop("cache_options", {}).copy() + return [ + AlreadyBufferedFile( + fs=None, + path=fn, + mode="rb", + cache_type="parts", + cache_options={ + **options, + "data": ranges, + }, + size=max(_[1] for _ in ranges), + **kwargs, + ) + for fn, ranges in data.items() + ] + + +def open_parquet_file(*args, **kwargs): + """Create files tailed to reading specific parts of parquet files + + Please see ``open_parquet_files`` for details of the arguments. The + difference is, this function always returns a single ``AlreadyBufferedFile``, + whereas `open_parquet_files`` always returns a list of files, even if + there are one or zero matching parquet files. + """ + return open_parquet_files(*args, **kwargs)[0] + + +def _get_parquet_byte_ranges( + paths, + fs, + metadata=None, + columns=None, + row_groups=None, + max_gap=64_000, + max_block=256_000_000, + footer_sample_size=1_000_000, + engine="auto", + filters=None, +): + """Get a dictionary of the known byte ranges needed + to read a specific column/row-group selection from a + Parquet dataset. Each value in the output dictionary + is intended for use as the `data` argument for the + `KnownPartsOfAFile` caching strategy of a single path. + """ + + # Set engine if necessary + if isinstance(engine, str): + engine = _set_engine(engine) + + # Pass to a specialized function if metadata is defined + if metadata is not None: + # Use the provided parquet metadata object + # to avoid transferring/parsing footer metadata + return _get_parquet_byte_ranges_from_metadata( + metadata, + fs, + engine, + columns=columns, + row_groups=row_groups, + max_gap=max_gap, + max_block=max_block, + filters=filters, + ) + + # Populate global paths, starts, & ends + if columns is None and row_groups is None and filters is None: + # We are NOT selecting specific columns or row-groups. + # + # We can avoid sampling the footers, and just transfer + # all file data with cat_ranges + result = {path: {(0, len(data)): data} for path, data in fs.cat(paths).items()} + else: + # We ARE selecting specific columns or row-groups. + # + # Get file sizes asynchronously + file_sizes = fs.sizes(paths) + data_paths = [] + data_starts = [] + data_ends = [] + # Gather file footers. + # We just take the last `footer_sample_size` bytes of each + # file (or the entire file if it is smaller than that) + footer_starts = [ + max(0, file_size - footer_sample_size) for file_size in file_sizes + ] + footer_samples = fs.cat_ranges(paths, footer_starts, file_sizes) + + # Check our footer samples and re-sample if necessary. + large_footer = [] + for i, path in enumerate(paths): + footer_size = int.from_bytes(footer_samples[i][-8:-4], "little") + real_footer_start = file_sizes[i] - (footer_size + 8) + if real_footer_start < footer_starts[i]: + large_footer.append((i, real_footer_start)) + if large_footer: + warnings.warn( + f"Not enough data was used to sample the parquet footer. " + f"Try setting footer_sample_size >= {large_footer}." + ) + path0 = [paths[i] for i, _ in large_footer] + starts = [_[1] for _ in large_footer] + ends = [file_sizes[i] - footer_sample_size for i, _ in large_footer] + data = fs.cat_ranges(path0, starts, ends) + for i, (path, start, block) in enumerate(zip(path0, starts, data)): + footer_samples[i] = block + footer_samples[i] + footer_starts[i] = start + result = { + path: {(start, size): data} + for path, start, size, data in zip( + paths, footer_starts, file_sizes, footer_samples + ) + } + + # Calculate required byte ranges for each path + for i, path in enumerate(paths): + # Use "engine" to collect data byte ranges + path_data_starts, path_data_ends = engine._parquet_byte_ranges( + columns, + row_groups=row_groups, + footer=footer_samples[i], + footer_start=footer_starts[i], + filters=filters, + ) + + data_paths += [path] * len(path_data_starts) + data_starts += path_data_starts + data_ends += path_data_ends + + # Merge adjacent offset ranges + data_paths, data_starts, data_ends = merge_offset_ranges( + data_paths, + data_starts, + data_ends, + max_gap=max_gap, + max_block=max_block, + sort=True, + ) + + # Transfer the data byte-ranges into local memory + _transfer_ranges(fs, result, data_paths, data_starts, data_ends) + + # Add b"PAR1" to headers + _add_header_magic(result) + + return result + + +def _get_parquet_byte_ranges_from_metadata( + metadata, + fs, + engine, + columns=None, + row_groups=None, + max_gap=64_000, + max_block=256_000_000, + filters=None, +): + """Simplified version of `_get_parquet_byte_ranges` for + the case that an engine-specific `metadata` object is + provided, and the remote footer metadata does not need to + be transferred before calculating the required byte ranges. + """ + + # Use "engine" to collect data byte ranges + data_paths, data_starts, data_ends = engine._parquet_byte_ranges( + columns, row_groups=row_groups, metadata=metadata, filters=filters + ) + + # Merge adjacent offset ranges + data_paths, data_starts, data_ends = merge_offset_ranges( + data_paths, + data_starts, + data_ends, + max_gap=max_gap, + max_block=max_block, + sort=False, # Should be sorted + ) + + # Transfer the data byte-ranges into local memory + result = {fn: {} for fn in list(set(data_paths))} + _transfer_ranges(fs, result, data_paths, data_starts, data_ends) + + # Add b"PAR1" to header + _add_header_magic(result) + + return result + + +def _transfer_ranges(fs, blocks, paths, starts, ends): + # Use cat_ranges to gather the data byte_ranges + ranges = (paths, starts, ends) + for path, start, stop, data in zip(*ranges, fs.cat_ranges(*ranges)): + blocks[path][(start, stop)] = data + + +def _add_header_magic(data): + # Add b"PAR1" to file headers + for path in list(data): + add_magic = True + for k in data[path]: + if k[0] == 0 and k[1] >= 4: + add_magic = False + break + if add_magic: + data[path][(0, 4)] = b"PAR1" + + +def _set_engine(engine_str): + # Define a list of parquet engines to try + if engine_str == "auto": + try_engines = ("fastparquet", "pyarrow") + elif not isinstance(engine_str, str): + raise ValueError( + "Failed to set parquet engine! " + "Please pass 'fastparquet', 'pyarrow', or 'auto'" + ) + elif engine_str not in ("fastparquet", "pyarrow"): + raise ValueError(f"{engine_str} engine not supported by `fsspec.parquet`") + else: + try_engines = [engine_str] + + # Try importing the engines in `try_engines`, + # and choose the first one that succeeds + for engine in try_engines: + try: + if engine == "fastparquet": + return FastparquetEngine() + elif engine == "pyarrow": + return PyarrowEngine() + except ImportError: + pass + + # Raise an error if a supported parquet engine + # was not found + raise ImportError( + f"The following parquet engines are not installed " + f"in your python environment: {try_engines}." + f"Please install 'fastparquert' or 'pyarrow' to " + f"utilize the `fsspec.parquet` module." + ) + + +class FastparquetEngine: + # The purpose of the FastparquetEngine class is + # to check if fastparquet can be imported (on initialization) + # and to define a `_parquet_byte_ranges` method. In the + # future, this class may also be used to define other + # methods/logic that are specific to fastparquet. + + def __init__(self): + import fastparquet as fp + + self.fp = fp + + def _parquet_byte_ranges( + self, + columns, + row_groups=None, + metadata=None, + footer=None, + footer_start=None, + filters=None, + ): + # Initialize offset ranges and define ParqetFile metadata + pf = metadata + data_paths, data_starts, data_ends = [], [], [] + if filters and row_groups: + raise ValueError("filters and row_groups cannot be used together") + if pf is None: + pf = self.fp.ParquetFile(io.BytesIO(footer)) + + # Convert columns to a set and add any index columns + # specified in the pandas metadata (just in case) + column_set = None if columns is None else {c.split(".", 1)[0] for c in columns} + if column_set is not None and hasattr(pf, "pandas_metadata"): + md_index = [ + ind + for ind in pf.pandas_metadata.get("index_columns", []) + # Ignore RangeIndex information + if not isinstance(ind, dict) + ] + column_set |= set(md_index) + + # Check if row_groups is a list of integers + # or a list of row-group metadata + if filters: + from fastparquet.api import filter_row_groups + + row_group_indices = None + row_groups = filter_row_groups(pf, filters) + elif row_groups and not isinstance(row_groups[0], int): + # Input row_groups contains row-group metadata + row_group_indices = None + else: + # Input row_groups contains row-group indices + row_group_indices = row_groups + row_groups = pf.row_groups + if column_set is not None: + column_set = [ + _ if isinstance(_, list) else _.split(".") for _ in column_set + ] + + # Loop through column chunks to add required byte ranges + for r, row_group in enumerate(row_groups): + # Skip this row-group if we are targeting + # specific row-groups + if row_group_indices is None or r in row_group_indices: + # Find the target parquet-file path for `row_group` + fn = pf.row_group_filename(row_group) + + for column in row_group.columns: + name = column.meta_data.path_in_schema + # Skip this column if we are targeting specific columns + if column_set is None or _cmp(name, column_set): + file_offset0 = column.meta_data.dictionary_page_offset + if file_offset0 is None: + file_offset0 = column.meta_data.data_page_offset + num_bytes = column.meta_data.total_compressed_size + if footer_start is None or file_offset0 < footer_start: + data_paths.append(fn) + data_starts.append(file_offset0) + data_ends.append( + min( + file_offset0 + num_bytes, + footer_start or (file_offset0 + num_bytes), + ) + ) + + if metadata: + # The metadata in this call may map to multiple + # file paths. Need to include `data_paths` + return data_paths, data_starts, data_ends + return data_starts, data_ends + + +class PyarrowEngine: + # The purpose of the PyarrowEngine class is + # to check if pyarrow can be imported (on initialization) + # and to define a `_parquet_byte_ranges` method. In the + # future, this class may also be used to define other + # methods/logic that are specific to pyarrow. + + def __init__(self): + import pyarrow.parquet as pq + + self.pq = pq + + def _parquet_byte_ranges( + self, + columns, + row_groups=None, + metadata=None, + footer=None, + footer_start=None, + filters=None, + ): + if metadata is not None: + raise ValueError("metadata input not supported for PyarrowEngine") + if filters: + # there must be a way! + raise NotImplementedError + + data_starts, data_ends = [], [] + md = self.pq.ParquetFile(io.BytesIO(footer)).metadata + + # Convert columns to a set and add any index columns + # specified in the pandas metadata (just in case) + column_set = None if columns is None else set(columns) + if column_set is not None: + schema = md.schema.to_arrow_schema() + has_pandas_metadata = ( + schema.metadata is not None and b"pandas" in schema.metadata + ) + if has_pandas_metadata: + md_index = [ + ind + for ind in json.loads( + schema.metadata[b"pandas"].decode("utf8") + ).get("index_columns", []) + # Ignore RangeIndex information + if not isinstance(ind, dict) + ] + column_set |= set(md_index) + if column_set is not None: + column_set = [ + _[:1] if isinstance(_, list) else _.split(".")[:1] for _ in column_set + ] + + # Loop through column chunks to add required byte ranges + for r in range(md.num_row_groups): + # Skip this row-group if we are targeting + # specific row-groups + if row_groups is None or r in row_groups: + row_group = md.row_group(r) + for c in range(row_group.num_columns): + column = row_group.column(c) + name = column.path_in_schema.split(".") + # Skip this column if we are targeting specific columns + if column_set is None or _cmp(name, column_set): + meta = column.to_dict() + # Any offset could be the first one + file_offset0 = min( + _ + for _ in [ + meta.get("dictionary_page_offset"), + meta.get("data_page_offset"), + meta.get("index_page_offset"), + ] + if _ is not None + ) + if file_offset0 < footer_start: + data_starts.append(file_offset0) + data_ends.append( + min( + meta["total_compressed_size"] + file_offset0, + footer_start, + ) + ) + + data_starts.append(footer_start) + data_ends.append(footer_start + len(footer)) + return data_starts, data_ends + + +def _cmp(name, column_set): + return any(all(a == b for a, b in zip(name, _)) for _ in column_set) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/registry.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..305d1e8908504fb6c38e94708bd7f20dba722705 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/registry.py @@ -0,0 +1,337 @@ +from __future__ import annotations + +import importlib +import types +import warnings + +__all__ = ["registry", "get_filesystem_class", "default"] + +# internal, mutable +_registry: dict[str, type] = {} + +# external, immutable +registry = types.MappingProxyType(_registry) +default = "file" + + +def register_implementation(name, cls, clobber=False, errtxt=None): + """Add implementation class to the registry + + Parameters + ---------- + name: str + Protocol name to associate with the class + cls: class or str + if a class: fsspec-compliant implementation class (normally inherits from + ``fsspec.AbstractFileSystem``, gets added straight to the registry. If a + str, the full path to an implementation class like package.module.class, + which gets added to known_implementations, + so the import is deferred until the filesystem is actually used. + clobber: bool (optional) + Whether to overwrite a protocol with the same name; if False, will raise + instead. + errtxt: str (optional) + If given, then a failure to import the given class will result in this + text being given. + """ + if isinstance(cls, str): + if name in known_implementations and clobber is False: + if cls != known_implementations[name]["class"]: + raise ValueError( + f"Name ({name}) already in the known_implementations and clobber " + f"is False" + ) + else: + known_implementations[name] = { + "class": cls, + "err": errtxt or f"{cls} import failed for protocol {name}", + } + + else: + if name in registry and clobber is False: + if _registry[name] is not cls: + raise ValueError( + f"Name ({name}) already in the registry and clobber is False" + ) + else: + _registry[name] = cls + + +# protocols mapped to the class which implements them. This dict can be +# updated with register_implementation +known_implementations = { + "abfs": { + "class": "adlfs.AzureBlobFileSystem", + "err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage", + }, + "adl": { + "class": "adlfs.AzureDatalakeFileSystem", + "err": ( + "Azure Data Lake Storage Gen1 is retired and no longer supported. Please " + "install adlfs and use the `az://` protocol to access Azure Blob Storage " + "and Azure Data Lake Storage Gen2 instead." + ), + }, + "arrow_hdfs": { + "class": "fsspec.implementations.arrow.HadoopFileSystem", + "err": "pyarrow and local java libraries required for HDFS", + }, + "async_wrapper": { + "class": "fsspec.implementations.asyn_wrapper.AsyncFileSystemWrapper", + }, + "asynclocal": { + "class": "morefs.asyn_local.AsyncLocalFileSystem", + "err": "Install 'morefs[asynclocalfs]' to use AsyncLocalFileSystem", + }, + "asyncwrapper": { + "class": "fsspec.implementations.asyn_wrapper.AsyncFileSystemWrapper", + }, + "az": { + "class": "adlfs.AzureBlobFileSystem", + "err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage", + }, + "blockcache": {"class": "fsspec.implementations.cached.CachingFileSystem"}, + "box": { + "class": "boxfs.BoxFileSystem", + "err": "Please install boxfs to access BoxFileSystem", + }, + "cached": {"class": "fsspec.implementations.cached.CachingFileSystem"}, + "dask": { + "class": "fsspec.implementations.dask.DaskWorkerFileSystem", + "err": "Install dask distributed to access worker file system", + }, + "data": {"class": "fsspec.implementations.data.DataFileSystem"}, + "dbfs": { + "class": "fsspec.implementations.dbfs.DatabricksFileSystem", + "err": "Install the requests package to use the DatabricksFileSystem", + }, + "dir": {"class": "fsspec.implementations.dirfs.DirFileSystem"}, + "dropbox": { + "class": "dropboxdrivefs.DropboxDriveFileSystem", + "err": ( + 'DropboxFileSystem requires "dropboxdrivefs","requests" and "' + '"dropbox" to be installed' + ), + }, + "dvc": { + "class": "dvc.api.DVCFileSystem", + "err": "Install dvc to access DVCFileSystem", + }, + "file": {"class": "fsspec.implementations.local.LocalFileSystem"}, + "filecache": {"class": "fsspec.implementations.cached.WholeFileCacheFileSystem"}, + "ftp": {"class": "fsspec.implementations.ftp.FTPFileSystem"}, + "gcs": { + "class": "gcsfs.GCSFileSystem", + "err": "Please install gcsfs to access Google Storage", + }, + "gdrive": { + "class": "gdrive_fsspec.GoogleDriveFileSystem", + "err": "Please install gdrive_fs for access to Google Drive", + }, + "generic": {"class": "fsspec.generic.GenericFileSystem"}, + "gist": { + "class": "fsspec.implementations.gist.GistFileSystem", + "err": "Install the requests package to use the gist FS", + }, + "git": { + "class": "fsspec.implementations.git.GitFileSystem", + "err": "Install pygit2 to browse local git repos", + }, + "github": { + "class": "fsspec.implementations.github.GithubFileSystem", + "err": "Install the requests package to use the github FS", + }, + "gs": { + "class": "gcsfs.GCSFileSystem", + "err": "Please install gcsfs to access Google Storage", + }, + "hdfs": { + "class": "fsspec.implementations.arrow.HadoopFileSystem", + "err": "pyarrow and local java libraries required for HDFS", + }, + "hf": { + "class": "huggingface_hub.HfFileSystem", + "err": "Install huggingface_hub to access HfFileSystem", + }, + "http": { + "class": "fsspec.implementations.http.HTTPFileSystem", + "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed', + }, + "https": { + "class": "fsspec.implementations.http.HTTPFileSystem", + "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed', + }, + "jlab": { + "class": "fsspec.implementations.jupyter.JupyterFileSystem", + "err": "Jupyter FS requires requests to be installed", + }, + "jupyter": { + "class": "fsspec.implementations.jupyter.JupyterFileSystem", + "err": "Jupyter FS requires requests to be installed", + }, + "lakefs": { + "class": "lakefs_spec.LakeFSFileSystem", + "err": "Please install lakefs-spec to access LakeFSFileSystem", + }, + "libarchive": { + "class": "fsspec.implementations.libarchive.LibArchiveFileSystem", + "err": "LibArchive requires to be installed", + }, + "local": {"class": "fsspec.implementations.local.LocalFileSystem"}, + "memory": {"class": "fsspec.implementations.memory.MemoryFileSystem"}, + "oci": { + "class": "ocifs.OCIFileSystem", + "err": "Install ocifs to access OCI Object Storage", + }, + "ocilake": { + "class": "ocifs.OCIFileSystem", + "err": "Install ocifs to access OCI Data Lake", + }, + "oss": { + "class": "ossfs.OSSFileSystem", + "err": "Install ossfs to access Alibaba Object Storage System", + }, + "pyscript": { + "class": "pyscript_fsspec_client.client.PyscriptFileSystem", + "err": "This only runs in a pyscript context", + }, + "reference": {"class": "fsspec.implementations.reference.ReferenceFileSystem"}, + "root": { + "class": "fsspec_xrootd.XRootDFileSystem", + "err": ( + "Install fsspec-xrootd to access xrootd storage system. " + "Note: 'root' is the protocol name for xrootd storage systems, " + "not referring to root directories" + ), + }, + "s3": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"}, + "s3a": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"}, + "sftp": { + "class": "fsspec.implementations.sftp.SFTPFileSystem", + "err": 'SFTPFileSystem requires "paramiko" to be installed', + }, + "simplecache": {"class": "fsspec.implementations.cached.SimpleCacheFileSystem"}, + "smb": { + "class": "fsspec.implementations.smb.SMBFileSystem", + "err": 'SMB requires "smbprotocol" or "smbprotocol[kerberos]" installed', + }, + "ssh": { + "class": "fsspec.implementations.sftp.SFTPFileSystem", + "err": 'SFTPFileSystem requires "paramiko" to be installed', + }, + "tar": {"class": "fsspec.implementations.tar.TarFileSystem"}, + "tos": { + "class": "tosfs.TosFileSystem", + "err": "Install tosfs to access ByteDance volcano engine Tinder Object Storage", + }, + "tosfs": { + "class": "tosfs.TosFileSystem", + "err": "Install tosfs to access ByteDance volcano engine Tinder Object Storage", + }, + "wandb": {"class": "wandbfs.WandbFS", "err": "Install wandbfs to access wandb"}, + "webdav": { + "class": "webdav4.fsspec.WebdavFileSystem", + "err": "Install webdav4 to access WebDAV", + }, + "webhdfs": { + "class": "fsspec.implementations.webhdfs.WebHDFS", + "err": 'webHDFS access requires "requests" to be installed', + }, + "zip": {"class": "fsspec.implementations.zip.ZipFileSystem"}, +} + +assert list(known_implementations) == sorted(known_implementations), ( + "Not in alphabetical order" +) + + +def get_filesystem_class(protocol): + """Fetch named protocol implementation from the registry + + The dict ``known_implementations`` maps protocol names to the locations + of classes implementing the corresponding file-system. When used for the + first time, appropriate imports will happen and the class will be placed in + the registry. All subsequent calls will fetch directly from the registry. + + Some protocol implementations require additional dependencies, and so the + import may fail. In this case, the string in the "err" field of the + ``known_implementations`` will be given as the error message. + """ + if not protocol: + protocol = default + + if protocol not in registry: + if protocol not in known_implementations: + raise ValueError(f"Protocol not known: {protocol}") + bit = known_implementations[protocol] + try: + register_implementation(protocol, _import_class(bit["class"])) + except ImportError as e: + raise ImportError(bit.get("err")) from e + cls = registry[protocol] + if getattr(cls, "protocol", None) in ("abstract", None): + cls.protocol = protocol + + return cls + + +s3_msg = """Your installed version of s3fs is very old and known to cause +severe performance issues, see also https://github.com/dask/dask/issues/10276 + +To fix, you should specify a lower version bound on s3fs, or +update the current installation. +""" + + +def _import_class(fqp: str): + """Take a fully-qualified path and return the imported class or identifier. + + ``fqp`` is of the form "package.module.klass" or + "package.module:subobject.klass". + + Warnings + -------- + This can import arbitrary modules. Make sure you haven't installed any modules + that may execute malicious code at import time. + """ + if ":" in fqp: + mod, name = fqp.rsplit(":", 1) + else: + mod, name = fqp.rsplit(".", 1) + + is_s3 = mod == "s3fs" + mod = importlib.import_module(mod) + if is_s3 and mod.__version__.split(".") < ["0", "5"]: + warnings.warn(s3_msg) + for part in name.split("."): + mod = getattr(mod, part) + + if not isinstance(mod, type): + raise TypeError(f"{fqp} is not a class") + + return mod + + +def filesystem(protocol, **storage_options): + """Instantiate filesystems for given protocol and arguments + + ``storage_options`` are specific to the protocol being chosen, and are + passed directly to the class. + """ + if protocol == "arrow_hdfs": + warnings.warn( + "The 'arrow_hdfs' protocol has been deprecated and will be " + "removed in the future. Specify it as 'hdfs'.", + DeprecationWarning, + ) + + cls = get_filesystem_class(protocol) + return cls(**storage_options) + + +def available_protocols(): + """Return a list of the implemented protocols. + + Note that any given protocol may require extra packages to be importable. + """ + return list(known_implementations) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/spec.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/spec.py new file mode 100644 index 0000000000000000000000000000000000000000..94d286b04fb55b0140a003193ab2409532fc674d --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/spec.py @@ -0,0 +1,2342 @@ +from __future__ import annotations + +import io +import json +import logging +import os +import threading +import warnings +import weakref +from errno import ESPIPE +from glob import has_magic +from hashlib import sha256 +from typing import Any, ClassVar + +from .callbacks import DEFAULT_CALLBACK +from .config import apply_config, conf +from .dircache import DirCache +from .transaction import Transaction +from .utils import ( + _unstrip_protocol, + glob_translate, + isfilelike, + other_paths, + read_block, + stringify_path, + tokenize, +) + +logger = logging.getLogger("fsspec") + + +def make_instance(cls, args, kwargs): + return cls(*args, **kwargs) + + +FORK_AVAILABLE = hasattr(os, "register_at_fork") + + +if FORK_AVAILABLE: + _registered_classes = weakref.WeakSet() + + def _reset_instances_lock(): + for cls in _registered_classes: + cls._instantiation_lock = threading.RLock() + cls._cache.clear() + cls._pid = os.getpid() + + os.register_at_fork(after_in_child=_reset_instances_lock) + + +class _Cached(type): + """ + Metaclass for caching file system instances. + + Notes + ----- + Instances are cached according to + + * The values of the class attributes listed in `_extra_tokenize_attributes` + * The arguments passed to ``__init__``. + + This creates an additional reference to the filesystem, which prevents the + filesystem from being garbage collected when all *user* references go away. + A call to the :meth:`AbstractFileSystem.clear_instance_cache` must *also* + be made for a filesystem instance to be garbage collected. + """ + + def __init__(cls, *args, **kwargs): + super().__init__(*args, **kwargs) + + # Note: we intentionally create a reference here, to avoid garbage + # collecting instances when all other references are gone. To really + # delete a FileSystem, the cache must be cleared. + if conf.get("weakref_instance_cache"): # pragma: no cover + # debug option for analysing fork/spawn conditions + cls._cache = weakref.WeakValueDictionary() + else: + cls._cache = {} + cls._pid = os.getpid() + cls._instantiation_lock = threading.RLock() + + if FORK_AVAILABLE: + _registered_classes.add(cls) + + def _check_instance_cache(cls, token): + inst = cls._cache.get(token) + if inst is not None: + cls._latest = token + return inst + + def __call__(cls, *args, **kwargs): + kwargs = apply_config(cls, kwargs) + extra_tokens = tuple( + getattr(cls, attr, None) for attr in cls._extra_tokenize_attributes + ) + strip_tokenize_options = { + k: kwargs.pop(k) for k in cls._strip_tokenize_options if k in kwargs + } + pid = os.getpid() + + if getattr(cls, "async_impl", False) and not kwargs.get("asynchronous", False): + token = tokenize(cls, pid, *args, *extra_tokens, **kwargs) + else: + token = tokenize( + cls, pid, threading.get_ident(), *args, *extra_tokens, **kwargs + ) + skip = kwargs.pop("skip_instance_cache", False) + + if pid != cls._pid: + with cls._instantiation_lock: + if pid != cls._pid: + cls._cache.clear() + cls._pid = pid + + if not skip and cls.cachable: + inst = cls._check_instance_cache(token) + if inst is not None: + return inst + + with cls._instantiation_lock: + # protect against the race condition that a new instance was created + # and inserted into the cache since the initial check just above + inst = cls._check_instance_cache(token) + if inst is not None: + return inst + + obj = super().__call__(*args, **kwargs, **strip_tokenize_options) + # Setting _fs_token here causes some static linters to complain. + obj._fs_token_ = token + obj.storage_args = args + obj.storage_options = kwargs + if obj.async_impl and obj.mirror_sync_methods: + from .asyn import mirror_sync_methods + + mirror_sync_methods(obj) + + if cls.cachable and not skip: + with cls._instantiation_lock: + # another thread may have created the instance while we were calling + # super().__call__(), so we check again. + inst = cls._check_instance_cache(token) + if inst is not None: + return inst + + cls._latest = token + cls._cache[token] = obj + return obj + + +class AbstractFileSystem(metaclass=_Cached): + """ + An abstract super-class for pythonic file-systems + + Implementations are expected to be compatible with or, better, subclass + from here. + """ + + cachable = True # this class can be cached, instances reused + _cached = False + blocksize = 2**22 + sep = "/" + protocol: ClassVar[str | tuple[str, ...]] = "abstract" + _latest = None + async_impl = False + mirror_sync_methods = False + root_marker = "" # For some FSs, may require leading '/' or other character + transaction_type = Transaction + + #: Extra *class attributes* that should be considered when hashing. + _extra_tokenize_attributes = () + #: *storage options* that should not be considered when hashing. + _strip_tokenize_options = () + + # Set by _Cached metaclass + storage_args: tuple[Any, ...] + storage_options: dict[str, Any] + + def __init__(self, *args, **storage_options): + """Create and configure file-system instance + + Instances may be cachable, so if similar enough arguments are seen + a new instance is not required. The token attribute exists to allow + implementations to cache instances if they wish. + + A reasonable default should be provided if there are no arguments. + + Subclasses should call this method. + + Parameters + ---------- + use_listings_cache, listings_expiry_time, max_paths: + passed to ``DirCache``, if the implementation supports + directory listing caching. Pass use_listings_cache=False + to disable such caching. + skip_instance_cache: bool + If this is a cachable implementation, pass True here to force + creating a new instance even if a matching instance exists, and prevent + storing this instance. + asynchronous: bool + loop: asyncio-compatible IOLoop or None + """ + if self._cached: + # reusing instance, don't change + return + self._cached = True + self._intrans = False + self._transaction = None + self._invalidated_caches_in_transaction = [] + self.dircache = DirCache(**storage_options) + + if storage_options.pop("add_docs", None): + warnings.warn("add_docs is no longer supported.", FutureWarning) + + if storage_options.pop("add_aliases", None): + warnings.warn("add_aliases has been removed.", FutureWarning) + # This is set in _Cached + self._fs_token_ = None + + @property + def fsid(self): + """Persistent filesystem id that can be used to compare filesystems + across sessions. + """ + raise NotImplementedError + + @property + def _fs_token(self): + return self._fs_token_ + + def __dask_tokenize__(self): + return self._fs_token + + def __hash__(self): + return int(self._fs_token, 16) + + def __eq__(self, other): + return isinstance(other, type(self)) and self._fs_token == other._fs_token + + def __reduce__(self): + return make_instance, (type(self), self.storage_args, self.storage_options) + + @classmethod + def _strip_protocol(cls, path): + """Turn path from fully-qualified to file-system-specific + + May require FS-specific handling, e.g., for relative paths or links. + """ + if isinstance(path, list): + return [cls._strip_protocol(p) for p in path] + path = stringify_path(path) + protos = (cls.protocol,) if isinstance(cls.protocol, str) else cls.protocol + for protocol in protos: + if path.startswith(protocol + "://"): + path = path[len(protocol) + 3 :] + elif path.startswith(protocol + "::"): + path = path[len(protocol) + 2 :] + path = path.rstrip("/") + # use of root_marker to make minimum required path, e.g., "/" + return path or cls.root_marker + + def unstrip_protocol(self, name: str) -> str: + """Format FS-specific path to generic, including protocol""" + protos = (self.protocol,) if isinstance(self.protocol, str) else self.protocol + for protocol in protos: + if name.startswith(f"{protocol}://"): + return name + return f"{protos[0]}://{name}" + + @staticmethod + def _get_kwargs_from_urls(path): + """If kwargs can be encoded in the paths, extract them here + + This should happen before instantiation of the class; incoming paths + then should be amended to strip the options in methods. + + Examples may look like an sftp path "sftp://user@host:/my/path", where + the user and host should become kwargs and later get stripped. + """ + # by default, nothing happens + return {} + + @classmethod + def current(cls): + """Return the most recently instantiated FileSystem + + If no instance has been created, then create one with defaults + """ + inst = cls._cache.get(cls._latest) + if inst is not None: + return inst + return cls() + + @property + def transaction(self): + """A context within which files are committed together upon exit + + Requires the file class to implement `.commit()` and `.discard()` + for the normal and exception cases. + """ + if self._transaction is None: + self._transaction = self.transaction_type(self) + return self._transaction + + def start_transaction(self): + """Begin write transaction for deferring files, non-context version""" + self._intrans = True + self._transaction = self.transaction_type(self) + return self.transaction + + def end_transaction(self): + """Finish write transaction, non-context version""" + self.transaction.complete() + self._transaction = None + # The invalid cache must be cleared after the transaction is completed. + for path in self._invalidated_caches_in_transaction: + self.invalidate_cache(path) + self._invalidated_caches_in_transaction.clear() + + def invalidate_cache(self, path=None): + """ + Discard any cached directory information + + Parameters + ---------- + path: string or None + If None, clear all listings cached else listings at or under given + path. + """ + # Not necessary to implement invalidation mechanism, may have no cache. + # But if have, you should call this method of parent class from your + # subclass to ensure expiring caches after transacations correctly. + # See the implementation of FTPFileSystem in ftp.py + if self._intrans: + self._invalidated_caches_in_transaction.append(path) + + def mkdir(self, path, create_parents=True, **kwargs): + """ + Create directory entry at path + + For systems that don't have true directories, may create an for + this instance only and not touch the real filesystem + + Parameters + ---------- + path: str + location + create_parents: bool + if True, this is equivalent to ``makedirs`` + kwargs: + may be permissions, etc. + """ + pass # not necessary to implement, may not have directories + + def makedirs(self, path, exist_ok=False): + """Recursively make directories + + Creates directory at path and any intervening required directories. + Raises exception if, for instance, the path already exists but is a + file. + + Parameters + ---------- + path: str + leaf directory name + exist_ok: bool (False) + If False, will error if the target already exists + """ + pass # not necessary to implement, may not have directories + + def rmdir(self, path): + """Remove a directory, if empty""" + pass # not necessary to implement, may not have directories + + def ls(self, path, detail=True, **kwargs): + """List objects at path. + + This should include subdirectories and files at that location. The + difference between a file and a directory must be clear when details + are requested. + + The specific keys, or perhaps a FileInfo class, or similar, is TBD, + but must be consistent across implementations. + Must include: + + - full path to the entry (without protocol) + - size of the entry, in bytes. If the value cannot be determined, will + be ``None``. + - type of entry, "file", "directory" or other + + Additional information + may be present, appropriate to the file-system, e.g., generation, + checksum, etc. + + May use refresh=True|False to allow use of self._ls_from_cache to + check for a saved listing and avoid calling the backend. This would be + common where listing may be expensive. + + Parameters + ---------- + path: str + detail: bool + if True, gives a list of dictionaries, where each is the same as + the result of ``info(path)``. If False, gives a list of paths + (str). + kwargs: may have additional backend-specific options, such as version + information + + Returns + ------- + List of strings if detail is False, or list of directory information + dicts if detail is True. + """ + raise NotImplementedError + + def _ls_from_cache(self, path): + """Check cache for listing + + Returns listing, if found (may be empty list for a directly that exists + but contains nothing), None if not in cache. + """ + parent = self._parent(path) + try: + return self.dircache[path.rstrip("/")] + except KeyError: + pass + try: + files = [ + f + for f in self.dircache[parent] + if f["name"] == path + or (f["name"] == path.rstrip("/") and f["type"] == "directory") + ] + if len(files) == 0: + # parent dir was listed but did not contain this file + raise FileNotFoundError(path) + return files + except KeyError: + pass + + def walk(self, path, maxdepth=None, topdown=True, on_error="omit", **kwargs): + """Return all files under the given path. + + List all files, recursing into subdirectories; output is iterator-style, + like ``os.walk()``. For a simple list of files, ``find()`` is available. + + When topdown is True, the caller can modify the dirnames list in-place (perhaps + using del or slice assignment), and walk() will + only recurse into the subdirectories whose names remain in dirnames; + this can be used to prune the search, impose a specific order of visiting, + or even to inform walk() about directories the caller creates or renames before + it resumes walk() again. + Modifying dirnames when topdown is False has no effect. (see os.walk) + + Note that the "files" outputted will include anything that is not + a directory, such as links. + + Parameters + ---------- + path: str + Root to recurse into + maxdepth: int + Maximum recursion depth. None means limitless, but not recommended + on link-based file-systems. + topdown: bool (True) + Whether to walk the directory tree from the top downwards or from + the bottom upwards. + on_error: "omit", "raise", a callable + if omit (default), path with exception will simply be empty; + If raise, an underlying exception will be raised; + if callable, it will be called with a single OSError instance as argument + kwargs: passed to ``ls`` + """ + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + path = self._strip_protocol(path) + full_dirs = {} + dirs = {} + files = {} + + detail = kwargs.pop("detail", False) + try: + listing = self.ls(path, detail=True, **kwargs) + except (FileNotFoundError, OSError) as e: + if on_error == "raise": + raise + if callable(on_error): + on_error(e) + return + + for info in listing: + # each info name must be at least [path]/part , but here + # we check also for names like [path]/part/ + pathname = info["name"].rstrip("/") + name = pathname.rsplit("/", 1)[-1] + if info["type"] == "directory" and pathname != path: + # do not include "self" path + full_dirs[name] = pathname + dirs[name] = info + elif pathname == path: + # file-like with same name as give path + files[""] = info + else: + files[name] = info + + if not detail: + dirs = list(dirs) + files = list(files) + + if topdown: + # Yield before recursion if walking top down + yield path, dirs, files + + if maxdepth is not None: + maxdepth -= 1 + if maxdepth < 1: + if not topdown: + yield path, dirs, files + return + + for d in dirs: + yield from self.walk( + full_dirs[d], + maxdepth=maxdepth, + detail=detail, + topdown=topdown, + **kwargs, + ) + + if not topdown: + # Yield after recursion if walking bottom up + yield path, dirs, files + + def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs): + """List all files below path. + + Like posix ``find`` command without conditions + + Parameters + ---------- + path : str + maxdepth: int or None + If not None, the maximum number of levels to descend + withdirs: bool + Whether to include directory paths in the output. This is True + when used by glob, but users usually only want files. + kwargs are passed to ``ls``. + """ + # TODO: allow equivalent of -name parameter + path = self._strip_protocol(path) + out = {} + + # Add the root directory if withdirs is requested + # This is needed for posix glob compliance + if withdirs and path != "" and self.isdir(path): + out[path] = self.info(path) + + for _, dirs, files in self.walk(path, maxdepth, detail=True, **kwargs): + if withdirs: + files.update(dirs) + out.update({info["name"]: info for name, info in files.items()}) + if not out and self.isfile(path): + # walk works on directories, but find should also return [path] + # when path happens to be a file + out[path] = {} + names = sorted(out) + if not detail: + return names + else: + return {name: out[name] for name in names} + + def du(self, path, total=True, maxdepth=None, withdirs=False, **kwargs): + """Space used by files and optionally directories within a path + + Directory size does not include the size of its contents. + + Parameters + ---------- + path: str + total: bool + Whether to sum all the file sizes + maxdepth: int or None + Maximum number of directory levels to descend, None for unlimited. + withdirs: bool + Whether to include directory paths in the output. + kwargs: passed to ``find`` + + Returns + ------- + Dict of {path: size} if total=False, or int otherwise, where numbers + refer to bytes used. + """ + sizes = {} + if withdirs and self.isdir(path): + # Include top-level directory in output + info = self.info(path) + sizes[info["name"]] = info["size"] + for f in self.find(path, maxdepth=maxdepth, withdirs=withdirs, **kwargs): + info = self.info(f) + sizes[info["name"]] = info["size"] + if total: + return sum(sizes.values()) + else: + return sizes + + def glob(self, path, maxdepth=None, **kwargs): + """Find files by glob-matching. + + Pattern matching capabilities for finding files that match the given pattern. + + Parameters + ---------- + path: str + The glob pattern to match against + maxdepth: int or None + Maximum depth for ``'**'`` patterns. Applied on the first ``'**'`` found. + Must be at least 1 if provided. + kwargs: + Additional arguments passed to ``find`` (e.g., detail=True) + + Returns + ------- + List of matched paths, or dict of paths and their info if detail=True + + Notes + ----- + Supported patterns: + - '*': Matches any sequence of characters within a single directory level + - ``'**'``: Matches any number of directory levels (must be an entire path component) + - '?': Matches exactly one character + - '[abc]': Matches any character in the set + - '[a-z]': Matches any character in the range + - '[!abc]': Matches any character NOT in the set + + Special behaviors: + - If the path ends with '/', only folders are returned + - Consecutive '*' characters are compressed into a single '*' + - Empty set '[]' or negated empty negated set '[!]' never match anything + - Special characters in character classes are escaped properly + + Limitations: + - ``'**'`` must be a complete path component (e.g., ``'a/**/b'``, not ``'a**b'``) + - No brace expansion ('{a,b}.txt') + - No extended glob patterns ('+(pattern)', '!(pattern)') + """ + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + import re + + seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,) + ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash + path = self._strip_protocol(path) + append_slash_to_dirname = ends_with_sep or path.endswith( + tuple(sep + "**" for sep in seps) + ) + idx_star = path.find("*") if path.find("*") >= 0 else len(path) + idx_qmark = path.find("?") if path.find("?") >= 0 else len(path) + idx_brace = path.find("[") if path.find("[") >= 0 else len(path) + + min_idx = min(idx_star, idx_qmark, idx_brace) + + detail = kwargs.pop("detail", False) + withdirs = kwargs.pop("withdirs", True) + + if not has_magic(path): + if self.exists(path, **kwargs): + if not detail: + return [path] + else: + return {path: self.info(path, **kwargs)} + else: + if not detail: + return [] # glob of non-existent returns empty + else: + return {} + elif "/" in path[:min_idx]: + min_idx = path[:min_idx].rindex("/") + root = path[: min_idx + 1] + depth = path[min_idx + 1 :].count("/") + 1 + else: + root = "" + depth = path[min_idx + 1 :].count("/") + 1 + + if "**" in path: + if maxdepth is not None: + idx_double_stars = path.find("**") + depth_double_stars = path[idx_double_stars:].count("/") + 1 + depth = depth - depth_double_stars + maxdepth + else: + depth = None + + allpaths = self.find( + root, maxdepth=depth, withdirs=withdirs, detail=True, **kwargs + ) + + pattern = glob_translate(path + ("/" if ends_with_sep else "")) + pattern = re.compile(pattern) + + out = { + p: info + for p, info in sorted(allpaths.items()) + if pattern.match( + p + "/" + if append_slash_to_dirname and info["type"] == "directory" + else p + ) + } + + if detail: + return out + else: + return list(out) + + def exists(self, path, **kwargs): + """Is there a file at the given path""" + try: + self.info(path, **kwargs) + return True + except: # noqa: E722 + # any exception allowed bar FileNotFoundError? + return False + + def lexists(self, path, **kwargs): + """If there is a file at the given path (including + broken links)""" + return self.exists(path) + + def info(self, path, **kwargs): + """Give details of entry at path + + Returns a single dictionary, with exactly the same information as ``ls`` + would with ``detail=True``. + + The default implementation calls ls and could be overridden by a + shortcut. kwargs are passed on to ```ls()``. + + Some file systems might not be able to measure the file's size, in + which case, the returned dict will include ``'size': None``. + + Returns + ------- + dict with keys: name (full path in the FS), size (in bytes), type (file, + directory, or something else) and other FS-specific keys. + """ + path = self._strip_protocol(path) + out = self.ls(self._parent(path), detail=True, **kwargs) + out = [o for o in out if o["name"].rstrip("/") == path] + if out: + return out[0] + out = self.ls(path, detail=True, **kwargs) + path = path.rstrip("/") + out1 = [o for o in out if o["name"].rstrip("/") == path] + if len(out1) == 1: + if "size" not in out1[0]: + out1[0]["size"] = None + return out1[0] + elif len(out1) > 1 or out: + return {"name": path, "size": 0, "type": "directory"} + else: + raise FileNotFoundError(path) + + def checksum(self, path): + """Unique value for current version of file + + If the checksum is the same from one moment to another, the contents + are guaranteed to be the same. If the checksum changes, the contents + *might* have changed. + + This should normally be overridden; default will probably capture + creation/modification timestamp (which would be good) or maybe + access timestamp (which would be bad) + """ + return int(tokenize(self.info(path)), 16) + + def size(self, path): + """Size in bytes of file""" + return self.info(path).get("size", None) + + def sizes(self, paths): + """Size in bytes of each file in a list of paths""" + return [self.size(p) for p in paths] + + def isdir(self, path): + """Is this entry directory-like?""" + try: + return self.info(path)["type"] == "directory" + except OSError: + return False + + def isfile(self, path): + """Is this entry file-like?""" + try: + return self.info(path)["type"] == "file" + except: # noqa: E722 + return False + + def read_text(self, path, encoding=None, errors=None, newline=None, **kwargs): + """Get the contents of the file as a string. + + Parameters + ---------- + path: str + URL of file on this filesystems + encoding, errors, newline: same as `open`. + """ + with self.open( + path, + mode="r", + encoding=encoding, + errors=errors, + newline=newline, + **kwargs, + ) as f: + return f.read() + + def write_text( + self, path, value, encoding=None, errors=None, newline=None, **kwargs + ): + """Write the text to the given file. + + An existing file will be overwritten. + + Parameters + ---------- + path: str + URL of file on this filesystems + value: str + Text to write. + encoding, errors, newline: same as `open`. + """ + with self.open( + path, + mode="w", + encoding=encoding, + errors=errors, + newline=newline, + **kwargs, + ) as f: + return f.write(value) + + def cat_file(self, path, start=None, end=None, **kwargs): + """Get the content of a file + + Parameters + ---------- + path: URL of file on this filesystems + start, end: int + Bytes limits of the read. If negative, backwards from end, + like usual python slices. Either can be None for start or + end of file, respectively + kwargs: passed to ``open()``. + """ + # explicitly set buffering off? + with self.open(path, "rb", **kwargs) as f: + if start is not None: + if start >= 0: + f.seek(start) + else: + f.seek(max(0, f.size + start)) + if end is not None: + if end < 0: + end = f.size + end + return f.read(end - f.tell()) + return f.read() + + def pipe_file(self, path, value, mode="overwrite", **kwargs): + """Set the bytes of given file""" + if mode == "create" and self.exists(path): + # non-atomic but simple way; or could use "xb" in open(), which is likely + # not as well supported + raise FileExistsError + with self.open(path, "wb", **kwargs) as f: + f.write(value) + + def pipe(self, path, value=None, **kwargs): + """Put value into path + + (counterpart to ``cat``) + + Parameters + ---------- + path: string or dict(str, bytes) + If a string, a single remote location to put ``value`` bytes; if a dict, + a mapping of {path: bytesvalue}. + value: bytes, optional + If using a single path, these are the bytes to put there. Ignored if + ``path`` is a dict + """ + if isinstance(path, str): + self.pipe_file(self._strip_protocol(path), value, **kwargs) + elif isinstance(path, dict): + for k, v in path.items(): + self.pipe_file(self._strip_protocol(k), v, **kwargs) + else: + raise ValueError("path must be str or dict") + + def cat_ranges( + self, paths, starts, ends, max_gap=None, on_error="return", **kwargs + ): + """Get the contents of byte ranges from one or more files + + Parameters + ---------- + paths: list + A list of of filepaths on this filesystems + starts, ends: int or list + Bytes limits of the read. If using a single int, the same value will be + used to read all the specified files. + """ + if max_gap is not None: + raise NotImplementedError + if not isinstance(paths, list): + raise TypeError + if not isinstance(starts, list): + starts = [starts] * len(paths) + if not isinstance(ends, list): + ends = [ends] * len(paths) + if len(starts) != len(paths) or len(ends) != len(paths): + raise ValueError + out = [] + for p, s, e in zip(paths, starts, ends): + try: + out.append(self.cat_file(p, s, e, **kwargs)) + except Exception as e: + if on_error == "return": + out.append(e) + else: + raise + return out + + def cat(self, path, recursive=False, on_error="raise", **kwargs): + """Fetch (potentially multiple) paths' contents + + Parameters + ---------- + recursive: bool + If True, assume the path(s) are directories, and get all the + contained files + on_error : "raise", "omit", "return" + If raise, an underlying exception will be raised (converted to KeyError + if the type is in self.missing_exceptions); if omit, keys with exception + will simply not be included in the output; if "return", all keys are + included in the output, but the value will be bytes or an exception + instance. + kwargs: passed to cat_file + + Returns + ------- + dict of {path: contents} if there are multiple paths + or the path has been otherwise expanded + """ + paths = self.expand_path(path, recursive=recursive, **kwargs) + if ( + len(paths) > 1 + or isinstance(path, list) + or paths[0] != self._strip_protocol(path) + ): + out = {} + for path in paths: + try: + out[path] = self.cat_file(path, **kwargs) + except Exception as e: + if on_error == "raise": + raise + if on_error == "return": + out[path] = e + return out + else: + return self.cat_file(paths[0], **kwargs) + + def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, outfile=None, **kwargs): + """Copy single remote file to local""" + from .implementations.local import LocalFileSystem + + if isfilelike(lpath): + outfile = lpath + elif self.isdir(rpath): + os.makedirs(lpath, exist_ok=True) + return None + + fs = LocalFileSystem(auto_mkdir=True) + fs.makedirs(fs._parent(lpath), exist_ok=True) + + with self.open(rpath, "rb", **kwargs) as f1: + if outfile is None: + outfile = open(lpath, "wb") + + try: + callback.set_size(getattr(f1, "size", None)) + data = True + while data: + data = f1.read(self.blocksize) + segment_len = outfile.write(data) + if segment_len is None: + segment_len = len(data) + callback.relative_update(segment_len) + finally: + if not isfilelike(lpath): + outfile.close() + + def get( + self, + rpath, + lpath, + recursive=False, + callback=DEFAULT_CALLBACK, + maxdepth=None, + **kwargs, + ): + """Copy file(s) to local. + + Copies a specific file or tree of files (if recursive=True). If lpath + ends with a "/", it will be assumed to be a directory, and target files + will go within. Can submit a list of paths, which may be glob-patterns + and will be expanded. + + Calls get_file for each source. + """ + if isinstance(lpath, list) and isinstance(rpath, list): + # No need to expand paths when both source and destination + # are provided as lists + rpaths = rpath + lpaths = lpath + else: + from .implementations.local import ( + LocalFileSystem, + make_path_posix, + trailing_sep, + ) + + source_is_str = isinstance(rpath, str) + rpaths = self.expand_path( + rpath, recursive=recursive, maxdepth=maxdepth, **kwargs + ) + if source_is_str and (not recursive or maxdepth is not None): + # Non-recursive glob does not copy directories + rpaths = [p for p in rpaths if not (trailing_sep(p) or self.isdir(p))] + if not rpaths: + return + + if isinstance(lpath, str): + lpath = make_path_posix(lpath) + + source_is_file = len(rpaths) == 1 + dest_is_dir = isinstance(lpath, str) and ( + trailing_sep(lpath) or LocalFileSystem().isdir(lpath) + ) + + exists = source_is_str and ( + (has_magic(rpath) and source_is_file) + or (not has_magic(rpath) and dest_is_dir and not trailing_sep(rpath)) + ) + lpaths = other_paths( + rpaths, + lpath, + exists=exists, + flatten=not source_is_str, + ) + + callback.set_size(len(lpaths)) + for lpath, rpath in callback.wrap(zip(lpaths, rpaths)): + with callback.branched(rpath, lpath) as child: + self.get_file(rpath, lpath, callback=child, **kwargs) + + def put_file( + self, lpath, rpath, callback=DEFAULT_CALLBACK, mode="overwrite", **kwargs + ): + """Copy single file to remote""" + if mode == "create" and self.exists(rpath): + raise FileExistsError + if os.path.isdir(lpath): + self.makedirs(rpath, exist_ok=True) + return None + + with open(lpath, "rb") as f1: + size = f1.seek(0, 2) + callback.set_size(size) + f1.seek(0) + + self.mkdirs(self._parent(os.fspath(rpath)), exist_ok=True) + with self.open(rpath, "wb", **kwargs) as f2: + while f1.tell() < size: + data = f1.read(self.blocksize) + segment_len = f2.write(data) + if segment_len is None: + segment_len = len(data) + callback.relative_update(segment_len) + + def put( + self, + lpath, + rpath, + recursive=False, + callback=DEFAULT_CALLBACK, + maxdepth=None, + **kwargs, + ): + """Copy file(s) from local. + + Copies a specific file or tree of files (if recursive=True). If rpath + ends with a "/", it will be assumed to be a directory, and target files + will go within. + + Calls put_file for each source. + """ + if isinstance(lpath, list) and isinstance(rpath, list): + # No need to expand paths when both source and destination + # are provided as lists + rpaths = rpath + lpaths = lpath + else: + from .implementations.local import ( + LocalFileSystem, + make_path_posix, + trailing_sep, + ) + + source_is_str = isinstance(lpath, str) + if source_is_str: + lpath = make_path_posix(lpath) + fs = LocalFileSystem() + lpaths = fs.expand_path( + lpath, recursive=recursive, maxdepth=maxdepth, **kwargs + ) + if source_is_str and (not recursive or maxdepth is not None): + # Non-recursive glob does not copy directories + lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))] + if not lpaths: + return + + source_is_file = len(lpaths) == 1 + dest_is_dir = isinstance(rpath, str) and ( + trailing_sep(rpath) or self.isdir(rpath) + ) + + rpath = ( + self._strip_protocol(rpath) + if isinstance(rpath, str) + else [self._strip_protocol(p) for p in rpath] + ) + exists = source_is_str and ( + (has_magic(lpath) and source_is_file) + or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath)) + ) + rpaths = other_paths( + lpaths, + rpath, + exists=exists, + flatten=not source_is_str, + ) + + callback.set_size(len(rpaths)) + for lpath, rpath in callback.wrap(zip(lpaths, rpaths)): + with callback.branched(lpath, rpath) as child: + self.put_file(lpath, rpath, callback=child, **kwargs) + + def head(self, path, size=1024): + """Get the first ``size`` bytes from file""" + with self.open(path, "rb") as f: + return f.read(size) + + def tail(self, path, size=1024): + """Get the last ``size`` bytes from file""" + with self.open(path, "rb") as f: + f.seek(max(-size, -f.size), 2) + return f.read() + + def cp_file(self, path1, path2, **kwargs): + raise NotImplementedError + + def copy( + self, path1, path2, recursive=False, maxdepth=None, on_error=None, **kwargs + ): + """Copy within two locations in the filesystem + + on_error : "raise", "ignore" + If raise, any not-found exceptions will be raised; if ignore any + not-found exceptions will cause the path to be skipped; defaults to + raise unless recursive is true, where the default is ignore + """ + if on_error is None and recursive: + on_error = "ignore" + elif on_error is None: + on_error = "raise" + + if isinstance(path1, list) and isinstance(path2, list): + # No need to expand paths when both source and destination + # are provided as lists + paths1 = path1 + paths2 = path2 + else: + from .implementations.local import trailing_sep + + source_is_str = isinstance(path1, str) + paths1 = self.expand_path( + path1, recursive=recursive, maxdepth=maxdepth, **kwargs + ) + if source_is_str and (not recursive or maxdepth is not None): + # Non-recursive glob does not copy directories + paths1 = [p for p in paths1 if not (trailing_sep(p) or self.isdir(p))] + if not paths1: + return + + source_is_file = len(paths1) == 1 + dest_is_dir = isinstance(path2, str) and ( + trailing_sep(path2) or self.isdir(path2) + ) + + exists = source_is_str and ( + (has_magic(path1) and source_is_file) + or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1)) + ) + paths2 = other_paths( + paths1, + path2, + exists=exists, + flatten=not source_is_str, + ) + + for p1, p2 in zip(paths1, paths2): + try: + self.cp_file(p1, p2, **kwargs) + except FileNotFoundError: + if on_error == "raise": + raise + + def expand_path( + self, path, recursive=False, maxdepth=None, assume_literal=False, **kwargs + ): + """Turn one or more globs or directories into a list of all matching paths + to files or directories. + + kwargs are passed to ``glob`` or ``find``, which may in turn call ``ls`` + """ + + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + if isinstance(path, (str, os.PathLike)): + out = self.expand_path([path], recursive, maxdepth, **kwargs) + else: + out = set() + path = [self._strip_protocol(p) for p in path] + for p in path: + if not assume_literal and has_magic(p): + bit = set(self.glob(p, maxdepth=maxdepth, **kwargs)) + out |= bit + if recursive: + # glob call above expanded one depth so if maxdepth is defined + # then decrement it in expand_path call below. If it is zero + # after decrementing then avoid expand_path call. + if maxdepth is not None and maxdepth <= 1: + continue + out |= set( + self.expand_path( + list(bit), + recursive=recursive, + maxdepth=maxdepth - 1 if maxdepth is not None else None, + assume_literal=True, + **kwargs, + ) + ) + continue + elif recursive: + rec = set( + self.find( + p, maxdepth=maxdepth, withdirs=True, detail=False, **kwargs + ) + ) + out |= rec + if p not in out and (recursive is False or self.exists(p)): + # should only check once, for the root + out.add(p) + if not out: + raise FileNotFoundError(path) + return sorted(out) + + def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs): + """Move file(s) from one location to another""" + if path1 == path2: + logger.debug("%s mv: The paths are the same, so no files were moved.", self) + else: + # explicitly raise exception to prevent data corruption + self.copy( + path1, path2, recursive=recursive, maxdepth=maxdepth, on_error="raise" + ) + self.rm(path1, recursive=recursive) + + def rm_file(self, path): + """Delete a file""" + self._rm(path) + + def _rm(self, path): + """Delete one file""" + # this is the old name for the method, prefer rm_file + raise NotImplementedError + + def rm(self, path, recursive=False, maxdepth=None): + """Delete files. + + Parameters + ---------- + path: str or list of str + File(s) to delete. + recursive: bool + If file(s) are directories, recursively delete contents and then + also remove the directory + maxdepth: int or None + Depth to pass to walk for finding files to delete, if recursive. + If None, there will be no limit and infinite recursion may be + possible. + """ + path = self.expand_path(path, recursive=recursive, maxdepth=maxdepth) + for p in reversed(path): + self.rm_file(p) + + @classmethod + def _parent(cls, path): + path = cls._strip_protocol(path) + if "/" in path: + parent = path.rsplit("/", 1)[0].lstrip(cls.root_marker) + return cls.root_marker + parent + else: + return cls.root_marker + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + """Return raw bytes-mode file-like from the file-system""" + return AbstractBufferedFile( + self, + path, + mode, + block_size, + autocommit, + cache_options=cache_options, + **kwargs, + ) + + def open( + self, + path, + mode="rb", + block_size=None, + cache_options=None, + compression=None, + **kwargs, + ): + """ + Return a file-like object from the filesystem + + The resultant instance must function correctly in a context ``with`` + block. + + Parameters + ---------- + path: str + Target file + mode: str like 'rb', 'w' + See builtin ``open()`` + Mode "x" (exclusive write) may be implemented by the backend. Even if + it is, whether it is checked up front or on commit, and whether it is + atomic is implementation-dependent. + block_size: int + Some indication of buffering - this is a value in bytes + cache_options : dict, optional + Extra arguments to pass through to the cache. + compression: string or None + If given, open file using compression codec. Can either be a compression + name (a key in ``fsspec.compression.compr``) or "infer" to guess the + compression from the filename suffix. + encoding, errors, newline: passed on to TextIOWrapper for text mode + """ + import io + + path = self._strip_protocol(path) + if "b" not in mode: + mode = mode.replace("t", "") + "b" + + text_kwargs = { + k: kwargs.pop(k) + for k in ["encoding", "errors", "newline"] + if k in kwargs + } + return io.TextIOWrapper( + self.open( + path, + mode, + block_size=block_size, + cache_options=cache_options, + compression=compression, + **kwargs, + ), + **text_kwargs, + ) + else: + ac = kwargs.pop("autocommit", not self._intrans) + f = self._open( + path, + mode=mode, + block_size=block_size, + autocommit=ac, + cache_options=cache_options, + **kwargs, + ) + if compression is not None: + from fsspec.compression import compr + from fsspec.core import get_compression + + compression = get_compression(path, compression) + compress = compr[compression] + f = compress(f, mode=mode[0]) + + if not ac and "r" not in mode: + self.transaction.files.append(f) + return f + + def touch(self, path, truncate=True, **kwargs): + """Create empty file, or update timestamp + + Parameters + ---------- + path: str + file location + truncate: bool + If True, always set file size to 0; if False, update timestamp and + leave file unchanged, if backend allows this + """ + if truncate or not self.exists(path): + with self.open(path, "wb", **kwargs): + pass + else: + raise NotImplementedError # update timestamp, if possible + + def ukey(self, path): + """Hash of file properties, to tell if it has changed""" + return sha256(str(self.info(path)).encode()).hexdigest() + + def read_block(self, fn, offset, length, delimiter=None): + """Read a block of bytes from + + Starting at ``offset`` of the file, read ``length`` bytes. If + ``delimiter`` is set then we ensure that the read starts and stops at + delimiter boundaries that follow the locations ``offset`` and ``offset + + length``. If ``offset`` is zero then we start at zero. The + bytestring returned WILL include the end delimiter string. + + If offset+length is beyond the eof, reads to eof. + + Parameters + ---------- + fn: string + Path to filename + offset: int + Byte offset to start read + length: int + Number of bytes to read. If None, read to end. + delimiter: bytes (optional) + Ensure reading starts and stops at delimiter bytestring + + Examples + -------- + >>> fs.read_block('data/file.csv', 0, 13) # doctest: +SKIP + b'Alice, 100\\nBo' + >>> fs.read_block('data/file.csv', 0, 13, delimiter=b'\\n') # doctest: +SKIP + b'Alice, 100\\nBob, 200\\n' + + Use ``length=None`` to read to the end of the file. + >>> fs.read_block('data/file.csv', 0, None, delimiter=b'\\n') # doctest: +SKIP + b'Alice, 100\\nBob, 200\\nCharlie, 300' + + See Also + -------- + :func:`fsspec.utils.read_block` + """ + with self.open(fn, "rb") as f: + size = f.size + if length is None: + length = size + if size is not None and offset + length > size: + length = size - offset + return read_block(f, offset, length, delimiter) + + def to_json(self, *, include_password: bool = True) -> str: + """ + JSON representation of this filesystem instance. + + Parameters + ---------- + include_password: bool, default True + Whether to include the password (if any) in the output. + + Returns + ------- + JSON string with keys ``cls`` (the python location of this class), + protocol (text name of this class's protocol, first one in case of + multiple), ``args`` (positional args, usually empty), and all other + keyword arguments as their own keys. + + Warnings + -------- + Serialized filesystems may contain sensitive information which have been + passed to the constructor, such as passwords and tokens. Make sure you + store and send them in a secure environment! + """ + from .json import FilesystemJSONEncoder + + return json.dumps( + self, + cls=type( + "_FilesystemJSONEncoder", + (FilesystemJSONEncoder,), + {"include_password": include_password}, + ), + ) + + @staticmethod + def from_json(blob: str) -> AbstractFileSystem: + """ + Recreate a filesystem instance from JSON representation. + + See ``.to_json()`` for the expected structure of the input. + + Parameters + ---------- + blob: str + + Returns + ------- + file system instance, not necessarily of this particular class. + + Warnings + -------- + This can import arbitrary modules (as determined by the ``cls`` key). + Make sure you haven't installed any modules that may execute malicious code + at import time. + """ + from .json import FilesystemJSONDecoder + + return json.loads(blob, cls=FilesystemJSONDecoder) + + def to_dict(self, *, include_password: bool = True) -> dict[str, Any]: + """ + JSON-serializable dictionary representation of this filesystem instance. + + Parameters + ---------- + include_password: bool, default True + Whether to include the password (if any) in the output. + + Returns + ------- + Dictionary with keys ``cls`` (the python location of this class), + protocol (text name of this class's protocol, first one in case of + multiple), ``args`` (positional args, usually empty), and all other + keyword arguments as their own keys. + + Warnings + -------- + Serialized filesystems may contain sensitive information which have been + passed to the constructor, such as passwords and tokens. Make sure you + store and send them in a secure environment! + """ + from .json import FilesystemJSONEncoder + + json_encoder = FilesystemJSONEncoder() + + cls = type(self) + proto = self.protocol + + storage_options = dict(self.storage_options) + if not include_password: + storage_options.pop("password", None) + + return dict( + cls=f"{cls.__module__}:{cls.__name__}", + protocol=proto[0] if isinstance(proto, (tuple, list)) else proto, + args=json_encoder.make_serializable(self.storage_args), + **json_encoder.make_serializable(storage_options), + ) + + @staticmethod + def from_dict(dct: dict[str, Any]) -> AbstractFileSystem: + """ + Recreate a filesystem instance from dictionary representation. + + See ``.to_dict()`` for the expected structure of the input. + + Parameters + ---------- + dct: Dict[str, Any] + + Returns + ------- + file system instance, not necessarily of this particular class. + + Warnings + -------- + This can import arbitrary modules (as determined by the ``cls`` key). + Make sure you haven't installed any modules that may execute malicious code + at import time. + """ + from .json import FilesystemJSONDecoder + + json_decoder = FilesystemJSONDecoder() + + dct = dict(dct) # Defensive copy + + cls = FilesystemJSONDecoder.try_resolve_fs_cls(dct) + if cls is None: + raise ValueError("Not a serialized AbstractFileSystem") + + dct.pop("cls", None) + dct.pop("protocol", None) + + return cls( + *json_decoder.unmake_serializable(dct.pop("args", ())), + **json_decoder.unmake_serializable(dct), + ) + + def _get_pyarrow_filesystem(self): + """ + Make a version of the FS instance which will be acceptable to pyarrow + """ + # all instances already also derive from pyarrow + return self + + def get_mapper(self, root="", check=False, create=False, missing_exceptions=None): + """Create key/value store based on this file-system + + Makes a MutableMapping interface to the FS at the given root path. + See ``fsspec.mapping.FSMap`` for further details. + """ + from .mapping import FSMap + + return FSMap( + root, + self, + check=check, + create=create, + missing_exceptions=missing_exceptions, + ) + + @classmethod + def clear_instance_cache(cls): + """ + Clear the cache of filesystem instances. + + Notes + ----- + Unless overridden by setting the ``cachable`` class attribute to False, + the filesystem class stores a reference to newly created instances. This + prevents Python's normal rules around garbage collection from working, + since the instances refcount will not drop to zero until + ``clear_instance_cache`` is called. + """ + cls._cache.clear() + + def created(self, path): + """Return the created timestamp of a file as a datetime.datetime""" + raise NotImplementedError + + def modified(self, path): + """Return the modified timestamp of a file as a datetime.datetime""" + raise NotImplementedError + + def tree( + self, + path: str = "/", + recursion_limit: int = 2, + max_display: int = 25, + display_size: bool = False, + prefix: str = "", + is_last: bool = True, + first: bool = True, + indent_size: int = 4, + ) -> str: + """ + Return a tree-like structure of the filesystem starting from the given path as a string. + + Parameters + ---------- + path: Root path to start traversal from + recursion_limit: Maximum depth of directory traversal + max_display: Maximum number of items to display per directory + display_size: Whether to display file sizes + prefix: Current line prefix for visual tree structure + is_last: Whether current item is last in its level + first: Whether this is the first call (displays root path) + indent_size: Number of spaces by indent + + Returns + ------- + str: A string representing the tree structure. + + Example + ------- + >>> from fsspec import filesystem + + >>> fs = filesystem('ftp', host='test.rebex.net', user='demo', password='password') + >>> tree = fs.tree(display_size=True, recursion_limit=3, indent_size=8, max_display=10) + >>> print(tree) + """ + + def format_bytes(n: int) -> str: + """Format bytes as text.""" + for prefix, k in ( + ("P", 2**50), + ("T", 2**40), + ("G", 2**30), + ("M", 2**20), + ("k", 2**10), + ): + if n >= 0.9 * k: + return f"{n / k:.2f} {prefix}b" + return f"{n}B" + + result = [] + + if first: + result.append(path) + + if recursion_limit: + indent = " " * indent_size + contents = self.ls(path, detail=True) + contents.sort( + key=lambda x: (x.get("type") != "directory", x.get("name", "")) + ) + + if max_display is not None and len(contents) > max_display: + displayed_contents = contents[:max_display] + remaining_count = len(contents) - max_display + else: + displayed_contents = contents + remaining_count = 0 + + for i, item in enumerate(displayed_contents): + is_last_item = (i == len(displayed_contents) - 1) and ( + remaining_count == 0 + ) + + branch = ( + "└" + ("─" * (indent_size - 2)) + if is_last_item + else "├" + ("─" * (indent_size - 2)) + ) + branch += " " + new_prefix = prefix + ( + indent if is_last_item else "│" + " " * (indent_size - 1) + ) + + name = os.path.basename(item.get("name", "")) + + if display_size and item.get("type") == "directory": + sub_contents = self.ls(item.get("name", ""), detail=True) + num_files = sum( + 1 for sub_item in sub_contents if sub_item.get("type") == "file" + ) + num_folders = sum( + 1 + for sub_item in sub_contents + if sub_item.get("type") == "directory" + ) + + if num_files == 0 and num_folders == 0: + size = " (empty folder)" + elif num_files == 0: + size = f" ({num_folders} subfolder{'s' if num_folders > 1 else ''})" + elif num_folders == 0: + size = f" ({num_files} file{'s' if num_files > 1 else ''})" + else: + size = f" ({num_files} file{'s' if num_files > 1 else ''}, {num_folders} subfolder{'s' if num_folders > 1 else ''})" + elif display_size and item.get("type") == "file": + size = f" ({format_bytes(item.get('size', 0))})" + else: + size = "" + + result.append(f"{prefix}{branch}{name}{size}") + + if item.get("type") == "directory" and recursion_limit > 0: + result.append( + self.tree( + path=item.get("name", ""), + recursion_limit=recursion_limit - 1, + max_display=max_display, + display_size=display_size, + prefix=new_prefix, + is_last=is_last_item, + first=False, + indent_size=indent_size, + ) + ) + + if remaining_count > 0: + more_message = f"{remaining_count} more item(s) not displayed." + result.append( + f"{prefix}{'└' + ('─' * (indent_size - 2))} {more_message}" + ) + + return "\n".join(_ for _ in result if _) + + # ------------------------------------------------------------------------ + # Aliases + + def read_bytes(self, path, start=None, end=None, **kwargs): + """Alias of `AbstractFileSystem.cat_file`.""" + return self.cat_file(path, start=start, end=end, **kwargs) + + def write_bytes(self, path, value, **kwargs): + """Alias of `AbstractFileSystem.pipe_file`.""" + self.pipe_file(path, value, **kwargs) + + def makedir(self, path, create_parents=True, **kwargs): + """Alias of `AbstractFileSystem.mkdir`.""" + return self.mkdir(path, create_parents=create_parents, **kwargs) + + def mkdirs(self, path, exist_ok=False): + """Alias of `AbstractFileSystem.makedirs`.""" + return self.makedirs(path, exist_ok=exist_ok) + + def listdir(self, path, detail=True, **kwargs): + """Alias of `AbstractFileSystem.ls`.""" + return self.ls(path, detail=detail, **kwargs) + + def cp(self, path1, path2, **kwargs): + """Alias of `AbstractFileSystem.copy`.""" + return self.copy(path1, path2, **kwargs) + + def move(self, path1, path2, **kwargs): + """Alias of `AbstractFileSystem.mv`.""" + return self.mv(path1, path2, **kwargs) + + def stat(self, path, **kwargs): + """Alias of `AbstractFileSystem.info`.""" + return self.info(path, **kwargs) + + def disk_usage(self, path, total=True, maxdepth=None, **kwargs): + """Alias of `AbstractFileSystem.du`.""" + return self.du(path, total=total, maxdepth=maxdepth, **kwargs) + + def rename(self, path1, path2, **kwargs): + """Alias of `AbstractFileSystem.mv`.""" + return self.mv(path1, path2, **kwargs) + + def delete(self, path, recursive=False, maxdepth=None): + """Alias of `AbstractFileSystem.rm`.""" + return self.rm(path, recursive=recursive, maxdepth=maxdepth) + + def upload(self, lpath, rpath, recursive=False, **kwargs): + """Alias of `AbstractFileSystem.put`.""" + return self.put(lpath, rpath, recursive=recursive, **kwargs) + + def download(self, rpath, lpath, recursive=False, **kwargs): + """Alias of `AbstractFileSystem.get`.""" + return self.get(rpath, lpath, recursive=recursive, **kwargs) + + def sign(self, path, expiration=100, **kwargs): + """Create a signed URL representing the given path + + Some implementations allow temporary URLs to be generated, as a + way of delegating credentials. + + Parameters + ---------- + path : str + The path on the filesystem + expiration : int + Number of seconds to enable the URL for (if supported) + + Returns + ------- + URL : str + The signed URL + + Raises + ------ + NotImplementedError : if method is not implemented for a filesystem + """ + raise NotImplementedError("Sign is not implemented for this filesystem") + + def _isfilestore(self): + # Originally inherited from pyarrow DaskFileSystem. Keeping this + # here for backwards compatibility as long as pyarrow uses its + # legacy fsspec-compatible filesystems and thus accepts fsspec + # filesystems as well + return False + + +class AbstractBufferedFile(io.IOBase): + """Convenient class to derive from to provide buffering + + In the case that the backend does not provide a pythonic file-like object + already, this class contains much of the logic to build one. The only + methods that need to be overridden are ``_upload_chunk``, + ``_initiate_upload`` and ``_fetch_range``. + """ + + DEFAULT_BLOCK_SIZE = 5 * 2**20 + _details = None + + def __init__( + self, + fs, + path, + mode="rb", + block_size="default", + autocommit=True, + cache_type="readahead", + cache_options=None, + size=None, + **kwargs, + ): + """ + Template for files with buffered reading and writing + + Parameters + ---------- + fs: instance of FileSystem + path: str + location in file-system + mode: str + Normal file modes. Currently only 'wb', 'ab' or 'rb'. Some file + systems may be read-only, and some may not support append. + block_size: int + Buffer size for reading or writing, 'default' for class default + autocommit: bool + Whether to write to final destination; may only impact what + happens when file is being closed. + cache_type: {"readahead", "none", "mmap", "bytes"}, default "readahead" + Caching policy in read mode. See the definitions in ``core``. + cache_options : dict + Additional options passed to the constructor for the cache specified + by `cache_type`. + size: int + If given and in read mode, suppressed having to look up the file size + kwargs: + Gets stored as self.kwargs + """ + from .core import caches + + self.path = path + self.fs = fs + self.mode = mode + self.blocksize = ( + self.DEFAULT_BLOCK_SIZE if block_size in ["default", None] else block_size + ) + self.loc = 0 + self.autocommit = autocommit + self.end = None + self.start = None + self.closed = False + + if cache_options is None: + cache_options = {} + + if "trim" in kwargs: + warnings.warn( + "Passing 'trim' to control the cache behavior has been deprecated. " + "Specify it within the 'cache_options' argument instead.", + FutureWarning, + ) + cache_options["trim"] = kwargs.pop("trim") + + self.kwargs = kwargs + + if mode not in {"ab", "rb", "wb", "xb"}: + raise NotImplementedError("File mode not supported") + if mode == "rb": + if size is not None: + self.size = size + else: + self.size = self.details["size"] + self.cache = caches[cache_type]( + self.blocksize, self._fetch_range, self.size, **cache_options + ) + else: + self.buffer = io.BytesIO() + self.offset = None + self.forced = False + self.location = None + + @property + def details(self): + if self._details is None: + self._details = self.fs.info(self.path) + return self._details + + @details.setter + def details(self, value): + self._details = value + self.size = value["size"] + + @property + def full_name(self): + return _unstrip_protocol(self.path, self.fs) + + @property + def closed(self): + # get around this attr being read-only in IOBase + # use getattr here, since this can be called during del + return getattr(self, "_closed", True) + + @closed.setter + def closed(self, c): + self._closed = c + + def __hash__(self): + if "w" in self.mode: + return id(self) + else: + return int(tokenize(self.details), 16) + + def __eq__(self, other): + """Files are equal if they have the same checksum, only in read mode""" + if self is other: + return True + return ( + isinstance(other, type(self)) + and self.mode == "rb" + and other.mode == "rb" + and hash(self) == hash(other) + ) + + def commit(self): + """Move from temp to final destination""" + + def discard(self): + """Throw away temporary file""" + + def info(self): + """File information about this path""" + if self.readable(): + return self.details + else: + raise ValueError("Info not available while writing") + + def tell(self): + """Current file location""" + return self.loc + + def seek(self, loc, whence=0): + """Set current file location + + Parameters + ---------- + loc: int + byte location + whence: {0, 1, 2} + from start of file, current location or end of file, resp. + """ + loc = int(loc) + if not self.mode == "rb": + raise OSError(ESPIPE, "Seek only available in read mode") + if whence == 0: + nloc = loc + elif whence == 1: + nloc = self.loc + loc + elif whence == 2: + nloc = self.size + loc + else: + raise ValueError(f"invalid whence ({whence}, should be 0, 1 or 2)") + if nloc < 0: + raise ValueError("Seek before start of file") + self.loc = nloc + return self.loc + + def write(self, data): + """ + Write data to buffer. + + Buffer only sent on flush() or if buffer is greater than + or equal to blocksize. + + Parameters + ---------- + data: bytes + Set of bytes to be written. + """ + if not self.writable(): + raise ValueError("File not in write mode") + if self.closed: + raise ValueError("I/O operation on closed file.") + if self.forced: + raise ValueError("This file has been force-flushed, can only close") + out = self.buffer.write(data) + self.loc += out + if self.buffer.tell() >= self.blocksize: + self.flush() + return out + + def flush(self, force=False): + """ + Write buffered data to backend store. + + Writes the current buffer, if it is larger than the block-size, or if + the file is being closed. + + Parameters + ---------- + force: bool + When closing, write the last block even if it is smaller than + blocks are allowed to be. Disallows further writing to this file. + """ + + if self.closed: + raise ValueError("Flush on closed file") + if force and self.forced: + raise ValueError("Force flush cannot be called more than once") + if force: + self.forced = True + + if self.readable(): + # no-op to flush on read-mode + return + + if not force and self.buffer.tell() < self.blocksize: + # Defer write on small block + return + + if self.offset is None: + # Initialize a multipart upload + self.offset = 0 + try: + self._initiate_upload() + except Exception: + self.closed = True + raise + + if self._upload_chunk(final=force) is not False: + self.offset += self.buffer.seek(0, 2) + self.buffer = io.BytesIO() + + def _upload_chunk(self, final=False): + """Write one part of a multi-block file upload + + Parameters + ========== + final: bool + This is the last block, so should complete file, if + self.autocommit is True. + """ + # may not yet have been initialized, may need to call _initialize_upload + + def _initiate_upload(self): + """Create remote file/upload""" + pass + + def _fetch_range(self, start, end): + """Get the specified set of bytes from remote""" + return self.fs.cat_file(self.path, start=start, end=end) + + def read(self, length=-1): + """ + Return data from cache, or fetch pieces as necessary + + Parameters + ---------- + length: int (-1) + Number of bytes to read; if <0, all remaining bytes. + """ + length = -1 if length is None else int(length) + if self.mode != "rb": + raise ValueError("File not in read mode") + if length < 0: + length = self.size - self.loc + if self.closed: + raise ValueError("I/O operation on closed file.") + if length == 0: + # don't even bother calling fetch + return b"" + out = self.cache._fetch(self.loc, self.loc + length) + + logger.debug( + "%s read: %i - %i %s", + self, + self.loc, + self.loc + length, + self.cache._log_stats(), + ) + self.loc += len(out) + return out + + def readinto(self, b): + """mirrors builtin file's readinto method + + https://docs.python.org/3/library/io.html#io.RawIOBase.readinto + """ + out = memoryview(b).cast("B") + data = self.read(out.nbytes) + out[: len(data)] = data + return len(data) + + def readuntil(self, char=b"\n", blocks=None): + """Return data between current position and first occurrence of char + + char is included in the output, except if the end of the tile is + encountered first. + + Parameters + ---------- + char: bytes + Thing to find + blocks: None or int + How much to read in each go. Defaults to file blocksize - which may + mean a new read on every call. + """ + out = [] + while True: + start = self.tell() + part = self.read(blocks or self.blocksize) + if len(part) == 0: + break + found = part.find(char) + if found > -1: + out.append(part[: found + len(char)]) + self.seek(start + found + len(char)) + break + out.append(part) + return b"".join(out) + + def readline(self): + """Read until and including the first occurrence of newline character + + Note that, because of character encoding, this is not necessarily a + true line ending. + """ + return self.readuntil(b"\n") + + def __next__(self): + out = self.readline() + if out: + return out + raise StopIteration + + def __iter__(self): + return self + + def readlines(self): + """Return all data, split by the newline character, including the newline character""" + data = self.read() + lines = data.split(b"\n") + out = [l + b"\n" for l in lines[:-1]] + if data.endswith(b"\n"): + return out + else: + return out + [lines[-1]] + # return list(self) ??? + + def readinto1(self, b): + return self.readinto(b) + + def close(self): + """Close file + + Finalizes writes, discards cache + """ + if getattr(self, "_unclosable", False): + return + if self.closed: + return + try: + if self.mode == "rb": + cache = getattr(self, "cache", None) + if cache is not None: + close = getattr(cache, "close", None) + if callable(close): + close() + self.cache = None + else: + if not getattr(self, "forced", True): + self.flush(force=True) + + if self.fs is not None: + self.fs.invalidate_cache(self.path) + self.fs.invalidate_cache(self.fs._parent(self.path)) + finally: + self.closed = True + + def readable(self): + """Whether opened for reading""" + return "r" in self.mode and not self.closed + + def seekable(self): + """Whether is seekable (only in read mode)""" + return self.readable() + + def writable(self): + """Whether opened for writing""" + return self.mode in {"wb", "ab", "xb"} and not self.closed + + def __reduce__(self): + if self.mode != "rb": + raise RuntimeError("Pickling a writeable file is not supported") + + return reopen, ( + self.fs, + self.path, + self.mode, + self.blocksize, + self.loc, + self.size, + self.autocommit, + self.cache.name if self.cache else "none", + self.kwargs, + ) + + def __del__(self): + if not self.closed: + self.close() + + def __str__(self): + return f"" + + __repr__ = __str__ + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + +def reopen(fs, path, mode, blocksize, loc, size, autocommit, cache_type, kwargs): + file = fs.open( + path, + mode=mode, + block_size=blocksize, + autocommit=autocommit, + cache_type=cache_type, + size=size, + **kwargs, + ) + if loc > 0: + file.seek(loc) + return file diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f5414dfd4239b27fd9a7c3946cf82d889d45106e --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/__init__.py @@ -0,0 +1,290 @@ +import os +from hashlib import md5 + +import pytest + +from fsspec.implementations.local import LocalFileSystem +from fsspec.tests.abstract.copy import AbstractCopyTests # noqa: F401 +from fsspec.tests.abstract.get import AbstractGetTests # noqa: F401 +from fsspec.tests.abstract.open import AbstractOpenTests # noqa: F401 +from fsspec.tests.abstract.pipe import AbstractPipeTests # noqa: F401 +from fsspec.tests.abstract.put import AbstractPutTests # noqa: F401 + + +class BaseAbstractFixtures: + """ + Abstract base class containing fixtures that are used by but never need to + be overridden in derived filesystem-specific classes to run the abstract + tests on such filesystems. + """ + + @pytest.fixture + def fs_bulk_operations_scenario_0(self, fs, fs_join, fs_path): + """ + Scenario on remote filesystem that is used for many cp/get/put tests. + + Cleans up at the end of each test it which it is used. + """ + source = self._bulk_operations_scenario_0(fs, fs_join, fs_path) + yield source + fs.rm(source, recursive=True) + + @pytest.fixture + def fs_glob_edge_cases_files(self, fs, fs_join, fs_path): + """ + Scenario on remote filesystem that is used for glob edge cases cp/get/put tests. + + Cleans up at the end of each test it which it is used. + """ + source = self._glob_edge_cases_files(fs, fs_join, fs_path) + yield source + fs.rm(source, recursive=True) + + @pytest.fixture + def fs_dir_and_file_with_same_name_prefix(self, fs, fs_join, fs_path): + """ + Scenario on remote filesystem that is used to check cp/get/put on directory + and file with the same name prefixes. + + Cleans up at the end of each test it which it is used. + """ + source = self._dir_and_file_with_same_name_prefix(fs, fs_join, fs_path) + yield source + fs.rm(source, recursive=True) + + @pytest.fixture + def fs_10_files_with_hashed_names(self, fs, fs_join, fs_path): + """ + Scenario on remote filesystem that is used to check cp/get/put files order + when source and destination are lists. + + Cleans up at the end of each test it which it is used. + """ + source = self._10_files_with_hashed_names(fs, fs_join, fs_path) + yield source + fs.rm(source, recursive=True) + + @pytest.fixture + def fs_target(self, fs, fs_join, fs_path): + """ + Return name of remote directory that does not yet exist to copy into. + + Cleans up at the end of each test it which it is used. + """ + target = fs_join(fs_path, "target") + yield target + if fs.exists(target): + fs.rm(target, recursive=True) + + @pytest.fixture + def local_bulk_operations_scenario_0(self, local_fs, local_join, local_path): + """ + Scenario on local filesystem that is used for many cp/get/put tests. + + Cleans up at the end of each test it which it is used. + """ + source = self._bulk_operations_scenario_0(local_fs, local_join, local_path) + yield source + local_fs.rm(source, recursive=True) + + @pytest.fixture + def local_glob_edge_cases_files(self, local_fs, local_join, local_path): + """ + Scenario on local filesystem that is used for glob edge cases cp/get/put tests. + + Cleans up at the end of each test it which it is used. + """ + source = self._glob_edge_cases_files(local_fs, local_join, local_path) + yield source + local_fs.rm(source, recursive=True) + + @pytest.fixture + def local_dir_and_file_with_same_name_prefix( + self, local_fs, local_join, local_path + ): + """ + Scenario on local filesystem that is used to check cp/get/put on directory + and file with the same name prefixes. + + Cleans up at the end of each test it which it is used. + """ + source = self._dir_and_file_with_same_name_prefix( + local_fs, local_join, local_path + ) + yield source + local_fs.rm(source, recursive=True) + + @pytest.fixture + def local_10_files_with_hashed_names(self, local_fs, local_join, local_path): + """ + Scenario on local filesystem that is used to check cp/get/put files order + when source and destination are lists. + + Cleans up at the end of each test it which it is used. + """ + source = self._10_files_with_hashed_names(local_fs, local_join, local_path) + yield source + local_fs.rm(source, recursive=True) + + @pytest.fixture + def local_target(self, local_fs, local_join, local_path): + """ + Return name of local directory that does not yet exist to copy into. + + Cleans up at the end of each test it which it is used. + """ + target = local_join(local_path, "target") + yield target + if local_fs.exists(target): + local_fs.rm(target, recursive=True) + + def _glob_edge_cases_files(self, some_fs, some_join, some_path): + """ + Scenario that is used for glob edge cases cp/get/put tests. + Creates the following directory and file structure: + + 📁 source + ├── 📄 file1 + ├── 📄 file2 + ├── 📁 subdir0 + │ ├── 📄 subfile1 + │ ├── 📄 subfile2 + │ └── 📁 nesteddir + │ └── 📄 nestedfile + └── 📁 subdir1 + ├── 📄 subfile1 + ├── 📄 subfile2 + └── 📁 nesteddir + └── 📄 nestedfile + """ + source = some_join(some_path, "source") + some_fs.touch(some_join(source, "file1")) + some_fs.touch(some_join(source, "file2")) + + for subdir_idx in range(2): + subdir = some_join(source, f"subdir{subdir_idx}") + nesteddir = some_join(subdir, "nesteddir") + some_fs.makedirs(nesteddir) + some_fs.touch(some_join(subdir, "subfile1")) + some_fs.touch(some_join(subdir, "subfile2")) + some_fs.touch(some_join(nesteddir, "nestedfile")) + + return source + + def _bulk_operations_scenario_0(self, some_fs, some_join, some_path): + """ + Scenario that is used for many cp/get/put tests. Creates the following + directory and file structure: + + 📁 source + ├── 📄 file1 + ├── 📄 file2 + └── 📁 subdir + ├── 📄 subfile1 + ├── 📄 subfile2 + └── 📁 nesteddir + └── 📄 nestedfile + """ + source = some_join(some_path, "source") + subdir = some_join(source, "subdir") + nesteddir = some_join(subdir, "nesteddir") + some_fs.makedirs(nesteddir) + some_fs.touch(some_join(source, "file1")) + some_fs.touch(some_join(source, "file2")) + some_fs.touch(some_join(subdir, "subfile1")) + some_fs.touch(some_join(subdir, "subfile2")) + some_fs.touch(some_join(nesteddir, "nestedfile")) + return source + + def _dir_and_file_with_same_name_prefix(self, some_fs, some_join, some_path): + """ + Scenario that is used to check cp/get/put on directory and file with + the same name prefixes. Creates the following directory and file structure: + + 📁 source + ├── 📄 subdir.txt + └── 📁 subdir + └── 📄 subfile.txt + """ + source = some_join(some_path, "source") + subdir = some_join(source, "subdir") + file = some_join(source, "subdir.txt") + subfile = some_join(subdir, "subfile.txt") + some_fs.makedirs(subdir) + some_fs.touch(file) + some_fs.touch(subfile) + return source + + def _10_files_with_hashed_names(self, some_fs, some_join, some_path): + """ + Scenario that is used to check cp/get/put files order when source and + destination are lists. Creates the following directory and file structure: + + 📁 source + └── 📄 {hashed([0-9])}.txt + """ + source = some_join(some_path, "source") + for i in range(10): + hashed_i = md5(str(i).encode("utf-8")).hexdigest() + path = some_join(source, f"{hashed_i}.txt") + some_fs.pipe(path=path, value=f"{i}".encode()) + return source + + +class AbstractFixtures(BaseAbstractFixtures): + """ + Abstract base class containing fixtures that may be overridden in derived + filesystem-specific classes to run the abstract tests on such filesystems. + + For any particular filesystem some of these fixtures must be overridden, + such as ``fs`` and ``fs_path``, and others may be overridden if the + default functions here are not appropriate, such as ``fs_join``. + """ + + @pytest.fixture + def fs(self): + raise NotImplementedError("This function must be overridden in derived classes") + + @pytest.fixture + def fs_join(self): + """ + Return a function that joins its arguments together into a path. + + Most fsspec implementations join paths in a platform-dependent way, + but some will override this to always use a forward slash. + """ + return os.path.join + + @pytest.fixture + def fs_path(self): + raise NotImplementedError("This function must be overridden in derived classes") + + @pytest.fixture(scope="class") + @classmethod + def local_fs(cls): + # Maybe need an option for auto_mkdir=False? This is only relevant + # for certain implementations. + return LocalFileSystem(auto_mkdir=True) + + @pytest.fixture + def local_join(self): + """ + Return a function that joins its arguments together into a path, on + the local filesystem. + """ + return os.path.join + + @pytest.fixture + def local_path(self, tmpdir): + return tmpdir + + @pytest.fixture + def supports_empty_directories(self): + """ + Return whether this implementation supports empty directories. + """ + return True + + @pytest.fixture + def fs_sanitize_path(self): + return lambda x: x diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/common.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/common.py new file mode 100644 index 0000000000000000000000000000000000000000..22e7c4140404ab2a8928689721419cf05c2760b9 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/common.py @@ -0,0 +1,175 @@ +GLOB_EDGE_CASES_TESTS = { + "argnames": ("path", "recursive", "maxdepth", "expected"), + "argvalues": [ + ("fil?1", False, None, ["file1"]), + ("fil?1", True, None, ["file1"]), + ("file[1-2]", False, None, ["file1", "file2"]), + ("file[1-2]", True, None, ["file1", "file2"]), + ("*", False, None, ["file1", "file2"]), + ( + "*", + True, + None, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir0/nesteddir/nestedfile", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ("*", True, 1, ["file1", "file2"]), + ( + "*", + True, + 2, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir1/subfile1", + "subdir1/subfile2", + ], + ), + ("*1", False, None, ["file1"]), + ( + "*1", + True, + None, + [ + "file1", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ("*1", True, 2, ["file1", "subdir1/subfile1", "subdir1/subfile2"]), + ( + "**", + False, + None, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir0/nesteddir/nestedfile", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ( + "**", + True, + None, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir0/nesteddir/nestedfile", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ("**", True, 1, ["file1", "file2"]), + ( + "**", + True, + 2, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir0/nesteddir/nestedfile", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ( + "**", + False, + 2, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir1/subfile1", + "subdir1/subfile2", + ], + ), + ("**/*1", False, None, ["file1", "subdir0/subfile1", "subdir1/subfile1"]), + ( + "**/*1", + True, + None, + [ + "file1", + "subdir0/subfile1", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ("**/*1", True, 1, ["file1"]), + ( + "**/*1", + True, + 2, + ["file1", "subdir0/subfile1", "subdir1/subfile1", "subdir1/subfile2"], + ), + ("**/*1", False, 2, ["file1", "subdir0/subfile1", "subdir1/subfile1"]), + ("**/subdir0", False, None, []), + ("**/subdir0", True, None, ["subfile1", "subfile2", "nesteddir/nestedfile"]), + ("**/subdir0/nested*", False, 2, []), + ("**/subdir0/nested*", True, 2, ["nestedfile"]), + ("subdir[1-2]", False, None, []), + ("subdir[1-2]", True, None, ["subfile1", "subfile2", "nesteddir/nestedfile"]), + ("subdir[1-2]", True, 2, ["subfile1", "subfile2"]), + ("subdir[0-1]", False, None, []), + ( + "subdir[0-1]", + True, + None, + [ + "subdir0/subfile1", + "subdir0/subfile2", + "subdir0/nesteddir/nestedfile", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ( + "subdir[0-1]/*fil[e]*", + False, + None, + [ + "subdir0/subfile1", + "subdir0/subfile2", + "subdir1/subfile1", + "subdir1/subfile2", + ], + ), + ( + "subdir[0-1]/*fil[e]*", + True, + None, + [ + "subdir0/subfile1", + "subdir0/subfile2", + "subdir1/subfile1", + "subdir1/subfile2", + ], + ), + ], +} diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/copy.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/copy.py new file mode 100644 index 0000000000000000000000000000000000000000..e39e57e5f7d52bfda8ab5e2398b04cc2303630a0 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/copy.py @@ -0,0 +1,557 @@ +from hashlib import md5 +from itertools import product + +import pytest + +from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS + + +class AbstractCopyTests: + def test_copy_file_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 1a + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + fs.touch(fs_join(target, "dummy")) + assert fs.isdir(target) + + target_file2 = fs_join(target, "file2") + target_subfile1 = fs_join(target, "subfile1") + + # Copy from source directory + fs.cp(fs_join(source, "file2"), target) + assert fs.isfile(target_file2) + + # Copy from sub directory + fs.cp(fs_join(source, "subdir", "subfile1"), target) + assert fs.isfile(target_subfile1) + + # Remove copied files + fs.rm([target_file2, target_subfile1]) + assert not fs.exists(target_file2) + assert not fs.exists(target_subfile1) + + # Repeat with trailing slash on target + fs.cp(fs_join(source, "file2"), target + "/") + assert fs.isdir(target) + assert fs.isfile(target_file2) + + fs.cp(fs_join(source, "subdir", "subfile1"), target + "/") + assert fs.isfile(target_subfile1) + + def test_copy_file_to_new_directory( + self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target + ): + # Copy scenario 1b + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + fs.cp( + fs_join(source, "subdir", "subfile1"), fs_join(target, "newdir/") + ) # Note trailing slash + assert fs.isdir(target) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + + def test_copy_file_to_file_in_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 1c + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + fs.touch(fs_join(target, "dummy")) + assert fs.isdir(target) + + fs.cp(fs_join(source, "subdir", "subfile1"), fs_join(target, "newfile")) + assert fs.isfile(fs_join(target, "newfile")) + + def test_copy_file_to_file_in_new_directory( + self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target + ): + # Copy scenario 1d + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + fs.cp( + fs_join(source, "subdir", "subfile1"), fs_join(target, "newdir", "newfile") + ) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "newfile")) + + def test_copy_directory_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 1e + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = target + "/" if target_slash else target + + # Without recursive does nothing + fs.cp(s, t) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # With recursive + fs.cp(s, t, recursive=True) + if source_slash: + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert fs.isdir(fs_join(target, "nesteddir")) + assert fs.isfile(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + fs_join(target, "nesteddir"), + ], + recursive=True, + ) + else: + assert fs.isdir(fs_join(target, "subdir")) + assert fs.isfile(fs_join(target, "subdir", "subfile1")) + assert fs.isfile(fs_join(target, "subdir", "subfile2")) + assert fs.isdir(fs_join(target, "subdir", "nesteddir")) + assert fs.isfile(fs_join(target, "subdir", "nesteddir", "nestedfile")) + + fs.rm(fs_join(target, "subdir"), recursive=True) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # Limit recursive by maxdepth + fs.cp(s, t, recursive=True, maxdepth=1) + if source_slash: + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.exists(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + else: + assert fs.isdir(fs_join(target, "subdir")) + assert fs.isfile(fs_join(target, "subdir", "subfile1")) + assert fs.isfile(fs_join(target, "subdir", "subfile2")) + assert not fs.exists(fs_join(target, "subdir", "nesteddir")) + + fs.rm(fs_join(target, "subdir"), recursive=True) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_copy_directory_to_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 1f + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = fs_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive does nothing + fs.cp(s, t) + if supports_empty_directories: + assert fs.ls(target) == [] + else: + with pytest.raises(FileNotFoundError): + fs.ls(target) + + # With recursive + fs.cp(s, t, recursive=True) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert fs.isdir(fs_join(target, "newdir", "nesteddir")) + assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # Limit recursive by maxdepth + fs.cp(s, t, recursive=True, maxdepth=1) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + def test_copy_glob_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 1g + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + # Without recursive + fs.cp(fs_join(source, "subdir", "*"), t) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.isdir(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.cp(fs_join(source, "subdir", glob), t, recursive=recursive) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert fs.isdir(fs_join(target, "nesteddir")) + assert fs.isfile(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + fs_join(target, "nesteddir"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # Limit recursive by maxdepth + fs.cp( + fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1 + ) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.exists(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_copy_glob_to_new_directory( + self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target + ): + # Copy scenario 1h + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + for target_slash in [False, True]: + t = fs_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive + fs.cp(fs_join(source, "subdir", "*"), t) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.cp(fs_join(source, "subdir", glob), t, recursive=recursive) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert fs.isdir(fs_join(target, "newdir", "nesteddir")) + assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # Limit recursive by maxdepth + fs.cp( + fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1 + ) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + @pytest.mark.parametrize( + GLOB_EDGE_CASES_TESTS["argnames"], + GLOB_EDGE_CASES_TESTS["argvalues"], + ) + def test_copy_glob_edge_cases( + self, + path, + recursive, + maxdepth, + expected, + fs, + fs_join, + fs_glob_edge_cases_files, + fs_target, + fs_sanitize_path, + ): + # Copy scenario 1g + source = fs_glob_edge_cases_files + + target = fs_target + + for new_dir, target_slash in product([True, False], [True, False]): + fs.mkdir(target) + + t = fs_join(target, "newdir") if new_dir else target + t = t + "/" if target_slash else t + + fs.copy(fs_join(source, path), t, recursive=recursive, maxdepth=maxdepth) + + output = fs.find(target) + if new_dir: + prefixed_expected = [ + fs_sanitize_path(fs_join(target, "newdir", p)) for p in expected + ] + else: + prefixed_expected = [ + fs_sanitize_path(fs_join(target, p)) for p in expected + ] + assert sorted(output) == sorted(prefixed_expected) + + try: + fs.rm(target, recursive=True) + except FileNotFoundError: + pass + + def test_copy_list_of_files_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 2a + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + source_files = [ + fs_join(source, "file1"), + fs_join(source, "file2"), + fs_join(source, "subdir", "subfile1"), + ] + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + fs.cp(source_files, t) + assert fs.isfile(fs_join(target, "file1")) + assert fs.isfile(fs_join(target, "file2")) + assert fs.isfile(fs_join(target, "subfile1")) + + fs.rm( + [ + fs_join(target, "file1"), + fs_join(target, "file2"), + fs_join(target, "subfile1"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_copy_list_of_files_to_new_directory( + self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target + ): + # Copy scenario 2b + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + source_files = [ + fs_join(source, "file1"), + fs_join(source, "file2"), + fs_join(source, "subdir", "subfile1"), + ] + + fs.cp(source_files, fs_join(target, "newdir") + "/") # Note trailing slash + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "file1")) + assert fs.isfile(fs_join(target, "newdir", "file2")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + + def test_copy_two_files_new_directory( + self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target + ): + # This is a duplicate of test_copy_list_of_files_to_new_directory and + # can eventually be removed. + source = fs_bulk_operations_scenario_0 + + target = fs_target + assert not fs.exists(target) + fs.cp([fs_join(source, "file1"), fs_join(source, "file2")], target) + + assert fs.isdir(target) + assert fs.isfile(fs_join(target, "file1")) + assert fs.isfile(fs_join(target, "file2")) + + def test_copy_directory_without_files_with_same_name_prefix( + self, + fs, + fs_join, + fs_target, + fs_dir_and_file_with_same_name_prefix, + supports_empty_directories, + ): + # Create the test dirs + source = fs_dir_and_file_with_same_name_prefix + target = fs_target + + # Test without glob + fs.cp(fs_join(source, "subdir"), target, recursive=True) + + assert fs.isfile(fs_join(target, "subfile.txt")) + assert not fs.isfile(fs_join(target, "subdir.txt")) + + fs.rm([fs_join(target, "subfile.txt")]) + if supports_empty_directories: + assert fs.ls(target) == [] + else: + assert not fs.exists(target) + + # Test with glob + fs.cp(fs_join(source, "subdir*"), target, recursive=True) + + assert fs.isdir(fs_join(target, "subdir")) + assert fs.isfile(fs_join(target, "subdir", "subfile.txt")) + assert fs.isfile(fs_join(target, "subdir.txt")) + + def test_copy_with_source_and_destination_as_list( + self, fs, fs_target, fs_join, fs_10_files_with_hashed_names + ): + # Create the test dir + source = fs_10_files_with_hashed_names + target = fs_target + + # Create list of files for source and destination + source_files = [] + destination_files = [] + for i in range(10): + hashed_i = md5(str(i).encode("utf-8")).hexdigest() + source_files.append(fs_join(source, f"{hashed_i}.txt")) + destination_files.append(fs_join(target, f"{hashed_i}.txt")) + + # Copy and assert order was kept + fs.copy(path1=source_files, path2=destination_files) + + for i in range(10): + file_content = fs.cat(destination_files[i]).decode("utf-8") + assert file_content == str(i) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/get.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/get.py new file mode 100644 index 0000000000000000000000000000000000000000..851ab81ee581e74cac41c64c83ef0af75826d6b0 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/get.py @@ -0,0 +1,587 @@ +from hashlib import md5 +from itertools import product + +import pytest + +from fsspec.implementations.local import make_path_posix +from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS + + +class AbstractGetTests: + def test_get_file_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1a + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + assert local_fs.isdir(target) + + target_file2 = local_join(target, "file2") + target_subfile1 = local_join(target, "subfile1") + + # Copy from source directory + fs.get(fs_join(source, "file2"), target) + assert local_fs.isfile(target_file2) + + # Copy from sub directory + fs.get(fs_join(source, "subdir", "subfile1"), target) + assert local_fs.isfile(target_subfile1) + + # Remove copied files + local_fs.rm([target_file2, target_subfile1]) + assert not local_fs.exists(target_file2) + assert not local_fs.exists(target_subfile1) + + # Repeat with trailing slash on target + fs.get(fs_join(source, "file2"), target + "/") + assert local_fs.isdir(target) + assert local_fs.isfile(target_file2) + + fs.get(fs_join(source, "subdir", "subfile1"), target + "/") + assert local_fs.isfile(target_subfile1) + + def test_get_file_to_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1b + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + fs.get( + fs_join(source, "subdir", "subfile1"), local_join(target, "newdir/") + ) # Note trailing slash + + assert local_fs.isdir(target) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + + def test_get_file_to_file_in_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1c + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + fs.get(fs_join(source, "subdir", "subfile1"), local_join(target, "newfile")) + assert local_fs.isfile(local_join(target, "newfile")) + + def test_get_file_to_file_in_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1d + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + fs.get( + fs_join(source, "subdir", "subfile1"), + local_join(target, "newdir", "newfile"), + ) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "newfile")) + + def test_get_directory_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1e + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + assert local_fs.isdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = target + "/" if target_slash else target + + # Without recursive does nothing + fs.get(s, t) + assert local_fs.ls(target) == [] + + # With recursive + fs.get(s, t, recursive=True) + if source_slash: + assert local_fs.isfile(local_join(target, "subfile1")) + assert local_fs.isfile(local_join(target, "subfile2")) + assert local_fs.isdir(local_join(target, "nesteddir")) + assert local_fs.isfile(local_join(target, "nesteddir", "nestedfile")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm( + [ + local_join(target, "subfile1"), + local_join(target, "subfile2"), + local_join(target, "nesteddir"), + ], + recursive=True, + ) + else: + assert local_fs.isdir(local_join(target, "subdir")) + assert local_fs.isfile(local_join(target, "subdir", "subfile1")) + assert local_fs.isfile(local_join(target, "subdir", "subfile2")) + assert local_fs.isdir(local_join(target, "subdir", "nesteddir")) + assert local_fs.isfile( + local_join(target, "subdir", "nesteddir", "nestedfile") + ) + + local_fs.rm(local_join(target, "subdir"), recursive=True) + assert local_fs.ls(target) == [] + + # Limit recursive by maxdepth + fs.get(s, t, recursive=True, maxdepth=1) + if source_slash: + assert local_fs.isfile(local_join(target, "subfile1")) + assert local_fs.isfile(local_join(target, "subfile2")) + assert not local_fs.exists(local_join(target, "nesteddir")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm( + [ + local_join(target, "subfile1"), + local_join(target, "subfile2"), + ], + recursive=True, + ) + else: + assert local_fs.isdir(local_join(target, "subdir")) + assert local_fs.isfile(local_join(target, "subdir", "subfile1")) + assert local_fs.isfile(local_join(target, "subdir", "subfile2")) + assert not local_fs.exists(local_join(target, "subdir", "nesteddir")) + + local_fs.rm(local_join(target, "subdir"), recursive=True) + assert local_fs.ls(target) == [] + + def test_get_directory_to_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1f + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = local_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive does nothing + fs.get(s, t) + assert local_fs.ls(target) == [] + + # With recursive + fs.get(s, t, recursive=True) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + assert local_fs.isfile(local_join(target, "newdir", "subfile2")) + assert local_fs.isdir(local_join(target, "newdir", "nesteddir")) + assert local_fs.isfile( + local_join(target, "newdir", "nesteddir", "nestedfile") + ) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm(local_join(target, "newdir"), recursive=True) + assert local_fs.ls(target) == [] + + # Limit recursive by maxdepth + fs.get(s, t, recursive=True, maxdepth=1) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + assert local_fs.isfile(local_join(target, "newdir", "subfile2")) + assert not local_fs.exists(local_join(target, "newdir", "nesteddir")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm(local_join(target, "newdir"), recursive=True) + assert not local_fs.exists(local_join(target, "newdir")) + + def test_get_glob_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1g + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + # Without recursive + fs.get(fs_join(source, "subdir", "*"), t) + assert local_fs.isfile(local_join(target, "subfile1")) + assert local_fs.isfile(local_join(target, "subfile2")) + assert not local_fs.isdir(local_join(target, "nesteddir")) + assert not local_fs.exists(local_join(target, "nesteddir", "nestedfile")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm( + [ + local_join(target, "subfile1"), + local_join(target, "subfile2"), + ], + recursive=True, + ) + assert local_fs.ls(target) == [] + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.get(fs_join(source, "subdir", glob), t, recursive=recursive) + assert local_fs.isfile(local_join(target, "subfile1")) + assert local_fs.isfile(local_join(target, "subfile2")) + assert local_fs.isdir(local_join(target, "nesteddir")) + assert local_fs.isfile(local_join(target, "nesteddir", "nestedfile")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm( + [ + local_join(target, "subfile1"), + local_join(target, "subfile2"), + local_join(target, "nesteddir"), + ], + recursive=True, + ) + assert local_fs.ls(target) == [] + + # Limit recursive by maxdepth + fs.get( + fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1 + ) + assert local_fs.isfile(local_join(target, "subfile1")) + assert local_fs.isfile(local_join(target, "subfile2")) + assert not local_fs.exists(local_join(target, "nesteddir")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm( + [ + local_join(target, "subfile1"), + local_join(target, "subfile2"), + ], + recursive=True, + ) + assert local_fs.ls(target) == [] + + def test_get_glob_to_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1h + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + for target_slash in [False, True]: + t = fs_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive + fs.get(fs_join(source, "subdir", "*"), t) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + assert local_fs.isfile(local_join(target, "newdir", "subfile2")) + assert not local_fs.exists(local_join(target, "newdir", "nesteddir")) + assert not local_fs.exists( + local_join(target, "newdir", "nesteddir", "nestedfile") + ) + assert not local_fs.exists(local_join(target, "subdir")) + assert not local_fs.exists(local_join(target, "newdir", "subdir")) + + local_fs.rm(local_join(target, "newdir"), recursive=True) + assert local_fs.ls(target) == [] + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.get(fs_join(source, "subdir", glob), t, recursive=recursive) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + assert local_fs.isfile(local_join(target, "newdir", "subfile2")) + assert local_fs.isdir(local_join(target, "newdir", "nesteddir")) + assert local_fs.isfile( + local_join(target, "newdir", "nesteddir", "nestedfile") + ) + assert not local_fs.exists(local_join(target, "subdir")) + assert not local_fs.exists(local_join(target, "newdir", "subdir")) + + local_fs.rm(local_join(target, "newdir"), recursive=True) + assert not local_fs.exists(local_join(target, "newdir")) + + # Limit recursive by maxdepth + fs.get( + fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1 + ) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + assert local_fs.isfile(local_join(target, "newdir", "subfile2")) + assert not local_fs.exists(local_join(target, "newdir", "nesteddir")) + assert not local_fs.exists(local_join(target, "subdir")) + assert not local_fs.exists(local_join(target, "newdir", "subdir")) + + local_fs.rm(local_fs.ls(target, detail=False), recursive=True) + assert not local_fs.exists(local_join(target, "newdir")) + + @pytest.mark.parametrize( + GLOB_EDGE_CASES_TESTS["argnames"], + GLOB_EDGE_CASES_TESTS["argvalues"], + ) + def test_get_glob_edge_cases( + self, + path, + recursive, + maxdepth, + expected, + fs, + fs_join, + fs_glob_edge_cases_files, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1g + source = fs_glob_edge_cases_files + + target = local_target + + for new_dir, target_slash in product([True, False], [True, False]): + local_fs.mkdir(target) + + t = local_join(target, "newdir") if new_dir else target + t = t + "/" if target_slash else t + + fs.get(fs_join(source, path), t, recursive=recursive, maxdepth=maxdepth) + + output = local_fs.find(target) + if new_dir: + prefixed_expected = [ + make_path_posix(local_join(target, "newdir", p)) for p in expected + ] + else: + prefixed_expected = [ + make_path_posix(local_join(target, p)) for p in expected + ] + assert sorted(output) == sorted(prefixed_expected) + + try: + local_fs.rm(target, recursive=True) + except FileNotFoundError: + pass + + def test_get_list_of_files_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 2a + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + source_files = [ + fs_join(source, "file1"), + fs_join(source, "file2"), + fs_join(source, "subdir", "subfile1"), + ] + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + fs.get(source_files, t) + assert local_fs.isfile(local_join(target, "file1")) + assert local_fs.isfile(local_join(target, "file2")) + assert local_fs.isfile(local_join(target, "subfile1")) + + local_fs.rm( + [ + local_join(target, "file1"), + local_join(target, "file2"), + local_join(target, "subfile1"), + ], + recursive=True, + ) + assert local_fs.ls(target) == [] + + def test_get_list_of_files_to_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 2b + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + source_files = [ + fs_join(source, "file1"), + fs_join(source, "file2"), + fs_join(source, "subdir", "subfile1"), + ] + + fs.get(source_files, local_join(target, "newdir") + "/") # Note trailing slash + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "file1")) + assert local_fs.isfile(local_join(target, "newdir", "file2")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + + def test_get_directory_recursive( + self, fs, fs_join, fs_path, local_fs, local_join, local_target + ): + # https://github.com/fsspec/filesystem_spec/issues/1062 + # Recursive cp/get/put of source directory into non-existent target directory. + src = fs_join(fs_path, "src") + src_file = fs_join(src, "file") + fs.mkdir(src) + fs.touch(src_file) + + target = local_target + + # get without slash + assert not local_fs.exists(target) + for loop in range(2): + fs.get(src, target, recursive=True) + assert local_fs.isdir(target) + + if loop == 0: + assert local_fs.isfile(local_join(target, "file")) + assert not local_fs.exists(local_join(target, "src")) + else: + assert local_fs.isfile(local_join(target, "file")) + assert local_fs.isdir(local_join(target, "src")) + assert local_fs.isfile(local_join(target, "src", "file")) + + local_fs.rm(target, recursive=True) + + # get with slash + assert not local_fs.exists(target) + for loop in range(2): + fs.get(src + "/", target, recursive=True) + assert local_fs.isdir(target) + assert local_fs.isfile(local_join(target, "file")) + assert not local_fs.exists(local_join(target, "src")) + + def test_get_directory_without_files_with_same_name_prefix( + self, + fs, + fs_join, + local_fs, + local_join, + local_target, + fs_dir_and_file_with_same_name_prefix, + ): + # Create the test dirs + source = fs_dir_and_file_with_same_name_prefix + target = local_target + + # Test without glob + fs.get(fs_join(source, "subdir"), target, recursive=True) + + assert local_fs.isfile(local_join(target, "subfile.txt")) + assert not local_fs.isfile(local_join(target, "subdir.txt")) + + local_fs.rm([local_join(target, "subfile.txt")]) + assert local_fs.ls(target) == [] + + # Test with glob + fs.get(fs_join(source, "subdir*"), target, recursive=True) + + assert local_fs.isdir(local_join(target, "subdir")) + assert local_fs.isfile(local_join(target, "subdir", "subfile.txt")) + assert local_fs.isfile(local_join(target, "subdir.txt")) + + def test_get_with_source_and_destination_as_list( + self, + fs, + fs_join, + local_fs, + local_join, + local_target, + fs_10_files_with_hashed_names, + ): + # Create the test dir + source = fs_10_files_with_hashed_names + target = local_target + + # Create list of files for source and destination + source_files = [] + destination_files = [] + for i in range(10): + hashed_i = md5(str(i).encode("utf-8")).hexdigest() + source_files.append(fs_join(source, f"{hashed_i}.txt")) + destination_files.append( + make_path_posix(local_join(target, f"{hashed_i}.txt")) + ) + + # Copy and assert order was kept + fs.get(rpath=source_files, lpath=destination_files) + + for i in range(10): + file_content = local_fs.cat(destination_files[i]).decode("utf-8") + assert file_content == str(i) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/mv.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/mv.py new file mode 100644 index 0000000000000000000000000000000000000000..39f6caa3de815e024fa84de2acecc986c823ed29 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/mv.py @@ -0,0 +1,57 @@ +import os + +import pytest + +import fsspec + + +def test_move_raises_error_with_tmpdir(tmpdir): + # Create a file in the temporary directory + source = tmpdir.join("source_file.txt") + source.write("content") + + # Define a destination that simulates a protected or invalid path + destination = tmpdir.join("non_existent_directory/destination_file.txt") + + # Instantiate the filesystem (assuming the local file system interface) + fs = fsspec.filesystem("file") + + # Use the actual file paths as string + with pytest.raises(FileNotFoundError): + fs.mv(str(source), str(destination)) + + +@pytest.mark.parametrize("recursive", (True, False)) +def test_move_raises_error_with_tmpdir_permission(recursive, tmpdir): + # Create a file in the temporary directory + source = tmpdir.join("source_file.txt") + source.write("content") + + # Create a protected directory (non-writable) + protected_dir = tmpdir.mkdir("protected_directory") + protected_path = str(protected_dir) + + # Set the directory to read-only + if os.name == "nt": + os.system(f'icacls "{protected_path}" /deny Everyone:(W)') + else: + os.chmod(protected_path, 0o555) # Sets the directory to read-only + + # Define a destination inside the protected directory + destination = protected_dir.join("destination_file.txt") + + # Instantiate the filesystem (assuming the local file system interface) + fs = fsspec.filesystem("file") + + # Try to move the file to the read-only directory, expecting a permission error + with pytest.raises(PermissionError): + fs.mv(str(source), str(destination), recursive=recursive) + + # Assert the file was not created in the destination + assert not os.path.exists(destination) + + # Cleanup: Restore permissions so the directory can be cleaned up + if os.name == "nt": + os.system(f'icacls "{protected_path}" /remove:d Everyone') + else: + os.chmod(protected_path, 0o755) # Restore write permission for cleanup diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/open.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/open.py new file mode 100644 index 0000000000000000000000000000000000000000..bb75ea852276fb8d834345883813b8e27a0ae24c --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/open.py @@ -0,0 +1,11 @@ +import pytest + + +class AbstractOpenTests: + def test_open_exclusive(self, fs, fs_target): + with fs.open(fs_target, "wb") as f: + f.write(b"data") + with fs.open(fs_target, "rb") as f: + assert f.read() == b"data" + with pytest.raises(FileExistsError): + fs.open(fs_target, "xb") diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/pipe.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/pipe.py new file mode 100644 index 0000000000000000000000000000000000000000..8ecca96e9d23ff268a253c48269d5cca451ea270 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/pipe.py @@ -0,0 +1,11 @@ +import pytest + + +class AbstractPipeTests: + def test_pipe_exclusive(self, fs, fs_target): + fs.pipe_file(fs_target, b"data") + assert fs.cat_file(fs_target) == b"data" + with pytest.raises(FileExistsError): + fs.pipe_file(fs_target, b"data", mode="create") + fs.pipe_file(fs_target, b"new data", mode="overwrite") + assert fs.cat_file(fs_target) == b"new data" diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/put.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/put.py new file mode 100644 index 0000000000000000000000000000000000000000..9fc349977f0384d9fc86126498be5c6ad99a21d3 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/tests/abstract/put.py @@ -0,0 +1,591 @@ +from hashlib import md5 +from itertools import product + +import pytest + +from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS + + +class AbstractPutTests: + def test_put_file_to_existing_directory( + self, + fs, + fs_join, + fs_target, + local_join, + local_bulk_operations_scenario_0, + supports_empty_directories, + ): + # Copy scenario 1a + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + fs.touch(fs_join(target, "dummy")) + assert fs.isdir(target) + + target_file2 = fs_join(target, "file2") + target_subfile1 = fs_join(target, "subfile1") + + # Copy from source directory + fs.put(local_join(source, "file2"), target) + assert fs.isfile(target_file2) + + # Copy from sub directory + fs.put(local_join(source, "subdir", "subfile1"), target) + assert fs.isfile(target_subfile1) + + # Remove copied files + fs.rm([target_file2, target_subfile1]) + assert not fs.exists(target_file2) + assert not fs.exists(target_subfile1) + + # Repeat with trailing slash on target + fs.put(local_join(source, "file2"), target + "/") + assert fs.isdir(target) + assert fs.isfile(target_file2) + + fs.put(local_join(source, "subdir", "subfile1"), target + "/") + assert fs.isfile(target_subfile1) + + def test_put_file_to_new_directory( + self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0 + ): + # Copy scenario 1b + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + fs.put( + local_join(source, "subdir", "subfile1"), fs_join(target, "newdir/") + ) # Note trailing slash + assert fs.isdir(target) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + + def test_put_file_to_file_in_existing_directory( + self, + fs, + fs_join, + fs_target, + local_join, + supports_empty_directories, + local_bulk_operations_scenario_0, + ): + # Copy scenario 1c + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + fs.touch(fs_join(target, "dummy")) + assert fs.isdir(target) + + fs.put(local_join(source, "subdir", "subfile1"), fs_join(target, "newfile")) + assert fs.isfile(fs_join(target, "newfile")) + + def test_put_file_to_file_in_new_directory( + self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0 + ): + # Copy scenario 1d + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + fs.put( + local_join(source, "subdir", "subfile1"), + fs_join(target, "newdir", "newfile"), + ) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "newfile")) + + def test_put_directory_to_existing_directory( + self, + fs, + fs_join, + fs_target, + local_bulk_operations_scenario_0, + supports_empty_directories, + ): + # Copy scenario 1e + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = target + "/" if target_slash else target + + # Without recursive does nothing + fs.put(s, t) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # With recursive + fs.put(s, t, recursive=True) + if source_slash: + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert fs.isdir(fs_join(target, "nesteddir")) + assert fs.isfile(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + fs_join(target, "nesteddir"), + ], + recursive=True, + ) + else: + assert fs.isdir(fs_join(target, "subdir")) + assert fs.isfile(fs_join(target, "subdir", "subfile1")) + assert fs.isfile(fs_join(target, "subdir", "subfile2")) + assert fs.isdir(fs_join(target, "subdir", "nesteddir")) + assert fs.isfile(fs_join(target, "subdir", "nesteddir", "nestedfile")) + + fs.rm(fs_join(target, "subdir"), recursive=True) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # Limit recursive by maxdepth + fs.put(s, t, recursive=True, maxdepth=1) + if source_slash: + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.exists(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + else: + assert fs.isdir(fs_join(target, "subdir")) + assert fs.isfile(fs_join(target, "subdir", "subfile1")) + assert fs.isfile(fs_join(target, "subdir", "subfile2")) + assert not fs.exists(fs_join(target, "subdir", "nesteddir")) + + fs.rm(fs_join(target, "subdir"), recursive=True) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_put_directory_to_new_directory( + self, + fs, + fs_join, + fs_target, + local_bulk_operations_scenario_0, + supports_empty_directories, + ): + # Copy scenario 1f + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = fs_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive does nothing + fs.put(s, t) + if supports_empty_directories: + assert fs.ls(target) == [] + else: + with pytest.raises(FileNotFoundError): + fs.ls(target) + + # With recursive + fs.put(s, t, recursive=True) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert fs.isdir(fs_join(target, "newdir", "nesteddir")) + assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # Limit recursive by maxdepth + fs.put(s, t, recursive=True, maxdepth=1) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + def test_put_glob_to_existing_directory( + self, + fs, + fs_join, + fs_target, + local_join, + supports_empty_directories, + local_bulk_operations_scenario_0, + ): + # Copy scenario 1g + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + # Without recursive + fs.put(local_join(source, "subdir", "*"), t) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.isdir(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.put(local_join(source, "subdir", glob), t, recursive=recursive) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert fs.isdir(fs_join(target, "nesteddir")) + assert fs.isfile(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + fs_join(target, "nesteddir"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # Limit recursive by maxdepth + fs.put( + local_join(source, "subdir", glob), + t, + recursive=recursive, + maxdepth=1, + ) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.exists(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_put_glob_to_new_directory( + self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0 + ): + # Copy scenario 1h + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + for target_slash in [False, True]: + t = fs_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive + fs.put(local_join(source, "subdir", "*"), t) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.put(local_join(source, "subdir", glob), t, recursive=recursive) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert fs.isdir(fs_join(target, "newdir", "nesteddir")) + assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # Limit recursive by maxdepth + fs.put( + local_join(source, "subdir", glob), + t, + recursive=recursive, + maxdepth=1, + ) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + @pytest.mark.parametrize( + GLOB_EDGE_CASES_TESTS["argnames"], + GLOB_EDGE_CASES_TESTS["argvalues"], + ) + def test_put_glob_edge_cases( + self, + path, + recursive, + maxdepth, + expected, + fs, + fs_join, + fs_target, + local_glob_edge_cases_files, + local_join, + fs_sanitize_path, + ): + # Copy scenario 1g + source = local_glob_edge_cases_files + + target = fs_target + + for new_dir, target_slash in product([True, False], [True, False]): + fs.mkdir(target) + + t = fs_join(target, "newdir") if new_dir else target + t = t + "/" if target_slash else t + + fs.put(local_join(source, path), t, recursive=recursive, maxdepth=maxdepth) + + output = fs.find(target) + if new_dir: + prefixed_expected = [ + fs_sanitize_path(fs_join(target, "newdir", p)) for p in expected + ] + else: + prefixed_expected = [ + fs_sanitize_path(fs_join(target, p)) for p in expected + ] + assert sorted(output) == sorted(prefixed_expected) + + try: + fs.rm(target, recursive=True) + except FileNotFoundError: + pass + + def test_put_list_of_files_to_existing_directory( + self, + fs, + fs_join, + fs_target, + local_join, + local_bulk_operations_scenario_0, + supports_empty_directories, + ): + # Copy scenario 2a + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + source_files = [ + local_join(source, "file1"), + local_join(source, "file2"), + local_join(source, "subdir", "subfile1"), + ] + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + fs.put(source_files, t) + assert fs.isfile(fs_join(target, "file1")) + assert fs.isfile(fs_join(target, "file2")) + assert fs.isfile(fs_join(target, "subfile1")) + + fs.rm( + [ + fs_join(target, "file1"), + fs_join(target, "file2"), + fs_join(target, "subfile1"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_put_list_of_files_to_new_directory( + self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0 + ): + # Copy scenario 2b + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + source_files = [ + local_join(source, "file1"), + local_join(source, "file2"), + local_join(source, "subdir", "subfile1"), + ] + + fs.put(source_files, fs_join(target, "newdir") + "/") # Note trailing slash + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "file1")) + assert fs.isfile(fs_join(target, "newdir", "file2")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + + def test_put_directory_recursive( + self, fs, fs_join, fs_target, local_fs, local_join, local_path + ): + # https://github.com/fsspec/filesystem_spec/issues/1062 + # Recursive cp/get/put of source directory into non-existent target directory. + src = local_join(local_path, "src") + src_file = local_join(src, "file") + local_fs.mkdir(src) + local_fs.touch(src_file) + + target = fs_target + + # put without slash + assert not fs.exists(target) + for loop in range(2): + fs.put(src, target, recursive=True) + assert fs.isdir(target) + + if loop == 0: + assert fs.isfile(fs_join(target, "file")) + assert not fs.exists(fs_join(target, "src")) + else: + assert fs.isfile(fs_join(target, "file")) + assert fs.isdir(fs_join(target, "src")) + assert fs.isfile(fs_join(target, "src", "file")) + + fs.rm(target, recursive=True) + + # put with slash + assert not fs.exists(target) + for loop in range(2): + fs.put(src + "/", target, recursive=True) + assert fs.isdir(target) + assert fs.isfile(fs_join(target, "file")) + assert not fs.exists(fs_join(target, "src")) + + def test_put_directory_without_files_with_same_name_prefix( + self, + fs, + fs_join, + fs_target, + local_join, + local_dir_and_file_with_same_name_prefix, + supports_empty_directories, + ): + # Create the test dirs + source = local_dir_and_file_with_same_name_prefix + target = fs_target + + # Test without glob + fs.put(local_join(source, "subdir"), fs_target, recursive=True) + + assert fs.isfile(fs_join(fs_target, "subfile.txt")) + assert not fs.isfile(fs_join(fs_target, "subdir.txt")) + + fs.rm([fs_join(target, "subfile.txt")]) + if supports_empty_directories: + assert fs.ls(target) == [] + else: + assert not fs.exists(target) + + # Test with glob + fs.put(local_join(source, "subdir*"), fs_target, recursive=True) + + assert fs.isdir(fs_join(fs_target, "subdir")) + assert fs.isfile(fs_join(fs_target, "subdir", "subfile.txt")) + assert fs.isfile(fs_join(fs_target, "subdir.txt")) + + def test_copy_with_source_and_destination_as_list( + self, fs, fs_target, fs_join, local_join, local_10_files_with_hashed_names + ): + # Create the test dir + source = local_10_files_with_hashed_names + target = fs_target + + # Create list of files for source and destination + source_files = [] + destination_files = [] + for i in range(10): + hashed_i = md5(str(i).encode("utf-8")).hexdigest() + source_files.append(local_join(source, f"{hashed_i}.txt")) + destination_files.append(fs_join(target, f"{hashed_i}.txt")) + + # Copy and assert order was kept + fs.put(lpath=source_files, rpath=destination_files) + + for i in range(10): + file_content = fs.cat(destination_files[i]).decode("utf-8") + assert file_content == str(i) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/transaction.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/transaction.py new file mode 100644 index 0000000000000000000000000000000000000000..77293f63ecc5f611e19d849ef236d53e9c258efc --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/transaction.py @@ -0,0 +1,90 @@ +from collections import deque + + +class Transaction: + """Filesystem transaction write context + + Gathers files for deferred commit or discard, so that several write + operations can be finalized semi-atomically. This works by having this + instance as the ``.transaction`` attribute of the given filesystem + """ + + def __init__(self, fs, **kwargs): + """ + Parameters + ---------- + fs: FileSystem instance + """ + self.fs = fs + self.files = deque() + + def __enter__(self): + self.start() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """End transaction and commit, if exit is not due to exception""" + # only commit if there was no exception + self.complete(commit=exc_type is None) + if self.fs: + self.fs._intrans = False + self.fs._transaction = None + self.fs = None + + def start(self): + """Start a transaction on this FileSystem""" + self.files = deque() # clean up after previous failed completions + self.fs._intrans = True + + def complete(self, commit=True): + """Finish transaction: commit or discard all deferred files""" + while self.files: + f = self.files.popleft() + if commit: + f.commit() + else: + f.discard() + self.fs._intrans = False + self.fs._transaction = None + self.fs = None + + +class FileActor: + def __init__(self): + self.files = [] + + def commit(self): + for f in self.files: + f.commit() + self.files.clear() + + def discard(self): + for f in self.files: + f.discard() + self.files.clear() + + def append(self, f): + self.files.append(f) + + +class DaskTransaction(Transaction): + def __init__(self, fs): + """ + Parameters + ---------- + fs: FileSystem instance + """ + import distributed + + super().__init__(fs) + client = distributed.default_client() + self.files = client.submit(FileActor, actor=True).result() + + def complete(self, commit=True): + """Finish transaction: commit or discard all deferred files""" + if commit: + self.files.commit().result() + else: + self.files.discard().result() + self.fs._intrans = False + self.fs = None diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/utils.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6010cc1270f60417be1842702d1df435d460909c --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/fsspec/utils.py @@ -0,0 +1,757 @@ +from __future__ import annotations + +import contextlib +import logging +import math +import os +import re +import sys +import tempfile +from collections.abc import Callable, Iterable, Iterator, Sequence +from functools import partial +from hashlib import md5 +from importlib.metadata import version +from typing import IO, TYPE_CHECKING, Any, TypeVar +from urllib.parse import urlsplit + +if TYPE_CHECKING: + import pathlib + from typing import TypeGuard + + from fsspec.spec import AbstractFileSystem + + +DEFAULT_BLOCK_SIZE = 5 * 2**20 + +T = TypeVar("T") + + +def infer_storage_options( + urlpath: str, inherit_storage_options: dict[str, Any] | None = None +) -> dict[str, Any]: + """Infer storage options from URL path and merge it with existing storage + options. + + Parameters + ---------- + urlpath: str or unicode + Either local absolute file path or URL (hdfs://namenode:8020/file.csv) + inherit_storage_options: dict (optional) + Its contents will get merged with the inferred information from the + given path + + Returns + ------- + Storage options dict. + + Examples + -------- + >>> infer_storage_options('/mnt/datasets/test.csv') # doctest: +SKIP + {"protocol": "file", "path", "/mnt/datasets/test.csv"} + >>> infer_storage_options( + ... 'hdfs://username:pwd@node:123/mnt/datasets/test.csv?q=1', + ... inherit_storage_options={'extra': 'value'}, + ... ) # doctest: +SKIP + {"protocol": "hdfs", "username": "username", "password": "pwd", + "host": "node", "port": 123, "path": "/mnt/datasets/test.csv", + "url_query": "q=1", "extra": "value"} + """ + + # Discover Windows paths including disk name in this special case. + is_filesystem = re.match(r"^[a-zA-Z]:[\\/]", urlpath) + + # Discover URI according to RFC 3986: Scheme names consist of a + # sequence of characters beginning with a letter and followed by + # any combination of letters, digits, plus ("+"), period ("."), + # or hyphen ("-"). + # https://datatracker.ietf.org/doc/html/rfc3986#section-3.1 + is_uri = re.match(r"^[a-zA-Z0-9+.-]+://", urlpath) + + if is_filesystem or is_uri is None: + return {"protocol": "file", "path": urlpath} + + parsed_path = urlsplit(urlpath) + protocol = parsed_path.scheme or "file" + if parsed_path.fragment: + path = "#".join([parsed_path.path, parsed_path.fragment]) + else: + path = parsed_path.path + if protocol == "file": + # Special case parsing file protocol URL on Windows according to: + # https://msdn.microsoft.com/en-us/library/jj710207.aspx + windows_path = re.match(r"^/([a-zA-Z])[:|]([\\/].*)$", path) + if windows_path: + drive, path = windows_path.groups() + path = f"{drive}:{path}" + + if protocol in ["http", "https"]: + # for HTTP, we don't want to parse, as requests will anyway + return {"protocol": protocol, "path": urlpath} + + options: dict[str, Any] = {"protocol": protocol, "path": path} + + if parsed_path.netloc: + # Parse `hostname` from netloc manually because `parsed_path.hostname` + # lowercases the hostname which is not always desirable (e.g. in S3): + # https://github.com/dask/dask/issues/1417 + options["host"] = parsed_path.netloc.rsplit("@", 1)[-1].rsplit(":", 1)[0] + + if protocol in ("s3", "s3a", "gcs", "gs"): + options["path"] = options["host"] + options["path"] + else: + options["host"] = options["host"] + if parsed_path.port: + options["port"] = parsed_path.port + if parsed_path.username: + options["username"] = parsed_path.username + if parsed_path.password: + options["password"] = parsed_path.password + + if parsed_path.query: + options["url_query"] = parsed_path.query + if parsed_path.fragment: + options["url_fragment"] = parsed_path.fragment + + if inherit_storage_options: + update_storage_options(options, inherit_storage_options) + + return options + + +def update_storage_options( + options: dict[str, Any], inherited: dict[str, Any] | None = None +) -> None: + if not inherited: + inherited = {} + collisions = set(options) & set(inherited) + if collisions: + for collision in collisions: + if options.get(collision) != inherited.get(collision): + raise KeyError( + f"Collision between inferred and specified storage " + f"option:\n{collision}" + ) + options.update(inherited) + + +# Compression extensions registered via fsspec.compression.register_compression +compressions: dict[str, str] = {} + + +def infer_compression(filename: str) -> str | None: + """Infer compression, if available, from filename. + + Infer a named compression type, if registered and available, from filename + extension. This includes builtin (gz, bz2, zip) compressions, as well as + optional compressions. See fsspec.compression.register_compression. + """ + extension = os.path.splitext(filename)[-1].strip(".").lower() + if extension in compressions: + return compressions[extension] + return None + + +def build_name_function(max_int: float) -> Callable[[int], str]: + """Returns a function that receives a single integer + and returns it as a string padded by enough zero characters + to align with maximum possible integer + + >>> name_f = build_name_function(57) + + >>> name_f(7) + '07' + >>> name_f(31) + '31' + >>> build_name_function(1000)(42) + '0042' + >>> build_name_function(999)(42) + '042' + >>> build_name_function(0)(0) + '0' + """ + # handle corner cases max_int is 0 or exact power of 10 + max_int += 1e-8 + + pad_length = int(math.ceil(math.log10(max_int))) + + def name_function(i: int) -> str: + return str(i).zfill(pad_length) + + return name_function + + +def seek_delimiter(file: IO[bytes], delimiter: bytes, blocksize: int) -> bool: + r"""Seek current file to file start, file end, or byte after delimiter seq. + + Seeks file to next chunk delimiter, where chunks are defined on file start, + a delimiting sequence, and file end. Use file.tell() to see location afterwards. + Note that file start is a valid split, so must be at offset > 0 to seek for + delimiter. + + Parameters + ---------- + file: a file + delimiter: bytes + a delimiter like ``b'\n'`` or message sentinel, matching file .read() type + blocksize: int + Number of bytes to read from the file at once. + + + Returns + ------- + Returns True if a delimiter was found, False if at file start or end. + + """ + + if file.tell() == 0: + # beginning-of-file, return without seek + return False + + # Interface is for binary IO, with delimiter as bytes, but initialize last + # with result of file.read to preserve compatibility with text IO. + last: bytes | None = None + while True: + current = file.read(blocksize) + if not current: + # end-of-file without delimiter + return False + full = last + current if last else current + try: + if delimiter in full: + i = full.index(delimiter) + file.seek(file.tell() - (len(full) - i) + len(delimiter)) + return True + elif len(current) < blocksize: + # end-of-file without delimiter + return False + except (OSError, ValueError): + pass + last = full[-len(delimiter) :] + + +def read_block( + f: IO[bytes], + offset: int, + length: int | None, + delimiter: bytes | None = None, + split_before: bool = False, +) -> bytes: + """Read a block of bytes from a file + + Parameters + ---------- + f: File + Open file + offset: int + Byte offset to start read + length: int + Number of bytes to read, read through end of file if None + delimiter: bytes (optional) + Ensure reading starts and stops at delimiter bytestring + split_before: bool (optional) + Start/stop read *before* delimiter bytestring. + + + If using the ``delimiter=`` keyword argument we ensure that the read + starts and stops at delimiter boundaries that follow the locations + ``offset`` and ``offset + length``. If ``offset`` is zero then we + start at zero, regardless of delimiter. The bytestring returned WILL + include the terminating delimiter string. + + Examples + -------- + + >>> from io import BytesIO # doctest: +SKIP + >>> f = BytesIO(b'Alice, 100\\nBob, 200\\nCharlie, 300') # doctest: +SKIP + >>> read_block(f, 0, 13) # doctest: +SKIP + b'Alice, 100\\nBo' + + >>> read_block(f, 0, 13, delimiter=b'\\n') # doctest: +SKIP + b'Alice, 100\\nBob, 200\\n' + + >>> read_block(f, 10, 10, delimiter=b'\\n') # doctest: +SKIP + b'Bob, 200\\nCharlie, 300' + """ + if delimiter: + f.seek(offset) + found_start_delim = seek_delimiter(f, delimiter, 2**16) + if length is None: + return f.read() + start = f.tell() + length -= start - offset + + f.seek(start + length) + found_end_delim = seek_delimiter(f, delimiter, 2**16) + end = f.tell() + + # Adjust split location to before delimiter if seek found the + # delimiter sequence, not start or end of file. + if found_start_delim and split_before: + start -= len(delimiter) + + if found_end_delim and split_before: + end -= len(delimiter) + + offset = start + length = end - start + + f.seek(offset) + + # TODO: allow length to be None and read to the end of the file? + assert length is not None + b = f.read(length) + return b + + +def tokenize(*args: Any, **kwargs: Any) -> str: + """Deterministic token + + (modified from dask.base) + + >>> tokenize([1, 2, '3']) + '9d71491b50023b06fc76928e6eddb952' + + >>> tokenize('Hello') == tokenize('Hello') + True + """ + if kwargs: + args += (kwargs,) + try: + h = md5(str(args).encode()) + except ValueError: + # FIPS systems: https://github.com/fsspec/filesystem_spec/issues/380 + h = md5(str(args).encode(), usedforsecurity=False) + return h.hexdigest() + + +def stringify_path(filepath: str | os.PathLike[str] | pathlib.Path) -> str: + """Attempt to convert a path-like object to a string. + + Parameters + ---------- + filepath: object to be converted + + Returns + ------- + filepath_str: maybe a string version of the object + + Notes + ----- + Objects supporting the fspath protocol are coerced according to its + __fspath__ method. + + For backwards compatibility with older Python version, pathlib.Path + objects are specially coerced. + + Any other object is passed through unchanged, which includes bytes, + strings, buffers, or anything else that's not even path-like. + """ + if isinstance(filepath, str): + return filepath + elif hasattr(filepath, "__fspath__"): + return filepath.__fspath__() + elif hasattr(filepath, "path"): + return filepath.path + else: + return filepath # type: ignore[return-value] + + +def make_instance( + cls: Callable[..., T], args: Sequence[Any], kwargs: dict[str, Any] +) -> T: + inst = cls(*args, **kwargs) + inst._determine_worker() # type: ignore[attr-defined] + return inst + + +def common_prefix(paths: Iterable[str]) -> str: + """For a list of paths, find the shortest prefix common to all""" + parts = [p.split("/") for p in paths] + lmax = min(len(p) for p in parts) + end = 0 + for i in range(lmax): + end = all(p[i] == parts[0][i] for p in parts) + if not end: + break + i += end + return "/".join(parts[0][:i]) + + +def other_paths( + paths: list[str], + path2: str | list[str], + exists: bool = False, + flatten: bool = False, +) -> list[str]: + """In bulk file operations, construct a new file tree from a list of files + + Parameters + ---------- + paths: list of str + The input file tree + path2: str or list of str + Root to construct the new list in. If this is already a list of str, we just + assert it has the right number of elements. + exists: bool (optional) + For a str destination, it is already exists (and is a dir), files should + end up inside. + flatten: bool (optional) + Whether to flatten the input directory tree structure so that the output files + are in the same directory. + + Returns + ------- + list of str + """ + + if isinstance(path2, str): + path2 = path2.rstrip("/") + + if flatten: + path2 = ["/".join((path2, p.split("/")[-1])) for p in paths] + else: + cp = common_prefix(paths) + if exists: + cp = cp.rsplit("/", 1)[0] + if not cp and all(not s.startswith("/") for s in paths): + path2 = ["/".join([path2, p]) for p in paths] + else: + path2 = [p.replace(cp, path2, 1) for p in paths] + else: + assert len(paths) == len(path2) + return path2 + + +def is_exception(obj: Any) -> bool: + return isinstance(obj, BaseException) + + +def isfilelike(f: Any) -> TypeGuard[IO[bytes]]: + return all(hasattr(f, attr) for attr in ["read", "close", "tell"]) + + +def get_protocol(url: str) -> str: + url = stringify_path(url) + parts = re.split(r"(\:\:|\://)", url, maxsplit=1) + if len(parts) > 1: + return parts[0] + return "file" + + +def get_file_extension(url: str) -> str: + url = stringify_path(url) + # Only consider the final path component: a "." in a parent directory name + # (e.g. "/path/to.dir/file") is not the file's extension. + ext_parts = url.rsplit("/", 1)[-1].rsplit(".", 1) + if len(ext_parts) > 1: + return ext_parts[-1] + return "" + + +def can_be_local(path: str) -> bool: + """Can the given URL be used with open_local?""" + from fsspec import get_filesystem_class + + try: + return getattr(get_filesystem_class(get_protocol(path)), "local_file", False) + except (ValueError, ImportError): + # not in registry or import failed + return False + + +def get_package_version_without_import(name: str) -> str | None: + """For given package name, try to find the version without importing it + + Import and package.__version__ is still the backup here, so an import + *might* happen. + + Returns either the version string, or None if the package + or the version was not readily found. + """ + if name in sys.modules: + mod = sys.modules[name] + if hasattr(mod, "__version__"): + return mod.__version__ + try: + return version(name) + except: # noqa: E722 + pass + try: + import importlib + + mod = importlib.import_module(name) + return mod.__version__ + except (ImportError, AttributeError): + return None + + +def setup_logging( + logger: logging.Logger | None = None, + logger_name: str | None = None, + level: str = "DEBUG", + clear: bool = True, +) -> logging.Logger: + if logger is None and logger_name is None: + raise ValueError("Provide either logger object or logger name") + logger = logger or logging.getLogger(logger_name) + handle = logging.StreamHandler() + formatter = logging.Formatter( + "%(asctime)s - %(name)s - %(levelname)s - %(funcName)s -- %(message)s" + ) + handle.setFormatter(formatter) + if clear: + logger.handlers.clear() + logger.addHandler(handle) + logger.setLevel(level) + return logger + + +def _unstrip_protocol(name: str, fs: AbstractFileSystem) -> str: + return fs.unstrip_protocol(name) + + +def mirror_from( + origin_name: str, methods: Iterable[str] +) -> Callable[[type[T]], type[T]]: + """Mirror attributes and methods from the given + origin_name attribute of the instance to the + decorated class""" + + def origin_getter(method: str, self: Any) -> Any: + origin = getattr(self, origin_name) + return getattr(origin, method) + + def wrapper(cls: type[T]) -> type[T]: + for method in methods: + wrapped_method = partial(origin_getter, method) + setattr(cls, method, property(wrapped_method)) + return cls + + return wrapper + + +@contextlib.contextmanager +def nullcontext(obj: T) -> Iterator[T]: + yield obj + + +def merge_offset_ranges( + paths: list[str], + starts: list[int] | int, + ends: list[int] | int, + max_gap: int = 0, + max_block: int | None = None, + sort: bool = True, +) -> tuple[list[str], list[int], list[int]]: + """Merge adjacent byte-offset ranges when the inter-range + gap is <= `max_gap`, and when the merged byte range does not + exceed `max_block` (if specified). By default, this function + will re-order the input paths and byte ranges to ensure sorted + order. If the user can guarantee that the inputs are already + sorted, passing `sort=False` will skip the re-ordering. + """ + # Check input + if not isinstance(paths, list): + raise TypeError + if not isinstance(starts, list): + starts = [starts] * len(paths) + if not isinstance(ends, list): + ends = [ends] * len(paths) + if len(starts) != len(paths) or len(ends) != len(paths): + raise ValueError + + # Early Return + if len(starts) <= 1: + return paths, starts, ends + + starts = [s or 0 for s in starts] + # Sort by paths and then ranges if `sort=True` + if sort: + paths, starts, ends = ( + list(v) + for v in zip( + *sorted( + zip(paths, starts, ends), + ) + ) + ) + remove = [] + for i, (path, start, end) in enumerate(zip(paths, starts, ends)): + if any( + e is not None and p == path and start >= s and end <= e and i != i2 + for i2, (p, s, e) in enumerate(zip(paths, starts, ends)) + ): + remove.append(i) + paths = [p for i, p in enumerate(paths) if i not in remove] + starts = [s for i, s in enumerate(starts) if i not in remove] + ends = [e for i, e in enumerate(ends) if i not in remove] + + if paths: + # Loop through the coupled `paths`, `starts`, and + # `ends`, and merge adjacent blocks when appropriate + new_paths = paths[:1] + new_starts = starts[:1] + new_ends = ends[:1] + for i in range(1, len(paths)): + if paths[i] == paths[i - 1] and new_ends[-1] is None: + continue + elif ( + paths[i] != paths[i - 1] + or ((starts[i] - new_ends[-1]) > max_gap) + or (max_block is not None and (ends[i] - new_starts[-1]) > max_block) + ): + # Cannot merge with previous block. + # Add new `paths`, `starts`, and `ends` elements + new_paths.append(paths[i]) + new_starts.append(starts[i]) + new_ends.append(ends[i]) + else: + # Merge with the previous block by updating the + # last element of `ends` + new_ends[-1] = ends[i] + return new_paths, new_starts, new_ends + + # `paths` is empty. Just return input lists + return paths, starts, ends + + +def file_size(filelike: IO[bytes]) -> int: + """Find length of any open read-mode file-like""" + pos = filelike.tell() + try: + return filelike.seek(0, 2) + finally: + filelike.seek(pos) + + +@contextlib.contextmanager +def atomic_write(path: str, mode: str = "wb"): + """ + A context manager that opens a temporary file next to `path` and, on exit, + replaces `path` with the temporary file, thereby updating `path` + atomically. + """ + fd, fn = tempfile.mkstemp( + dir=os.path.dirname(path), prefix=os.path.basename(path) + "-" + ) + try: + with open(fd, mode) as fp: + yield fp + except BaseException: + with contextlib.suppress(FileNotFoundError): + os.unlink(fn) + raise + else: + os.replace(fn, path) + + +def _translate(pat, STAR, QUESTION_MARK): + # Copied from: https://github.com/python/cpython/pull/106703. + res: list[str] = [] + add = res.append + i, n = 0, len(pat) + while i < n: + c = pat[i] + i = i + 1 + if c == "*": + # compress consecutive `*` into one + if (not res) or res[-1] is not STAR: + add(STAR) + elif c == "?": + add(QUESTION_MARK) + elif c == "[": + j = i + if j < n and pat[j] == "!": + j = j + 1 + if j < n and pat[j] == "]": + j = j + 1 + while j < n and pat[j] != "]": + j = j + 1 + if j >= n: + add("\\[") + else: + stuff = pat[i:j] + if "-" not in stuff: + stuff = stuff.replace("\\", r"\\") + else: + chunks = [] + k = i + 2 if pat[i] == "!" else i + 1 + while True: + k = pat.find("-", k, j) + if k < 0: + break + chunks.append(pat[i:k]) + i = k + 1 + k = k + 3 + chunk = pat[i:j] + if chunk: + chunks.append(chunk) + else: + chunks[-1] += "-" + # Remove empty ranges -- invalid in RE. + for k in range(len(chunks) - 1, 0, -1): + if chunks[k - 1][-1] > chunks[k][0]: + chunks[k - 1] = chunks[k - 1][:-1] + chunks[k][1:] + del chunks[k] + # Escape backslashes and hyphens for set difference (--). + # Hyphens that create ranges shouldn't be escaped. + stuff = "-".join( + s.replace("\\", r"\\").replace("-", r"\-") for s in chunks + ) + # Escape set operations (&&, ~~ and ||). + stuff = re.sub(r"([&~|])", r"\\\1", stuff) + i = j + 1 + if not stuff: + # Empty range: never match. + add("(?!)") + elif stuff == "!": + # Negated empty range: match any character. + add(".") + else: + if stuff[0] == "!": + stuff = "^" + stuff[1:] + elif stuff[0] in ("^", "["): + stuff = "\\" + stuff + add(f"[{stuff}]") + else: + add(re.escape(c)) + assert i == n + return res + + +def glob_translate(pat): + # Copied from: https://github.com/python/cpython/pull/106703. + # The keyword parameters' values are fixed to: + # recursive=True, include_hidden=True, seps=None + """Translate a pathname with shell wildcards to a regular expression.""" + if os.path.altsep: + seps = os.path.sep + os.path.altsep + else: + seps = os.path.sep + escaped_seps = "".join(map(re.escape, seps)) + any_sep = f"[{escaped_seps}]" if len(seps) > 1 else escaped_seps + not_sep = f"[^{escaped_seps}]" + one_last_segment = f"{not_sep}+" + one_segment = f"{one_last_segment}{any_sep}" + any_segments = f"(?:.+{any_sep})?" + any_last_segments = ".*" + results = [] + parts = re.split(any_sep, pat) + last_part_idx = len(parts) - 1 + for idx, part in enumerate(parts): + if part == "*": + results.append(one_segment if idx < last_part_idx else one_last_segment) + continue + if part == "**": + results.append(any_segments if idx < last_part_idx else any_last_segments) + continue + elif "**" in part: + raise ValueError( + "Invalid pattern: '**' can only be an entire path component" + ) + if part: + results.extend(_translate(part, f"{not_sep}*", not_sep)) + if idx < last_part_idx: + results.append(any_sep) + res = "".join(results) + return rf"(?s:{res})\Z" diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_C.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_C.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..0f9989a3eafa4dbd85d61a59a0a00f820e391eb0 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_C.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b47cde4dc6a352014f58255ae607df24b9c7dad6da4bce9cd0651c24ec1070c +size 340912 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0aef38c8a9bb84a9833c4c2c9c34ad528d564b32 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/__init__.py @@ -0,0 +1,39 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. +import torch +from torch._functorch.deprecated import ( + combine_state_for_ensemble, + functionalize, + grad, + grad_and_value, + hessian, + jacfwd, + jacrev, + jvp, + make_functional, + make_functional_with_buffers, + vjp, + vmap, +) + +# utilities. Maybe these should go in their own namespace in the future? +from torch._functorch.make_functional import ( + FunctionalModule, + FunctionalModuleWithBuffers, +) + +# Was never documented +from torch._functorch.python_key import make_fx + + +# Top-level APIs. Please think carefully before adding something to the +# top-level namespace: +# - private helper functions should go into torch._functorch +# - very experimental things should go into functorch.experimental +# - compilation related things should go into functorch.compile + + +__version__ = torch.__version__ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/__pycache__/__init__.cpython-311.pyc b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17f7060e76dcb90c2c33f63f17679b472260b33c Binary files /dev/null and b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/__pycache__/__init__.cpython-311.pyc differ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_src/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_src/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_src/aot_autograd/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_src/aot_autograd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..94f258df84ba8730208768fc44222bee4b3ebc33 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_src/aot_autograd/__init__.py @@ -0,0 +1,8 @@ +# This file has moved to under torch/_functorch. It is not public API. +# If you are not a PyTorch developer and you are relying on the following +# imports, please file an issue. +from torch._functorch.aot_autograd import ( + aot_autograd_decompositions, + KNOWN_TYPES, + PytreeThunk, +) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_src/eager_transforms/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_src/eager_transforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6052b5548f4af3dbc6d9d45b0ffe72a8d5013d41 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_src/eager_transforms/__init__.py @@ -0,0 +1,7 @@ +# This file has moved to under torch/_functorch. It is not public API. +# If you are not a PyTorch developer and you are relying on the following +# imports, please file an issue. +from torch._functorch.eager_transforms import ( + _assert_wrapped_functional, + _unwrap_functional_tensor, +) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_src/make_functional/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_src/make_functional/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3de7787df0c3304207b42b51e9fb62da9d33c7d0 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_src/make_functional/__init__.py @@ -0,0 +1,4 @@ +# This file has moved to under torch/_functorch. It is not public API. +# If you are not a PyTorch developer and you are relying on the following +# imports, please file an issue. +from torch._functorch.make_functional import _swap_state diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_src/vmap/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_src/vmap/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dc90517753e50f92362ba954248e31f69f7cfcd5 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/_src/vmap/__init__.py @@ -0,0 +1,16 @@ +# This file has moved to under torch/_functorch. It is not public API. +# If you are not a PyTorch developer and you are relying on the following +# imports, please file an issue. +from torch._functorch.vmap import ( + _add_batch_dim, + _broadcast_to_and_flatten, + _create_batched_inputs, + _get_name, + _process_batched_inputs, + _remove_batch_dim, + _unwrap_batched, + _validate_and_get_batch_size, + Tensor, + tree_flatten, + tree_unflatten, +) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/compile/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/compile/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e7548a5ff6b91bae4fa561f0de7ad5d3492eda05 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/compile/__init__.py @@ -0,0 +1,30 @@ +from torch._functorch import config +from torch._functorch.aot_autograd import ( + aot_function, + aot_module, + aot_module_simplified, + compiled_function, + compiled_module, + get_aot_compilation_context, + get_aot_graph_name, + get_graph_being_compiled, + make_boxed_compiler, + make_boxed_func, +) +from torch._functorch.compilers import ( + debug_compile, + default_decompositions, + draw_graph_compile, + memory_efficient_fusion, + nnc_jit, + nop, + print_compile, + ts_compile, +) +from torch._functorch.fx_minifier import minifier +from torch._functorch.partitioners import ( + default_partition, + draw_graph, + min_cut_rematerialization_partition, +) +from torch._functorch.python_key import pythonkey_decompose diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/compile/__pycache__/__init__.cpython-311.pyc b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/compile/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9ea8654bc401f2be944e8e533c79651f8279f0e Binary files /dev/null and b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/compile/__pycache__/__init__.cpython-311.pyc differ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/dim/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/dim/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..95747181e848ed89d1bf71b2ca26abe3869cddcd --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/dim/__init__.py @@ -0,0 +1,160 @@ +import functorch._C +import torch +from functorch._C import dim as _C + +from .tree_map import tree_flatten, tree_map +from .wrap_type import wrap_type + + +_C._patch_tensor_class() +dims, DimList, dimlists = _C.dims, _C.DimList, _C.dimlists + + +class DimensionMismatchError(Exception): + pass + + +class DimensionBindError(Exception): + pass + + +from . import op_properties + + +# use dict to avoid writing C++ bindings for set +pointwise = dict.fromkeys(op_properties.pointwise, True) + + +class _Tensor: + # fast path around slow wrapping/unwrapping logic for simply queries used + # by the implementation... + + @property + def dims(self): + return tuple(d for d in self._levels if isinstance(d, Dim)) + + def dim(self): + return self.ndim + + __torch_function__ = classmethod(_C.__torch_function__) + expand = _C._instancemethod(_C.expand) + + index = _C._instancemethod(_C.index) + + def __repr__(self): + tensor, levels, ndim = self._tensor, self._levels, self.ndim + return f"{tensor}\nwith dims={tuple(l + ndim if isinstance(l, int) else l for l in levels)} sizes={tuple(tensor.size())}" + + +TensorLike = (_Tensor, torch.Tensor) + + +class Dim(_C.Dim, _Tensor): + # note that _C.Dim comes before tensor because we want the Dim API for things like size to take precedence. + # Tensor defines format, but we want to print Dims with special formatting + __format__ = object.__format__ + + +class Tensor(_Tensor, _C.Tensor): + from_positional = staticmethod(_C.Tensor_from_positional) + sum = _C._instancemethod(_C.Tensor_sum) + + +def cat(tensors, dim, new_dim): + n = dims() + return stack(tensors, n, dim).index([n, dim], new_dim) + + +_wrap = _C._wrap + + +def _def(name, *args, **kwargs): + orig = getattr(torch.Tensor, name) + setattr(_Tensor, name, _C._instancemethod(_wrap(orig, *args, **kwargs))) + + +t__getitem__ = _C._instancemethod(_C.__getitem__) +stack = _C.stack +split = _C._instancemethod(_C.split) + +# note: there is no python reference +t__setitem__ = _C._instancemethod(_C.__setitem__) +# this is patched in the C API because otherwise torch.Tensor will +# no longer be considered a sequence and things will break +# torch.Tensor.__getitem__ = t__getitem__ + +_Tensor.__getitem__ = t__getitem__ +# torch.Tensor.__setitem__ = t__setitem__ +_Tensor.__setitem__ = t__setitem__ + +torch.Tensor.split = split +_Tensor.split = split +torch.Tensor.expand = _C._instancemethod(_C.expand) +torch.Tensor.index = _C._instancemethod(_C.index) +wrap_type(_Tensor, torch.Tensor, _Tensor.__torch_function__) +del _Tensor.ndim + +_Tensor.order = _C._instancemethod(_C.order) + +_def("mean") +_def("sum") +_def("all") +_def("amax") +_def("amin") +_def("aminmax") +_def("any") +_def("count_nonzero") +_def("logsumexp") +_def("nanmean") +_def("nansum") +_def("prod") +_def("std", keepdim_offset=2) +_def("var", keepdim_offset=2) +_def("max", single_dim=True) +_def("min", single_dim=True) +_def("argmax", single_dim=True) +_def("argmin", single_dim=True) +_def("kthvalue", single_dim=True) +_def("median", single_dim=True) +_def("nanmedian", single_dim=True) +_def("mode", single_dim=True) +_def("sort", reduce=False) +_def("argsort", reduce=False) +_def("unbind", single_dim=True) +_def("chunk", dim_offset=1, reduce=False) +_def("cummax", single_dim=True, reduce=False) +_def("cummin", single_dim=True, reduce=False) +_def("cumprod", single_dim=True, reduce=False) +_def("cumprod_", single_dim=True, reduce=False) +_def("cumsum", single_dim=True, reduce=False) +_def("cumsum_", single_dim=True, reduce=False) +_def("logcumsumexp", single_dim=True, reduce=False) +_def("renorm", dim_offset=1, single_dim=True, reduce=False) +_def("softmax", single_dim=True, reduce=False) +softmax = _wrap(torch.nn.functional.softmax, single_dim=True, reduce=False) + +# stuff to handle in the future, because they require special +# binding logic for dims +# cross +# diag_embed +# diagonal +# diagonal_scatter +# diff +# nanquantile +# quantile +# roll +# rot90 +# topk (new dimes on output) +# should these all be subsumed by inplace indexing? +# index_add_ +# index_add +# index_copy +# index_copy_ +# index_fill +# index_fill_ +# index_select +# scatter +# scatter_ +# scatter_add +# scatter_add_ +# scatter_reduce diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/dim/magic_trace.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/dim/magic_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..5c962a898ca79cfe3d8af7432aacc3802d4f4ade --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/dim/magic_trace.py @@ -0,0 +1,42 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. +import os +import signal +import subprocess +from contextlib import contextmanager + + +@contextmanager +def magic_trace(output="trace.fxt", magic_trace_cache="/tmp/magic-trace"): + pid = os.getpid() + if not os.path.exists(magic_trace_cache): + print(f"Downloading magic_trace to: {magic_trace_cache}") + subprocess.run( + [ + "wget", + "-O", + magic_trace_cache, + "-q", + "https://github.com/janestreet/magic-trace/releases/download/v1.0.2/magic-trace", + ] + ) + subprocess.run(["chmod", "+x", magic_trace_cache]) + args = [magic_trace_cache, "attach", "-pid", str(pid), "-o", output] + p = subprocess.Popen(args, stderr=subprocess.PIPE, encoding="utf-8") + while True: + x = p.stderr.readline() + print(x) + if "Attached" in x: + break + try: + yield + finally: + p.send_signal(signal.SIGINT) + r = p.wait() + print(p.stderr.read()) + p.stderr.close() + if r != 0: + raise ValueError(f"magic_trace exited abnormally: {r}") diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/dim/op_properties.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/dim/op_properties.py new file mode 100644 index 0000000000000000000000000000000000000000..01313f71f030d58ce76c15c7f8516c4a0bdcf48a --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/dim/op_properties.py @@ -0,0 +1,312 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. +import torch + + +# pointwise operators can go through a faster pathway + +tensor_magic_methods = ["add", ""] +pointwise_magic_methods_with_reverse = ( + "add", + "sub", + "mul", + "floordiv", + "div", + "truediv", + "mod", + "pow", + "lshift", + "rshift", + "and", + "or", + "xor", +) +pointwise_magic_methods = ( + *(x for m in pointwise_magic_methods_with_reverse for x in (m, "r" + m)), + "eq", + "gt", + "le", + "lt", + "ge", + "gt", + "ne", + "neg", + "pos", + "abs", + "invert", + "iadd", + "isub", + "imul", + "ifloordiv", + "idiv", + "itruediv", + "imod", + "ipow", + "ilshift", + "irshift", + "iand", + "ior", + "ixor", + "int", + "long", + "float", + "complex", +) + +pointwise_methods = (*(f"__{m}__" for m in pointwise_magic_methods),) + +pointwise = ( + *(getattr(torch.Tensor, m) for m in pointwise_methods), + torch.nn.functional.dropout, + torch.where, + torch.Tensor.abs, + torch.abs, + torch.Tensor.acos, + torch.acos, + torch.Tensor.acosh, + torch.acosh, + torch.Tensor.add, + torch.add, + torch.Tensor.addcdiv, + torch.addcdiv, + torch.Tensor.addcmul, + torch.addcmul, + torch.Tensor.addr, + torch.addr, + torch.Tensor.angle, + torch.angle, + torch.Tensor.asin, + torch.asin, + torch.Tensor.asinh, + torch.asinh, + torch.Tensor.atan, + torch.atan, + torch.Tensor.atan2, + torch.atan2, + torch.Tensor.atanh, + torch.atanh, + torch.Tensor.bitwise_and, + torch.bitwise_and, + torch.Tensor.bitwise_left_shift, + torch.bitwise_left_shift, + torch.Tensor.bitwise_not, + torch.bitwise_not, + torch.Tensor.bitwise_or, + torch.bitwise_or, + torch.Tensor.bitwise_right_shift, + torch.bitwise_right_shift, + torch.Tensor.bitwise_xor, + torch.bitwise_xor, + torch.Tensor.ceil, + torch.ceil, + torch.celu, + torch.nn.functional.celu, + torch.Tensor.clamp, + torch.clamp, + torch.Tensor.clamp_max, + torch.clamp_max, + torch.Tensor.clamp_min, + torch.clamp_min, + torch.Tensor.copysign, + torch.copysign, + torch.Tensor.cos, + torch.cos, + torch.Tensor.cosh, + torch.cosh, + torch.Tensor.deg2rad, + torch.deg2rad, + torch.Tensor.digamma, + torch.digamma, + torch.Tensor.div, + torch.div, + torch.dropout, + torch.nn.functional.dropout, + torch.nn.functional.elu, + torch.Tensor.eq, + torch.eq, + torch.Tensor.erf, + torch.erf, + torch.Tensor.erfc, + torch.erfc, + torch.Tensor.erfinv, + torch.erfinv, + torch.Tensor.exp, + torch.exp, + torch.Tensor.exp2, + torch.exp2, + torch.Tensor.expm1, + torch.expm1, + torch.feature_dropout, + torch.Tensor.float_power, + torch.float_power, + torch.Tensor.floor, + torch.floor, + torch.Tensor.floor_divide, + torch.floor_divide, + torch.Tensor.fmod, + torch.fmod, + torch.Tensor.frac, + torch.frac, + torch.Tensor.frexp, + torch.frexp, + torch.Tensor.gcd, + torch.gcd, + torch.Tensor.ge, + torch.ge, + torch.nn.functional.gelu, + torch.nn.functional.glu, + torch.Tensor.gt, + torch.gt, + torch.Tensor.hardshrink, + torch.hardshrink, + torch.nn.functional.hardshrink, + torch.nn.functional.hardsigmoid, + torch.nn.functional.hardswish, + torch.nn.functional.hardtanh, + torch.Tensor.heaviside, + torch.heaviside, + torch.Tensor.hypot, + torch.hypot, + torch.Tensor.i0, + torch.i0, + torch.Tensor.igamma, + torch.igamma, + torch.Tensor.igammac, + torch.igammac, + torch.Tensor.isclose, + torch.isclose, + torch.Tensor.isfinite, + torch.isfinite, + torch.Tensor.isinf, + torch.isinf, + torch.Tensor.isnan, + torch.isnan, + torch.Tensor.isneginf, + torch.isneginf, + torch.Tensor.isposinf, + torch.isposinf, + torch.Tensor.isreal, + torch.isreal, + torch.Tensor.kron, + torch.kron, + torch.Tensor.lcm, + torch.lcm, + torch.Tensor.ldexp, + torch.ldexp, + torch.Tensor.le, + torch.le, + torch.nn.functional.leaky_relu, + torch.Tensor.lerp, + torch.lerp, + torch.Tensor.lgamma, + torch.lgamma, + torch.Tensor.log, + torch.log, + torch.Tensor.log10, + torch.log10, + torch.Tensor.log1p, + torch.log1p, + torch.Tensor.log2, + torch.log2, + torch.nn.functional.logsigmoid, + torch.Tensor.logical_and, + torch.logical_and, + torch.Tensor.logical_not, + torch.logical_not, + torch.Tensor.logical_or, + torch.logical_or, + torch.Tensor.logical_xor, + torch.logical_xor, + torch.Tensor.logit, + torch.logit, + torch.Tensor.lt, + torch.lt, + torch.Tensor.maximum, + torch.maximum, + torch.Tensor.minimum, + torch.minimum, + torch.nn.functional.mish, + torch.Tensor.mvlgamma, + torch.mvlgamma, + torch.Tensor.nan_to_num, + torch.nan_to_num, + torch.Tensor.ne, + torch.ne, + torch.Tensor.neg, + torch.neg, + torch.Tensor.nextafter, + torch.nextafter, + torch.Tensor.outer, + torch.outer, + torch.polar, + torch.Tensor.polygamma, + torch.polygamma, + torch.Tensor.positive, + torch.positive, + torch.Tensor.pow, + torch.pow, + torch.Tensor.prelu, + torch.prelu, + torch.nn.functional.prelu, + torch.Tensor.rad2deg, + torch.rad2deg, + torch.Tensor.reciprocal, + torch.reciprocal, + torch.Tensor.relu, + torch.relu, + torch.nn.functional.relu, + torch.nn.functional.relu6, + torch.Tensor.remainder, + torch.remainder, + torch.Tensor.round, + torch.round, + torch.rrelu, + torch.nn.functional.rrelu, + torch.Tensor.rsqrt, + torch.rsqrt, + torch.rsub, + torch.selu, + torch.nn.functional.selu, + torch.Tensor.sgn, + torch.sgn, + torch.Tensor.sigmoid, + torch.sigmoid, + torch.nn.functional.sigmoid, + torch.Tensor.sign, + torch.sign, + torch.Tensor.signbit, + torch.signbit, + torch.nn.functional.silu, + torch.Tensor.sin, + torch.sin, + torch.Tensor.sinc, + torch.sinc, + torch.Tensor.sinh, + torch.sinh, + torch.nn.functional.softplus, + torch.nn.functional.softshrink, + torch.Tensor.sqrt, + torch.sqrt, + torch.Tensor.square, + torch.square, + torch.Tensor.sub, + torch.sub, + torch.Tensor.tan, + torch.tan, + torch.Tensor.tanh, + torch.tanh, + torch.nn.functional.tanh, + torch.threshold, + torch.nn.functional.threshold, + torch.trapz, + torch.Tensor.true_divide, + torch.true_divide, + torch.Tensor.trunc, + torch.trunc, + torch.Tensor.xlogy, + torch.xlogy, + torch.rand_like, +) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/dim/tree_map.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/dim/tree_map.py new file mode 100644 index 0000000000000000000000000000000000000000..3d2eae0582c85619e0d28e648af58cbd847eee97 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/dim/tree_map.py @@ -0,0 +1,15 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from functorch._C import dim + + +tree_flatten = dim.tree_flatten + + +def tree_map(fn, tree): + vs, unflatten = tree_flatten(tree) + return unflatten(fn(v) for v in vs) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/dim/wrap_type.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/dim/wrap_type.py new file mode 100644 index 0000000000000000000000000000000000000000..b9ebda47c4cfe3378d9238277424be73400d482c --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/dim/wrap_type.py @@ -0,0 +1,62 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +from types import ( + BuiltinMethodType, + FunctionType, + GetSetDescriptorType, + MethodDescriptorType, + WrapperDescriptorType, +) + +from functorch._C import dim as _C + + +_wrap_method = _C._wrap_method + +FUNC_TYPES = ( + FunctionType, + MethodDescriptorType, + BuiltinMethodType, + WrapperDescriptorType, +) +PROPERTY_TYPES = (GetSetDescriptorType, property) + + +def wrap_type(to_patch, pattern, __torch_function__): + wrap_method = _wrap_method + + all = {} + for t in reversed(pattern.mro()[:-1]): # skip object + all.update(t.__dict__) + + def wrap_attr(orig): + return property(wrap_method(orig.__get__, __torch_function__)) + + for name, obj in all.items(): + if name in ( + "__dict__", + "__new__", + "__init__", + "__repr__", + "__weakref__", + "__doc__", + "__module__", + "__dir__", + ): + continue + + # skip things that have been overloaded + # things that come from object like `__eq__` still need to be patched, however. + if hasattr(to_patch, name) and getattr(to_patch, name) is not getattr( + object, name, None + ): + continue + + if isinstance(obj, FUNC_TYPES): + setattr(to_patch, name, wrap_method(obj, __torch_function__)) + elif isinstance(obj, PROPERTY_TYPES): + setattr(to_patch, name, wrap_attr(obj)) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/einops/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/einops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d7ac34f7a3722010fc0fde97fd1cd72e76fa88b7 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/einops/__init__.py @@ -0,0 +1,4 @@ +from .rearrange import rearrange + + +__all__ = ["rearrange"] diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/einops/_parsing.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/einops/_parsing.py new file mode 100644 index 0000000000000000000000000000000000000000..2352ea932426271fdc16f660abb4308ea9b3c924 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/einops/_parsing.py @@ -0,0 +1,308 @@ +"""Adapted from https://github.com/arogozhnikov/einops/blob/36c7bb16e57d6e57f8f3050f9e07abdf3f00469f/einops/parsing.py. + +MIT License + +Copyright (c) 2018 Alex Rogozhnikov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +""" + +from __future__ import annotations + +import keyword +import warnings +from typing import Optional, TYPE_CHECKING, Union + + +if TYPE_CHECKING: + from collections.abc import Collection, Mapping + + +_ellipsis: str = "\u2026" # NB, this is a single unicode symbol. String is used as it is not a list, but can be iterated + + +class AnonymousAxis: + """Used by `ParsedExpression` to represent an axis with a size (> 1), but no associated identifier. + + Note: Different instances of this class are not equal to each other, even if they have the same value. + """ + + def __init__(self, value: str) -> None: + self.value = int(value) + if self.value < 1: + raise ValueError( + f"Anonymous axis should have positive length, not {self.value}" + ) + + def __repr__(self) -> str: + return f"{self.value}-axis" + + +class ParsedExpression: + """Structure containing information about one side of an `einops`-style pattern (e.g. 'b c (h w)').""" + + def __init__( + self, + expression: str, + *, + allow_underscore: bool = False, + allow_duplicates: bool = False, + ) -> None: + """Parse the expression and store relevant metadata. + + Args: + expression (str): the `einops`-pattern to parse + allow_underscore (bool): whether to allow axis identifier names to begin with an underscore + allow_duplicates (bool): whether to allow an identifier to appear more than once in the expression + """ + self.has_ellipsis: bool = False + self.has_ellipsis_parenthesized: Optional[bool] = None + self.identifiers: set[Union[str, AnonymousAxis]] = set() + # that's axes like 2, 3, 4 or 5. Axes with size 1 are exceptional and replaced with empty composition + self.has_non_unitary_anonymous_axes: bool = False + # composition keeps structure of composite axes, see how different corner cases are handled in tests + self.composition: list[Union[list[Union[str, AnonymousAxis]], str]] = [] + if "." in expression: + if "..." not in expression: + raise ValueError( + "Expression may contain dots only inside ellipsis (...)" + ) + if str.count(expression, "...") != 1 or str.count(expression, ".") != 3: + raise ValueError( + "Expression may contain dots only inside ellipsis (...); only one ellipsis for tensor " + ) + expression = expression.replace("...", _ellipsis) + self.has_ellipsis = True + + bracket_group: Optional[list[Union[str, AnonymousAxis]]] = None + + def add_axis_name(x: str) -> None: + if x in self.identifiers: + if not (allow_underscore and x == "_") and not allow_duplicates: + raise ValueError( + f"Indexing expression contains duplicate dimension '{x}'" + ) + if x == _ellipsis: + self.identifiers.add(_ellipsis) + if bracket_group is None: + self.composition.append(_ellipsis) + self.has_ellipsis_parenthesized = False + else: + bracket_group.append(_ellipsis) + self.has_ellipsis_parenthesized = True + else: + is_number = str.isdecimal(x) + if is_number and int(x) == 1: + # handling the case of anonymous axis of length 1 + if bracket_group is None: + self.composition.append([]) + else: + pass # no need to think about 1s inside parenthesis + return + is_axis_name, reason = self.check_axis_name_return_reason( + x, allow_underscore=allow_underscore + ) + if not (is_number or is_axis_name): + raise ValueError(f"Invalid axis identifier: {x}\n{reason}") + axis_name: Union[str, AnonymousAxis] = ( + AnonymousAxis(x) if is_number else x + ) + self.identifiers.add(axis_name) + if is_number: + self.has_non_unitary_anonymous_axes = True + if bracket_group is None: + self.composition.append([axis_name]) + else: + bracket_group.append(axis_name) + + current_identifier = None + for char in expression: + if char in "() ": + if current_identifier is not None: + add_axis_name(current_identifier) + current_identifier = None + if char == "(": + if bracket_group is not None: + raise ValueError( + "Axis composition is one-level (brackets inside brackets not allowed)" + ) + bracket_group = [] + elif char == ")": + if bracket_group is None: + raise ValueError("Brackets are not balanced") + self.composition.append(bracket_group) + bracket_group = None + elif str.isalnum(char) or char in ["_", _ellipsis]: + if current_identifier is None: + current_identifier = char + else: + current_identifier += char + else: + raise ValueError(f"Unknown character '{char}'") + + if bracket_group is not None: + raise ValueError(f"Imbalanced parentheses in expression: '{expression}'") + if current_identifier is not None: + add_axis_name(current_identifier) + + @staticmethod + def check_axis_name_return_reason( + name: str, allow_underscore: bool = False + ) -> tuple[bool, str]: + """Check if the given axis name is valid, and a message explaining why if not. + + Valid axes names are python identifiers except keywords, and should not start or end with an underscore. + + Args: + name (str): the axis name to check + allow_underscore (bool): whether axis names are allowed to start with an underscore + + Returns: + tuple[bool, str]: whether the axis name is valid, a message explaining why if not + """ + if not str.isidentifier(name): + return False, "not a valid python identifier" + elif name[0] == "_" or name[-1] == "_": + if name == "_" and allow_underscore: + return True, "" + return False, "axis name should should not start or end with underscore" + else: + if keyword.iskeyword(name): + warnings.warn( + f"It is discouraged to use axes names that are keywords: {name}", + RuntimeWarning, + ) + if name in ["axis"]: + warnings.warn( + "It is discouraged to use 'axis' as an axis name and will raise an error in future", + FutureWarning, + ) + return True, "" + + @staticmethod + def check_axis_name(name: str) -> bool: + """Check if the name is a valid axis name. + + Args: + name (str): the axis name to check + + Returns: + bool: whether the axis name is valid + """ + is_valid, _ = ParsedExpression.check_axis_name_return_reason(name) + return is_valid + + +def parse_pattern( + pattern: str, axes_lengths: Mapping[str, int] +) -> tuple[ParsedExpression, ParsedExpression]: + """Parse an `einops`-style pattern into a left-hand side and right-hand side `ParsedExpression` object. + + Args: + pattern (str): the `einops`-style rearrangement pattern + axes_lengths (Mapping[str, int]): any additional length specifications for dimensions + + Returns: + tuple[ParsedExpression, ParsedExpression]: a tuple containing the left-hand side and right-hand side expressions + """ + # adapted from einops.einops._prepare_transformation_recipe + # https://github.com/arogozhnikov/einops/blob/230ac1526c1f42c9e1f7373912c7f8047496df11/einops/einops.py + try: + left_str, right_str = pattern.split("->") + except ValueError: + raise ValueError("Pattern must contain a single '->' separator") from None + + if _ellipsis in axes_lengths: + raise ValueError(f"'{_ellipsis}' is not an allowed axis identifier") + + left = ParsedExpression(left_str) + right = ParsedExpression(right_str) + + if not left.has_ellipsis and right.has_ellipsis: + raise ValueError( + f"Ellipsis found in right side, but not left side of a pattern {pattern}" + ) + if left.has_ellipsis and left.has_ellipsis_parenthesized: + raise ValueError( + f"Ellipsis is parenthesis in the left side is not allowed: {pattern}" + ) + + return left, right + + +def validate_rearrange_expressions( + left: ParsedExpression, right: ParsedExpression, axes_lengths: Mapping[str, int] +) -> None: + """Perform expression validations that are specific to the `rearrange` operation. + + Args: + left (ParsedExpression): left-hand side expression + right (ParsedExpression): right-hand side expression + axes_lengths (Mapping[str, int]): any additional length specifications for dimensions + """ + for length in axes_lengths.values(): + if (length_type := type(length)) is not int: + raise TypeError( + f"rearrange axis lengths must be integers, got: {length_type}" + ) + + if left.has_non_unitary_anonymous_axes or right.has_non_unitary_anonymous_axes: + raise ValueError("rearrange only supports unnamed axes of size 1") + + difference = set.symmetric_difference(left.identifiers, right.identifiers) + if len(difference) > 0: + raise ValueError( + f"Identifiers only on one side of rearrange expression (should be on both): {difference}" + ) + + unmatched_axes = axes_lengths.keys() - left.identifiers + if len(unmatched_axes) > 0: + raise ValueError( + f"Identifiers not found in rearrange expression: {unmatched_axes}" + ) + + +def comma_separate(collection: Collection[Union[str, Collection[str]]]) -> str: + """Convert a collection of strings representing first class dims into a comma-separated string. + + Args: + collection (Collection[Union[str, Collection[str]]]): the collection of strings to convert + + Returns: + str: the comma-separated string + + Examples: + >>> comma_separate(("d0",)) + 'd0' + + >>> comma_separate(("d0", "d1", "d2", "d3")) + 'd0, d1, d2, d3' + + >>> comma_separate([("d1", "d4")]) + '(d1, d4)' + + >>> comma_separate([("d0",), (), ("d1",), ("d2",), ("d3", "d4")]) + '(d0,), (), (d1,), (d2,), (d3, d4)' + """ + return ", ".join( + item + if isinstance(item, str) + else f"({comma_separate(item)}{',' if len(item) == 1 else ''})" + for item in collection + ) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/einops/rearrange.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/einops/rearrange.py new file mode 100644 index 0000000000000000000000000000000000000000..d7d71f5103f94b1a3667e7c02106a4418157fa2e --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/einops/rearrange.py @@ -0,0 +1,211 @@ +from __future__ import annotations + +import functools +from typing import Callable, TYPE_CHECKING, Union + +import torch +from functorch._C import dim as _C + +from ._parsing import ( + _ellipsis, + AnonymousAxis, + comma_separate, + parse_pattern, + validate_rearrange_expressions, +) + + +if TYPE_CHECKING: + from collections.abc import Sequence + +__all__ = ["rearrange"] + +dims = _C.dims + + +@functools.lru_cache(256) +def _create_rearrange_callable( + tensor_ndim: int, pattern: str, **axes_lengths: int +) -> Callable[[torch.Tensor], torch.Tensor]: + r"""Translate an `einops`-style pattern into a callable that performs the rearrange using first-class dimensions. + + Since the an equivalent result is computed for tensors with the same number of dimensions, with the same pattern and + specified axes lengths, this function can be memoized. + + Args: + tensor_ndim (int): the number of dimensions in the tensor to rearrange + pattern (str): the `einops`-style rearrangement pattern + axes_lengths (int): any additional length specifications for dimensions + + Returns: + Callable[[torch.Tensor], torch.Tensor]: a callable that performs the rearrangement + """ + left, right = parse_pattern(pattern, axes_lengths) + validate_rearrange_expressions(left, right, axes_lengths) + + n_anon_dims = sum(not dim for dim in left.composition) + if left.has_ellipsis: + n_ellipsis_dims = tensor_ndim - (len(left.composition) - 1) + n_named_dims = len(left.identifiers) - 1 + + if (pattern_ndim := n_anon_dims + n_named_dims) > tensor_ndim: + raise ValueError( + f"Number of dimensions in pattern ({pattern_ndim}) must be less than or equal to the number of " + f"dimensions in the tensor ({tensor_ndim})" + ) + else: + n_ellipsis_dims = 0 + n_named_dims = len(left.identifiers) + + if (pattern_ndim := len(left.composition)) != tensor_ndim: + raise ValueError( + f"Number of dimensions in pattern ({pattern_ndim}) must be equal to the number of dimensions in " + f"the tensor ({tensor_ndim})" + ) + n_dims = n_named_dims + n_ellipsis_dims + n_anon_dims + + if n_dims == 0: + # an identity rearrangement on a 0-dimension tensor + return lambda tensor: tensor + + first_class_dims: tuple[str, ...] = tuple(f"d{i}" for i in range(n_dims)) + identifier_dim_map: dict[Union[str, AnonymousAxis], tuple[str, ...]] = {} + anon_axes: list[AnonymousAxis] = [] + + # map the left-hand side identifiers to strings representing first class dims + dims_i = 0 + for dimension in left.composition: + if isinstance(dimension, list): + for identifier in dimension: + # non-unitary anon axes are not allowed in rearrange & unitary anon axes are represented as empty lists + assert isinstance(identifier, str) + identifier_dim_map[identifier] = (first_class_dims[dims_i],) + dims_i += 1 + if not dimension: + # unitary anonymous axis + anon_axis = AnonymousAxis("1") + identifier_dim_map[anon_axis] = (first_class_dims[dims_i],) + anon_axes.append(anon_axis) + dimension.append(anon_axis) + dims_i += 1 + elif dimension == _ellipsis: + identifier = _ellipsis + identifier_dim_map[identifier] = tuple( + first_class_dims[dims_i + j] for j in range(n_ellipsis_dims) + ) + dims_i += n_ellipsis_dims + else: + raise ValueError(f"Unexpected dimension: {dimension}") + + def composition_to_dims( + composition: Sequence[Union[list[Union[str, AnonymousAxis]], str]], + ) -> list[Union[str, tuple[str, ...]]]: + """Convert a `ParsedExpression.composition` into a `Tensor.__getitem__` index of strings representing first + class dims.""" + dim_composition: list[Union[str, tuple[str, ...]]] = [] + for dimension in composition: + if isinstance(dimension, list): + dim_composition.append( + tuple( + dim + for identifier in dimension + for dim in identifier_dim_map[identifier] + ) + ) + elif dimension == _ellipsis: + dim_composition.extend(identifier_dim_map[_ellipsis]) + else: + raise ValueError(f"Unexpected dimension: {dimension}") + return dim_composition + + left_dims = composition_to_dims(left.composition) + right_dims = composition_to_dims(right.composition) + anon_dims = tuple(identifier_dim_map[axis][0] for axis in anon_axes) + specified_lengths = tuple( + (identifier_dim_map[axis][0], length) for axis, length in axes_lengths.items() + ) + + custom_rearrange_callable_name = "do_rearrange" + custom_rearrange_callable_code = ( + ( + f"def {custom_rearrange_callable_name}(tensor):\n" + f" {comma_separate(first_class_dims)} = dims({n_dims})\n" + ) + + ( + "".join( + f" {dim}.size = {length}\n" for (dim, length) in specified_lengths + ) + if specified_lengths + else "" + ) + + f" tensor = tensor[{comma_separate(left_dims)}].order({comma_separate(right_dims)})\n" + + ( + f" return tensor.sum({comma_separate([anon_dims])}, keepdim=False)\n" + if anon_dims + else " return tensor\n" + ) + ) + + exec(custom_rearrange_callable_code) + return locals()[custom_rearrange_callable_name] + + +def rearrange( + tensor: Union[torch.Tensor, list[torch.Tensor], tuple[torch.Tensor, ...]], + pattern: str, + **axes_lengths: int, +) -> torch.Tensor: + r"""A native implementation of `einops.rearrange`, a reader-friendly smart element reordering for multidimensional + tensors. This operation includes functionality of transpose (axes permutation), reshape (view), squeeze, unsqueeze, + stack, concatenate and other operations. + + See: https://einops.rocks/api/rearrange/ + + Args: + tensor (Tensor or sequence of Tensor): the tensor(s) to rearrange + pattern (str): the rearrangement pattern + axes_lengths (int): any additional length specifications for dimensions + + Returns: + Tensor: the rearranged tensor + + Examples: + >>> # suppose we have a set of 32 images in "h w c" format (height-width-channel) + >>> images = torch.randn((32, 30, 40, 3)) + + >>> # stack along first (batch) axis, output is a single array + >>> rearrange(images, "b h w c -> b h w c").shape + torch.Size([32, 30, 40, 3]) + + >>> # concatenate images along height (vertical axis), 960 = 32 * 30 + >>> rearrange(images, "b h w c -> (b h) w c").shape + torch.Size([960, 40, 3]) + + >>> # concatenated images along horizontal axis, 1280 = 32 * 40 + >>> rearrange(images, "b h w c -> h (b w) c").shape + torch.Size([30, 1280, 3]) + + >>> # reordered axes to "b c h w" format for deep learning + >>> rearrange(images, "b h w c -> b c h w").shape + torch.Size([32, 3, 30, 40]) + + >>> # flattened each image into a vector, 3600 = 30 * 40 * 3 + >>> rearrange(images, "b h w c -> b (c h w)").shape + torch.Size([32, 3600]) + + >>> # split each image into 4 smaller (top-left, top-right, bottom-left, bottom-right), 128 = 32 * 2 * 2 + >>> rearrange(images, "b (h1 h) (w1 w) c -> (b h1 w1) h w c", h1=2, w1=2).shape + torch.Size([128, 15, 20, 3]) + + >>> # space-to-depth operation + >>> rearrange(images, "b (h h1) (w w1) c -> b h w (c h1 w1)", h1=2, w1=2).shape + torch.Size([32, 15, 20, 12]) + """ + if not isinstance(tensor, torch.Tensor): + tensor = torch.stack(tensor) + + rearrange_callable = _create_rearrange_callable( + tensor.ndim, pattern, **axes_lengths + ) + + return rearrange_callable(tensor) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/experimental/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3941f6d96e1f6df532966d06de4f72a952a58465 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/experimental/__init__.py @@ -0,0 +1,5 @@ +# PyTorch forward-mode is not mature yet +from functorch import functionalize +from torch._functorch.apis import chunk_vmap +from torch._functorch.batch_norm_replacement import replace_all_batch_norm_modules_ +from torch._functorch.eager_transforms import hessian, jacfwd, jvp diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/experimental/control_flow.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/experimental/control_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..c2b4d52271e7f8c5851b5ef961ea7e90d8a01408 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/experimental/control_flow.py @@ -0,0 +1,6 @@ +from torch import cond # noqa: F401 +from torch._higher_order_ops.map import ( # noqa: F401 + _stack_pytree, + _unstack_pytree, + map, +) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/experimental/ops.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/experimental/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..7a502ef2b002cd824e7b67d08fccac872b313110 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/functorch/experimental/ops.py @@ -0,0 +1 @@ +from torch._ops import HigherOrderOperator # noqa: F401 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/METADATA b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..636a75d33ef37e7b5a58d75312c7fad40d2f3c31 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/METADATA @@ -0,0 +1,64 @@ +Metadata-Version: 2.4 +Name: h5py +Version: 3.15.1 +Summary: Read and write HDF5 files from Python +Author-email: Andrew Collette +Maintainer-email: Thomas Kluyver , Thomas A Caswell +License-Expression: BSD-3-Clause +Project-URL: Homepage, https://www.h5py.org/ +Project-URL: Source, https://github.com/h5py/h5py +Project-URL: Documentation, https://docs.h5py.org/en/stable/ +Project-URL: Release notes, https://docs.h5py.org/en/stable/whatsnew/index.html +Project-URL: Discussion forum, https://forum.hdfgroup.org/c/hdf5/h5py +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: Intended Audience :: Science/Research +Classifier: Operating System :: Unix +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Programming Language :: Cython +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Free Threading :: 1 - Unstable +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Database +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: lzf/LICENSE.txt +License-File: licenses/hdf5.txt +License-File: licenses/license.txt +License-File: licenses/pytables.txt +License-File: licenses/python.txt +License-File: licenses/stdint.txt +Requires-Dist: numpy>=1.21.2 +Dynamic: license-file +Dynamic: requires-dist + +The h5py package provides both a high- and low-level interface to the HDF5 +library from Python. The low-level interface is intended to be a complete +wrapping of the HDF5 API, while the high-level component supports access to +HDF5 files, datasets and groups using established Python and NumPy concepts. + +A strong emphasis on automatic conversion between Python (Numpy) datatypes and +data structures and their HDF5 equivalents vastly simplifies the process of +reading and writing data from Python. + +Wheels are provided for several popular platforms, with an included copy of +the HDF5 library (usually the latest version when h5py is released). + +You can also `build h5py from source +`_ +with any HDF5 stable release from version 1.10.4 onwards, although naturally new +HDF5 versions released after this version of h5py may not work. +Odd-numbered minor versions of HDF5 (e.g. 1.13) are experimental, and may not +be supported. diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/RECORD b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..0b52a7af2863b8634dea82651aa2b8871bad0e33 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/RECORD @@ -0,0 +1,102 @@ +h5py-3.15.1.dist-info/METADATA,sha256=M7UOYHZtOQKtGHsiCmd9IyyOdQdRTXCm2G6f4BsbbNM,3007 +h5py-3.15.1.dist-info/RECORD,, +h5py-3.15.1.dist-info/WHEEL,sha256=3daP3VhxT_uXQ4g9qxjrsHJLh9a9x1Dc522TvcSo1E0,152 +h5py-3.15.1.dist-info/licenses/LICENSE,sha256=5XSylmVc-wylGA7G7uPJXRIrCQZzbTyn484Z4PKX8Mk,1520 +h5py-3.15.1.dist-info/licenses/licenses/hdf5.txt,sha256=K4L--O2KAgumVs4tslBe2FiTnLfDtvffCEvYMDLXe8c,3766 +h5py-3.15.1.dist-info/licenses/licenses/license.txt,sha256=-s9D4DGTz0z42LzdZ84E_GHvaUjdBmcqTl2leeZKOUg,1739 +h5py-3.15.1.dist-info/licenses/licenses/pytables.txt,sha256=mi1dboFWOMajwRMPZr58z_CehMDoIeVz8q3WnURiJBQ,1640 +h5py-3.15.1.dist-info/licenses/licenses/python.txt,sha256=hITnBcmcf12_FXcjtOPNHa_5z-QcdAtXJVWHjwWFiYQ,2503 +h5py-3.15.1.dist-info/licenses/licenses/stdint.txt,sha256=HUwLpl1NqiPvjWwFcevpazCrrr2inCbWbOE1QNTxKyg,1394 +h5py-3.15.1.dist-info/licenses/lzf/LICENSE.txt,sha256=qPjFSrwA0azRV0AVV7Psb1AKx2pe_Reg6qZE4tMua-s,1556 +h5py-3.15.1.dist-info/top_level.txt,sha256=fO7Bsaa0F3Nx6djErCCbSw4-E7rBFMWrBVTGLEMxUMg,5 +h5py.libs/libaec-187855bc.so.0.1.3,sha256=iUOUuf5Mv1X6ypXIACUiEK-_CzTWP7tEvAIsjUn94N8,136561 +h5py.libs/libhdf5-7d060e2f.so.310.5.1,sha256=DfhzTXPESSrR0nxVqcnUz_-h0vqHK207Yh70h9Nchx8,4975937 +h5py.libs/libhdf5_hl-0ce065ed.so.310.0.6,sha256=53TW1caulaT4IwCm4GKjNr498Y-cTP92P5z3YpifYtc,181945 +h5py.libs/libsz-daeb5235.so.2.0.1,sha256=u7E9T3a_Re3CDSXoB-sigbxREYvBorAMo6NtxmaaXVk,37185 +h5py/__init__.py,sha256=I_kmYQhL0idhVllBRhj99lXgVY_3zhpzn0NTuTiZd2o,3662 +h5py/_conv.cpython-311-x86_64-linux-gnu.so,sha256=Fy6UBEzAFKcsQ2m-cXp_Rv_dMsqbIkS_5jAbwtYjt-g,475945 +h5py/_errors.cpython-311-x86_64-linux-gnu.so,sha256=eT_nhxkH1FKPGX14hcB6fBlTKTQ73ODIX6exlUlM-4c,155297 +h5py/_hl/__init__.py,sha256=R6siZWBApRmGrOkxi8kNKxZ0Hcp2MieM-0EBWwbp7vc,457 +h5py/_hl/attrs.py,sha256=XYwfpTHDMKy5zGbPQqb_PPAW1drycRoKPlmZXK4aFaU,10209 +h5py/_hl/base.py,sha256=gWk0AtTeTQUlqw75kZVq93QL-CAGBhzOlOY2O6fXXTc,15711 +h5py/_hl/compat.py,sha256=UXvt42U_OiXAcPcrr1FwVP_ScD4yL-ONPercjyUx6FA,1523 +h5py/_hl/dataset.py,sha256=8PFOQHtcrPx25skyqd2B7BclM8ctguMxRGwZsO7-J58,44034 +h5py/_hl/datatype.py,sha256=-kIh5Ha9K21VLqInUmZ6SZdXag1yvyo30MpgsM3H0P0,1548 +h5py/_hl/dims.py,sha256=rbjYav9D7dFG-Tns_RDuP24B6bwR80LO_2d2NQYihh8,5109 +h5py/_hl/files.py,sha256=2x1X8rFOXNt9VY6OCzWc5-c6LMjUpfJdbqbMykHyDVQ,25643 +h5py/_hl/filters.py,sha256=8e00taWWH4eV9y0Hq9CIRsCNZMqJyN9x2sUjKkYya-Y,14604 +h5py/_hl/group.py,sha256=6t66pmqXrQ8b_YPl5kP3JzQ2EMQZUUCf4PRqtlFTNac,31049 +h5py/_hl/selections.py,sha256=eewlCtKZOm9AMw7G57WQdZXN-0VOinIFqzasdF2HjdI,14655 +h5py/_hl/selections2.py,sha256=PcKxIbSCYjL_QrbeCHw8-MHWDBxOlEDG_UHvP4aBuKY,2723 +h5py/_hl/vds.py,sha256=QpMLtumI_uaJ1CdqMXyxgGaW3rxAztcwSIB4rEjLC3U,9468 +h5py/_npystrings.cpython-311-x86_64-linux-gnu.so,sha256=5TgICi4LqRtiiyMOc6IDnXRUmsFhCEB9d9Bu_1raARI,154713 +h5py/_objects.cpython-311-x86_64-linux-gnu.so,sha256=Ra7XjmfsLyNDj1Z2pAoTJR72hUhqRDUaosVBcLfVw3I,336073 +h5py/_proxy.cpython-311-x86_64-linux-gnu.so,sha256=sLpNyTGYp7PSiPGH5Y3z4F5qaNny3RG71kl2_PVfmOw,146297 +h5py/_selector.cpython-311-x86_64-linux-gnu.so,sha256=pI5Erjnsq0e3N86LTNlfdt_Vl3JgdJhcvzLTuCel0F4,377161 +h5py/defs.cpython-311-x86_64-linux-gnu.so,sha256=USIxDamYP35rZc0JiQ2N5pp3UTCIB3AyMUuhHQdbftc,635329 +h5py/h5.cpython-311-x86_64-linux-gnu.so,sha256=8_Esaif86HkPdZmhFrc3Xvrv2maJnMonxVnGsjQG7kY,265817 +h5py/h5a.cpython-311-x86_64-linux-gnu.so,sha256=wQx9RKirhdof4ucvwcWSfZo-v9YSBtvWlex0NfnAmB0,331289 +h5py/h5ac.cpython-311-x86_64-linux-gnu.so,sha256=D8PtwRLDHuHFxdfbkivuvJew0BxAcuMpEL7VvYpTJHE,216217 +h5py/h5d.cpython-311-x86_64-linux-gnu.so,sha256=IgFk7L-KcqYXRZoZENE3HgAo0TsG94UZLLUWV5Z3ml0,627081 +h5py/h5ds.cpython-311-x86_64-linux-gnu.so,sha256=kTHzJH1mlyv9-lTx8FEs-GTVaxvmRIufN16KQ08OHdU,228801 +h5py/h5f.cpython-311-x86_64-linux-gnu.so,sha256=bAJWDDsV9hqd91bvu_QepXtY5nwvTNkDc3FNj1rC7Dw,380633 +h5py/h5fd.cpython-311-x86_64-linux-gnu.so,sha256=J03N2bPwc5pEjGvpeXnn9WlGM5dDacFLporQYw-Tgrg,389409 +h5py/h5g.cpython-311-x86_64-linux-gnu.so,sha256=qLPXwTclsu33cwBn7jgpSm7TPEZ91n3wWzbOy2px8n0,409601 +h5py/h5i.cpython-311-x86_64-linux-gnu.so,sha256=J0ujFOLT1KrpM60tnlmFUMy5ZsEtTqD7CeszFotSQjg,175281 +h5py/h5l.cpython-311-x86_64-linux-gnu.so,sha256=vq9EN8fWtvQRturncrwK9-SUOOO2dFMD53-JCPC9Tj4,290289 +h5py/h5o.cpython-311-x86_64-linux-gnu.so,sha256=vn5dgfEfHjnzo5A3Syy5_Sf4omHRN6f3Dgs5h0tcKZ0,363993 +h5py/h5p.cpython-311-x86_64-linux-gnu.so,sha256=vs-0rHl0ZSS2w4xt0XteUxYBm9Ujmfr8ukECjYP-wZA,962817 +h5py/h5pl.cpython-311-x86_64-linux-gnu.so,sha256=OWTIbCIh--4HLvWoEQ0oLrIWbapioWJfuP1UEZWQQdo,162849 +h5py/h5py_warnings.py,sha256=bNPu7wWPt1xLVZVB-lpycIoMux1kcNfaKf4NE78dK90,523 +h5py/h5r.cpython-311-x86_64-linux-gnu.so,sha256=htARLXZyGB7id19USs_0kGoYEvc4rht82s0upYx6lJo,200049 +h5py/h5s.cpython-311-x86_64-linux-gnu.so,sha256=o3tHTV5wMgByhkvn0Wr_v5B88JM1FtVAUSKocs2HOH4,327097 +h5py/h5t.cpython-311-x86_64-linux-gnu.so,sha256=C7j2JWqSLb0cHSO01nF8ButpC8LGMUwG2cWoQRrMnhk,923009 +h5py/h5z.cpython-311-x86_64-linux-gnu.so,sha256=SB_uuchd7LJ4bJtCm-nbUlQU8nwY1ZZl2zNbG31DLkY,167017 +h5py/ipy_completer.py,sha256=dGKYNK3CE32jwRVrBeUssdXRocu45VnrA3cvLRp-2E0,3733 +h5py/tests/__init__.py,sha256=oPTnFGaf5_48QHzq0mpTwlxbagBvnvU3W9s2AWRcWFU,613 +h5py/tests/common.py,sha256=X9BqGSwVloEK0cEwqpgOndgtgJVQqrGOFzOcUnn8PxA,7781 +h5py/tests/conftest.py,sha256=-aF7Ig1w4yd00YxOS9ScB4hFunPLXPXUGF8rDL43WSg,545 +h5py/tests/data_files/__init__.py,sha256=WgwvU8ZVG00ZN2EOOnZ7TYJX_NzF_JCSd7nSEDJrbrE,193 +h5py/tests/data_files/vlen_string_dset.h5,sha256=kA-LrxnT2MTRGTrBrGAZ7nd0AF6FwDCvROZ1ezjSl5M,6304 +h5py/tests/data_files/vlen_string_dset_utc.h5,sha256=hbcoOCuDPB2mFie5ozTiKCLVwcs1n-O6byUmKvRTL2M,169904 +h5py/tests/data_files/vlen_string_s390x.h5,sha256=6pkMaOA3G6-rSWb3UvoTVbO59kNgBm9tna_48bfnTKU,9008 +h5py/tests/test_attribute_create.py,sha256=rTj6oNLncfwMXbUy2PK58LL3etbcsEwvZpv-dR7VP0k,2986 +h5py/tests/test_attrs.py,sha256=GdCVdhfibwwUm065SoE63teXY4p2J69uhMClYQUvIfI,9393 +h5py/tests/test_attrs_data.py,sha256=m97aSlhhgkkZs1gECnu8NVZtO5RwdcqIOgr4EVFCc10,9764 +h5py/tests/test_base.py,sha256=OXvSeVI2kBSz2mGhjHQiHFiYSNWeHXd1Rs99xUs7cRA,3816 +h5py/tests/test_big_endian_file.py,sha256=znAyyPu_Vl0gOlXfAP4Z4u2pVJ5gvHjGnEkEq7QupxA,1433 +h5py/tests/test_completions.py,sha256=J1wbtCmv-9uBETTLM3YK58Q3vhNiVmf9kaIK5BQa4RU,1473 +h5py/tests/test_dataset.py,sha256=d0KNSNcsmfgzJ-g4Jzjst4A0id7Z3Adozwejp-kjjLo,82881 +h5py/tests/test_dataset_getitem.py,sha256=nan1Kiw0eFZx8jW4dJ6fvttxNZMITcn5tDMXkwtnzxk,18721 +h5py/tests/test_dataset_swmr.py,sha256=zdgeftjqpiZnEdwoegXfPSaOqhFSh6MP6jq-mgFsYoo,3971 +h5py/tests/test_datatype.py,sha256=AwXgOUaPnQGp5uewoIkxSzg-e7-B0JFcFZfOAihLqKY,1003 +h5py/tests/test_dimension_scales.py,sha256=6b-Qcwe7S1fu-axgbLwKNW3zqGD3xfqrN1Vbzgnp-8k,8086 +h5py/tests/test_dims_dimensionproxy.py,sha256=UVg3DxDIRBqkOmB5DTZvxK-7FyT2XdG8rT_dX3lBebY,566 +h5py/tests/test_dtype.py,sha256=U1-zZawNefDsl-AzEqLjblHv9j3qzlISHPkOYgVza3k,18576 +h5py/tests/test_errors.py,sha256=ero4th_0YJBjXsepwfO6lwXN_tC6D_CRyBzdrXWT-5M,2247 +h5py/tests/test_file.py,sha256=uuuWnXs13fHK5NAZTiIf7Z6yiLvCPvslZt6b4pfogYU,35432 +h5py/tests/test_file2.py,sha256=bGsULxaqWNKoDwi6ktW3nV0UjVaBf0Y7QMYQ0NImeT0,10944 +h5py/tests/test_file_alignment.py,sha256=uWoDfrSqFphLzolVfNNANV_Duz5IkpnTQKf0PVuk87M,4406 +h5py/tests/test_file_image.py,sha256=w7COnNE--O_zfmJKdADzNjTsJp8zUC5Z5XzX0p9OGeY,2009 +h5py/tests/test_filters.py,sha256=JHmfktfdpD2JPkdL-2LPYv1Rrqw6VuDmAVI9e8z6xiU,3062 +h5py/tests/test_group.py,sha256=GDAbp-QBIycuUQbqhwAWWgEeMrdB1PclTP5MXjqTuJs,39573 +h5py/tests/test_h5.py,sha256=FlYZcVxxP1kIYCZdSEC3sR7o72dPWYiUbhyFO0rvN-8,1216 +h5py/tests/test_h5d_direct_chunk.py,sha256=dwvp5uSNX5bpiSRdWsKRvx2aOr6rOuKVpGNVCMn0zhU,7747 +h5py/tests/test_h5f.py,sha256=0Ok7B4xMjF6drAewvvq2lo_I2EBvqMatuA1lGq6D4G4,3949 +h5py/tests/test_h5o.py,sha256=wbDg6o-kzCQKi97Gt0IMBLgcVmNYw59EyESwcSIYaDE,508 +h5py/tests/test_h5p.py,sha256=qWO3u5JOQ4XkgLm2t0kSZgj0RgAylFWlSHia_M2r9AI,8094 +h5py/tests/test_h5pl.py,sha256=2LZY4glHa9lMQLXfuPFFs_mcdGHMgUxpixKQ6RyEIx8,1847 +h5py/tests/test_h5s.py,sha256=mirtQKkR500tMGGC_-srMdPDZ-rp7xQTf8xaj9tFuDg,582 +h5py/tests/test_h5t.py,sha256=EjYXQl70rJaUfE9NOYnWjTltP0g02IYGWpmq1uMQsx8,6595 +h5py/tests/test_h5z.py,sha256=beBdenWUq5TMEpFAWMopFiG4A10Uu7witsFdIjylDG8,1919 +h5py/tests/test_npystrings.py,sha256=MEJN0F674HAeNS1u__wJQsSmCrYuAgSpLxbFsO5zOPo,5620 +h5py/tests/test_objects.py,sha256=SJkg8_VVOEeK7efkjmXTeaty--qd-aPBskYbvy1H5xQ,2703 +h5py/tests/test_ros3.py,sha256=19xBp3LF0QnFwKbcuZDAa2YEt90hl44_bB2Qdo2F0JM,3378 +h5py/tests/test_selections.py,sha256=jmClFsj6x6DJxyx1LxDhtCRZR1wexfYbiLb8FJyzKpw,4849 +h5py/tests/test_slicing.py,sha256=uS5Wpbf9ez2hNgAsBwc5h7fEZfZMKQcvj6fbiFriFDM,13839 +h5py/tests/test_vds/__init__.py,sha256=2mnHIhOAdjMVjHQjBp9VFDLfltPEOR02aoZ1yTJU5hY,103 +h5py/tests/test_vds/test_highlevel_vds.py,sha256=X-Q2z_fbbwkKeAms2RzoSKkwT6rzzB7q1o1zIiY8zbA,17562 +h5py/tests/test_vds/test_lowlevel_vds.py,sha256=Hh3UW61lAvw40hOtJM23lffT84CD7MTWdlFJF4Gg78c,11862 +h5py/tests/test_vds/test_virtual_source.py,sha256=TYP5izckkYLYgVH3rv04EwE1ba1N7Fbjd5LEsqSur-U,6033 +h5py/utils.cpython-311-x86_64-linux-gnu.so,sha256=E-ErYHGF_gDgOmm8_LTNhQfv39sK6Ai2Ftdwsb96F10,179625 +h5py/version.py,sha256=js_yu0sKJ6NfkeCU2Ok1RlHwPO3htXTldqsSUUEUGo0,1911 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/WHEEL b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..877b63ad81f31e9e52588701b631478d58f56658 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp311-cp311-manylinux_2_27_x86_64 +Tag: cp311-cp311-manylinux_2_28_x86_64 + diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/LICENSE b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..28ca56277f0c598235b91158fc8f99755997fb0e --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/LICENSE @@ -0,0 +1,30 @@ +Copyright (c) 2008 Andrew Collette and contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the + distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/licenses/hdf5.txt b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/licenses/hdf5.txt new file mode 100644 index 0000000000000000000000000000000000000000..54126de23c56fdafc8ed5baebfd8da6f1ccdcf8c --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/licenses/hdf5.txt @@ -0,0 +1,69 @@ +HDF5 (Hierarchical Data Format 5) Software Library and Utilities +Copyright 2006-2007 by The HDF Group (THG). + +NCSA HDF5 (Hierarchical Data Format 5) Software Library and Utilities +Copyright 1998-2006 by the Board of Trustees of the University of Illinois. + +All rights reserved. + +Contributors: National Center for Supercomputing Applications (NCSA) +at the University of Illinois, Fortner Software, Unidata Program +Center (netCDF), The Independent JPEG Group (JPEG), Jean-loup Gailly +and Mark Adler (gzip), and Digital Equipment Corporation (DEC). + +Redistribution and use in source and binary forms, with or without +modification, are permitted for any purpose (including commercial +purposes) provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright +notice, this list of conditions, and the following disclaimer. + 2. Redistributions in binary form must reproduce the above +copyright notice, this list of conditions, and the following +disclaimer in the documentation and/or materials provided with the +distribution. + 3. In addition, redistributions of modified forms of the source or +binary code must carry prominent notices stating that the original +code was changed and the date of the change. + 4. All publications or advertising materials mentioning features or +use of this software are asked, but not required, to acknowledge that +it was developed by The HDF Group and by the National Center for +Supercomputing Applications at the University of Illinois at +Urbana-Champaign and credit the contributors. + 5. Neither the name of The HDF Group, the name of the University, +nor the name of any Contributor may be used to endorse or promote +products derived from this software without specific prior written +permission from THG, the University, or the Contributor, respectively. + +DISCLAIMER: THIS SOFTWARE IS PROVIDED BY THE HDF GROUP (THG) AND THE +CONTRIBUTORS "AS IS" WITH NO WARRANTY OF ANY KIND, EITHER EXPRESSED OR +IMPLIED. In no event shall THG or the Contributors be liable for any +damages suffered by the users arising out of the use of this software, +even if advised of the possibility of such damage. + +Portions of HDF5 were developed with support from the University of +California, Lawrence Livermore National Laboratory (UC LLNL). The +following statement applies to those portions of the product and must +be retained in any redistribution of source code, binaries, +documentation, and/or accompanying materials: + +This work was partially produced at the University of California, +Lawrence Livermore National Laboratory (UC LLNL) under contract +no. W-7405-ENG-48 (Contract 48) between the U.S. Department of Energy +(DOE) and The Regents of the University of California (University) for +the operation of UC LLNL. + +DISCLAIMER: This work was prepared as an account of work sponsored by +an agency of the United States Government. Neither the United States +Government nor the University of California nor any of their +employees, makes any warranty, express or implied, or assumes any +liability or responsibility for the accuracy, completeness, or +usefulness of any information, apparatus, product, or process +disclosed, or represents that its use would not infringe privately- +owned rights. Reference herein to any specific commercial products, +process, or service by trade name, trademark, manufacturer, or +otherwise, does not necessarily constitute or imply its endorsement, +recommendation, or favoring by the United States Government or the +University of California. The views and opinions of authors expressed +herein do not necessarily state or reflect those of the United States +Government or the University of California, and shall not be used for +advertising or product endorsement purposes. diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/licenses/license.txt b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/licenses/license.txt new file mode 100644 index 0000000000000000000000000000000000000000..ac98432bd7d27bfe817c29f6b97ff4597c4c7732 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/licenses/license.txt @@ -0,0 +1,34 @@ +Copyright Notice and Statement for the h5py Project +=================================================== + + Copyright (c) 2008-2013 Andrew Collette and contributors + http://www.h5py.org + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + a. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + b. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the + distribution. + + c. Neither the name of the author nor the names of contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/licenses/pytables.txt b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/licenses/pytables.txt new file mode 100644 index 0000000000000000000000000000000000000000..9f2f482c1bdcc7fe4930c79c0d65be5e84d4fbdf --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/licenses/pytables.txt @@ -0,0 +1,33 @@ +Copyright Notice and Statement for PyTables Software Library and Utilities: + +Copyright (c) 2002, 2003, 2004 Francesc Altet +Copyright (c) 2005, 2006, 2007 Carabos Coop. V. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +a. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +b. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the + distribution. + +c. Neither the name of the Carabos Coop. V. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/licenses/python.txt b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/licenses/python.txt new file mode 100644 index 0000000000000000000000000000000000000000..1d49873f2d99aa547a695ba2733bcfe068e3fdec --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/licenses/python.txt @@ -0,0 +1,44 @@ +Python license +============== + +#. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and + the Individual or Organization ("Licensee") accessing and otherwise using Python + Python 2.7.5 software in source or binary form and its associated documentation. + +#. Subject to the terms and conditions of this License Agreement, PSF hereby + grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, + analyze, test, perform and/or display publicly, prepare derivative works, + distribute, and otherwise use Python Python 2.7.5 alone or in any derivative + version, provided, however, that PSF's License Agreement and PSF's notice of + copyright, i.e., "Copyright 2001-2013 Python Software Foundation; All Rights + Reserved" are retained in Python Python 2.7.5 alone or in any derivative version + prepared by Licensee. + +#. In the event Licensee prepares a derivative work that is based on or + incorporates Python Python 2.7.5 or any part thereof, and wants to make the + derivative work available to others as provided herein, then Licensee hereby + agrees to include in any such work a brief summary of the changes made to Python + Python 2.7.5. + +#. PSF is making Python Python 2.7.5 available to Licensee on an "AS IS" basis. + PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF + EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR + WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE + USE OF PYTHON Python 2.7.5 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. + +#. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON Python 2.7.5 + FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF + MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON Python 2.7.5, OR ANY DERIVATIVE + THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +#. This License Agreement will automatically terminate upon a material breach of + its terms and conditions. + +#. Nothing in this License Agreement shall be deemed to create any relationship + of agency, partnership, or joint venture between PSF and Licensee. This License + Agreement does not grant permission to use PSF trademarks or trade name in a + trademark sense to endorse or promote products or services of Licensee, or any + third party. + +#. By copying, installing or otherwise using Python Python 2.7.5, Licensee agrees + to be bound by the terms and conditions of this License Agreement. diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/licenses/stdint.txt b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/licenses/stdint.txt new file mode 100644 index 0000000000000000000000000000000000000000..be8a46bc0ef5bc23abc088774cb7fd4cbb0c60b7 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/licenses/stdint.txt @@ -0,0 +1,25 @@ +Copyright (c) 2006-2008 Alexander Chemeris + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The name of the author may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/lzf/LICENSE.txt b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/lzf/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..41cf84d3647838aae518d19e0d8042fb3a488e30 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/licenses/lzf/LICENSE.txt @@ -0,0 +1,33 @@ +Copyright Notice and Statement for LZF filter + +Copyright (c) 2008-2009 Andrew Collette +http://h5py.org +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +a. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +b. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the + distribution. + +c. Neither the name of the author nor the names of contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/top_level.txt b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..c5a4eac431789a52d7f7d521a84937511cdc400c --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py-3.15.1.dist-info/top_level.txt @@ -0,0 +1 @@ +h5py diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libaec-187855bc.so.0.1.3 b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libaec-187855bc.so.0.1.3 new file mode 100644 index 0000000000000000000000000000000000000000..907517037df7608040c36374320222b7763505b1 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libaec-187855bc.so.0.1.3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:894394b9fe4cbf55faca95c800252210afbf0b34d63fbb44bc022c8d49fde0df +size 136561 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libhdf5-7d060e2f.so.310.5.1 b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libhdf5-7d060e2f.so.310.5.1 new file mode 100644 index 0000000000000000000000000000000000000000..801d403b8524c20fbf6caeee915a7bda6a305086 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libhdf5-7d060e2f.so.310.5.1 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0df8734d73c4492ad1d27c55a9c9d4cfffa1d2fa872b6d3b621ef487d35c871f +size 4975937 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libhdf5_hl-0ce065ed.so.310.0.6 b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libhdf5_hl-0ce065ed.so.310.0.6 new file mode 100644 index 0000000000000000000000000000000000000000..725e2984996274f86a55167dca4660d6c2c71b1e --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libhdf5_hl-0ce065ed.so.310.0.6 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e774d6d5c6ae95a4f82300a6e062a336be3df18f9c4cff763f9cf762989f62d7 +size 181945 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libsz-daeb5235.so.2.0.1 b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libsz-daeb5235.so.2.0.1 new file mode 100644 index 0000000000000000000000000000000000000000..b1392c732c7d82d8a8c465d4be5024ec6149bc23 Binary files /dev/null and b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py.libs/libsz-daeb5235.so.2.0.1 differ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..20d11225db969eae06814842ce8e3cf746dd745b --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/__init__.py @@ -0,0 +1,115 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + This is the h5py package, a Python interface to the HDF5 + scientific data format. +""" + +from warnings import warn as _warn +import atexit + + +# --- Library setup ----------------------------------------------------------- + +# When importing from the root of the unpacked tarball or git checkout, +# Python sees the "h5py" source directory and tries to load it, which fails. +# We tried working around this by using "package_dir" but that breaks Cython. +try: + from . import _errors +except ImportError: + import os.path as _op + if _op.exists(_op.join(_op.dirname(__file__), '..', 'setup.py')): + raise ImportError("You cannot import h5py from inside the install directory.\nChange to another directory first.") + else: + raise + +from . import version + +if version.hdf5_version_tuple != version.hdf5_built_version_tuple: + _warn(("h5py is running against HDF5 {0} when it was built against {1}, " + "this may cause problems").format( + '{0}.{1}.{2}'.format(*version.hdf5_version_tuple), + '{0}.{1}.{2}'.format(*version.hdf5_built_version_tuple) + )) + + +_errors.silence_errors() + +from ._conv import register_converters as _register_converters, \ + unregister_converters as _unregister_converters +_register_converters() +atexit.register(_unregister_converters) + +from .h5z import _register_lzf +_register_lzf() + + +# --- Public API -------------------------------------------------------------- + +from . import h5a, h5d, h5ds, h5f, h5fd, h5g, h5r, h5s, h5t, h5p, h5z, h5pl + +from ._hl import filters +from ._hl.base import is_hdf5, HLObject, Empty +from ._hl.files import ( + File, + register_driver, + unregister_driver, + registered_drivers, +) +from ._hl.group import Group, SoftLink, ExternalLink, HardLink +from ._hl.dataset import Dataset +from ._hl.datatype import Datatype +from ._hl.attrs import AttributeManager +from ._hl.vds import VirtualSource, VirtualLayout + +from ._selector import MultiBlockSlice +from .h5 import get_config +from .h5r import Reference, RegionReference +from .h5t import (special_dtype, check_dtype, + vlen_dtype, string_dtype, enum_dtype, ref_dtype, regionref_dtype, + opaque_dtype, + check_vlen_dtype, check_string_dtype, check_enum_dtype, check_ref_dtype, + check_opaque_dtype, +) +from .h5s import UNLIMITED + +from .version import version as __version__ + + +def run_tests(args=''): + """Run tests with pytest and returns the exit status as an int. + """ + # Lazy-loading of tests package to avoid strong dependency on test + # requirements, e.g. pytest + from .tests import run_tests + return run_tests(args) + + +def enable_ipython_completer(): + """ Call this from an interactive IPython session to enable tab-completion + of group and attribute names. + """ + import sys + if 'IPython' in sys.modules: + ip_running = False + try: + from IPython.core.interactiveshell import InteractiveShell + ip_running = InteractiveShell.initialized() + except ImportError: + # support .attrs. +""" + +import numpy + +from .. import h5, h5s, h5t, h5a, h5p +from . import base +from .base import phil, with_phil, Empty, is_empty_dataspace, product +from .datatype import Datatype + + +class AttributeManager(base.MutableMappingHDF5, base.CommonStateObject): + + """ + Allows dictionary-style access to an HDF5 object's attributes. + + These are created exclusively by the library and are available as + a Python attribute at .attrs + + Like Group objects, attributes provide a minimal dictionary- + style interface. Anything which can be reasonably converted to a + Numpy array or Numpy scalar can be stored. + + Attributes are automatically created on assignment with the + syntax .attrs[name] = value, with the HDF5 type automatically + deduced from the value. Existing attributes are overwritten. + + To modify an existing attribute while preserving its type, use the + method modify(). To specify an attribute of a particular type and + shape, use create(). + """ + + def __init__(self, parent): + """ Private constructor. + """ + self._id = parent.id + + @with_phil + def __getitem__(self, name): + """ Read the value of an attribute. + """ + attr = h5a.open(self._id, self._e(name)) + shape = attr.shape + + # shape is None for empty dataspaces + if shape is None: + return Empty(attr.dtype) + + dtype = attr.dtype + + # Do this first, as we'll be fiddling with the dtype for top-level + # array types + htype = h5t.py_create(dtype) + + # NumPy doesn't support top-level array types, so we have to "fake" + # the correct type and shape for the array. For example, consider + # attr.shape == (5,) and attr.dtype == '(3,)f'. Then: + if dtype.subdtype is not None: + subdtype, subshape = dtype.subdtype + shape = attr.shape + subshape # (5, 3) + dtype = subdtype # 'f' + + arr = numpy.zeros(shape, dtype=dtype, order='C') + attr.read(arr, mtype=htype) + + string_info = h5t.check_string_dtype(dtype) + if string_info and (string_info.length is None): + # Vlen strings: convert bytes to Python str + arr = numpy.array([ + b.decode('utf-8', 'surrogateescape') for b in arr.flat + ], dtype=dtype).reshape(arr.shape) + + if arr.ndim == 0: + return arr[()] + return arr + + def get_id(self, name): + """Get a low-level AttrID object for the named attribute. + """ + return h5a.open(self._id, self._e(name)) + + @with_phil + def __setitem__(self, name, value): + """ Set a new attribute, overwriting any existing attribute. + + The type and shape of the attribute are determined from the data. To + use a specific type or shape, or to preserve the type of an attribute, + use the methods create() and modify(). + """ + self.create(name, data=value) + + @with_phil + def __delitem__(self, name): + """ Delete an attribute (which must already exist). """ + h5a.delete(self._id, self._e(name)) + + def create(self, name, data, shape=None, dtype=None): + """ Create a new attribute, overwriting any existing attribute. + + name + Name of the new attribute (required) + data + An array to initialize the attribute (required) + shape + Shape of the attribute. Overrides data.shape if both are + given, in which case the total number of points must be unchanged. + dtype + Data type of the attribute. Overrides data.dtype if both + are given. + """ + name = self._e(name) + + with phil: + # First, make sure we have a NumPy array. We leave the data type + # conversion for HDF5 to perform. + if not isinstance(data, Empty): + data = base.array_for_new_object(data, specified_dtype=dtype) + + if shape is None: + shape = data.shape + elif isinstance(shape, int): + shape = (shape,) + + use_htype = None # If a committed type is given, we must use it + # in the call to h5a.create. + + if isinstance(dtype, Datatype): + use_htype = dtype.id + dtype = dtype.dtype + elif dtype is None: + dtype = data.dtype + else: + dtype = numpy.dtype(dtype) # In case a string, e.g. 'i8' is passed + + original_dtype = dtype # We'll need this for top-level array types + + # Where a top-level array type is requested, we have to do some + # fiddling around to present the data as a smaller array of + # subarrays. + if dtype.subdtype is not None: + + subdtype, subshape = dtype.subdtype + + # Make sure the subshape matches the last N axes' sizes. + if shape[-len(subshape):] != subshape: + raise ValueError("Array dtype shape %s is incompatible with data shape %s" % (subshape, shape)) + + # New "advertised" shape and dtype + shape = shape[0:len(shape)-len(subshape)] + dtype = subdtype + + # Not an array type; make sure to check the number of elements + # is compatible, and reshape if needed. + else: + + if shape is not None and product(shape) != product(data.shape): + raise ValueError("Shape of new attribute conflicts with shape of data") + + if shape != data.shape: + data = data.reshape(shape) + + # We need this to handle special string types. + if not isinstance(data, Empty): + data = numpy.asarray(data, dtype=dtype) + + # Make HDF5 datatype and dataspace for the H5A calls + if use_htype is None: + htype = h5t.py_create(original_dtype, logical=True) + htype2 = h5t.py_create(original_dtype) # Must be bit-for-bit representation rather than logical + else: + htype = use_htype + htype2 = None + + if isinstance(data, Empty): + space = h5s.create(h5s.NULL) + else: + space = h5s.create_simple(shape) + + # For a long time, h5py would create attributes with a random name + # and then rename them, imitating how you can atomically replace + # a file in a filesystem. But HDF5 does not offer atomic replacement + # (you have to delete the existing attribute first), and renaming + # exposes some bugs - see https://github.com/h5py/h5py/issues/1385 + # So we've gone back to the simpler delete & recreate model. + if h5a.exists(self._id, name): + h5a.delete(self._id, name) + + attr = h5a.create(self._id, name, htype, space) + try: + if not isinstance(data, Empty): + attr.write(data, mtype=htype2) + except: + attr.close() + h5a.delete(self._id, name) + raise + attr.close() + + def modify(self, name, value): + """ Change the value of an attribute while preserving its type. + + Differs from __setitem__ in that if the attribute already exists, its + type is preserved. This can be very useful for interacting with + externally generated files. + + If the attribute doesn't exist, it will be automatically created. + """ + with phil: + if not name in self: + self[name] = value + else: + attr = h5a.open(self._id, self._e(name)) + + if is_empty_dataspace(attr): + raise OSError("Empty attributes can't be modified") + + # If the input data is already an array, let HDF5 do the conversion. + # If it's a list or similar, don't make numpy guess a dtype for it. + dt = None if isinstance(value, numpy.ndarray) else attr.dtype + value = numpy.asarray(value, order='C', dtype=dt) + + # Allow the case of () <-> (1,) + if (value.shape != attr.shape) and not \ + (value.size == 1 and product(attr.shape) == 1): + raise TypeError("Shape of data is incompatible with existing attribute") + attr.write(value) + + @with_phil + def __len__(self): + """ Number of attributes attached to the object. """ + # I expect we will not have more than 2**32 attributes + return h5a.get_num_attrs(self._id) + + def __iter__(self): + """ Iterate over the names of attributes. """ + with phil: + + attrlist = [] + def iter_cb(name, *args): + """ Callback to gather attribute names """ + attrlist.append(self._d(name)) + + cpl = self._id.get_create_plist() + crt_order = cpl.get_attr_creation_order() + cpl.close() + if crt_order & h5p.CRT_ORDER_TRACKED: + idx_type = h5.INDEX_CRT_ORDER + else: + idx_type = h5.INDEX_NAME + + h5a.iterate(self._id, iter_cb, index_type=idx_type) + + for name in attrlist: + yield name + + @with_phil + def __contains__(self, name): + """ Determine if an attribute exists, by name. """ + return h5a.exists(self._id, self._e(name)) + + @with_phil + def __repr__(self): + if not self._id: + return "" + return "" % id(self._id) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/base.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/base.py new file mode 100644 index 0000000000000000000000000000000000000000..e11642f665c718345ec2fce481f3a37dd6d98847 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/base.py @@ -0,0 +1,535 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Implements operations common to all high-level objects (File, etc.). +""" + +from collections.abc import ( + Mapping, MutableMapping, KeysView, ValuesView, ItemsView +) +import os +import posixpath + +import numpy as np + +# The high-level interface is serialized; every public API function & method +# is wrapped in a lock. We reuse the low-level lock because (1) it's fast, +# and (2) it eliminates the possibility of deadlocks due to out-of-order +# lock acquisition. +from .._objects import phil, with_phil +from .. import h5d, h5i, h5r, h5p, h5f, h5t, h5s +from .compat import filename_encode + + +def is_hdf5(fname): + """ Determine if a file is valid HDF5 (False if it doesn't exist). """ + with phil: + fname = os.path.abspath(os.fspath(fname)) + + if os.path.isfile(fname): + return h5f.is_hdf5(filename_encode(fname)) + return False + + +def find_item_type(data): + """Find the item type of a simple object or collection of objects. + + E.g. [[['a']]] -> str + + The focus is on collections where all items have the same type; we'll return + None if that's not the case. + + The aim is to treat numpy arrays of Python objects like normal Python + collections, while treating arrays with specific dtypes differently. + We're also only interested in array-like collections - lists and tuples, + possibly nested - not things like sets or dicts. + """ + if isinstance(data, np.ndarray): + if ( + data.dtype.kind == 'O' + and not h5t.check_string_dtype(data.dtype) + and not h5t.check_vlen_dtype(data.dtype) + ): + item_types = {type(e) for e in data.flat} + else: + return None + elif isinstance(data, (list, tuple)): + item_types = {find_item_type(e) for e in data} + else: + return type(data) + + if len(item_types) != 1: + return None + return item_types.pop() + + +def guess_dtype(data): + """ Attempt to guess an appropriate dtype for the object, returning None + if nothing is appropriate (or if it should be left up the the array + constructor to figure out) + """ + with phil: + if isinstance(data, h5r.RegionReference): + return h5t.regionref_dtype + if isinstance(data, h5r.Reference): + return h5t.ref_dtype + + item_type = find_item_type(data) + + if item_type is bytes: + return h5t.string_dtype(encoding='ascii') + if item_type is str: + return h5t.string_dtype() + + return None + + +def is_float16_dtype(dt): + if dt is None: + return False + + dt = np.dtype(dt) # normalize strings -> np.dtype objects + return dt.kind == 'f' and dt.itemsize == 2 + + +def array_for_new_object(data, specified_dtype=None): + """Prepare an array from data used to create a new dataset or attribute""" + + if not isinstance(specified_dtype, (np.dtype, type(None))): + specified_dtype = np.dtype(specified_dtype) + + # We mostly let HDF5 convert data as necessary when it's written. + # But if we are going to a float16 datatype, pre-convert in python + # to workaround a bug in the conversion. + # https://github.com/h5py/h5py/issues/819 + if is_float16_dtype(specified_dtype): + as_dtype = specified_dtype + elif not isinstance(data, np.ndarray) and (specified_dtype is not None): + # If we need to convert e.g. a list to an array, don't leave numpy + # to guess a dtype we already know. + as_dtype = specified_dtype + else: + as_dtype = guess_dtype(data) + + data = np.asarray(data, order="C", dtype=as_dtype) + + # In most cases, this does nothing. But if data was already an array, + # and as_dtype is a tagged h5py dtype (e.g. for an object array of strings), + # asarray() doesn't replace its dtype object. This gives it the tagged dtype: + if as_dtype is not None: + data = data.view(dtype=as_dtype) + + return data + + +def default_lapl(): + """ Default link access property list """ + return None + + +def default_lcpl(): + """ Default link creation property list """ + lcpl = h5p.create(h5p.LINK_CREATE) + lcpl.set_create_intermediate_group(True) + return lcpl + +dlapl = default_lapl() +dlcpl = default_lcpl() + + +def is_empty_dataspace(obj): + """ Check if an object's dataspace is empty """ + if obj.get_space().get_simple_extent_type() == h5s.NULL: + return True + return False + + +class CommonStateObject: + + """ + Mixin class that allows sharing information between objects which + reside in the same HDF5 file. Requires that the host class have + a ".id" attribute which returns a low-level ObjectID subclass. + + Also implements Unicode operations. + """ + + @property + def _lapl(self): + """ Fetch the link access property list appropriate for this object + """ + return dlapl + + @property + def _lcpl(self): + """ Fetch the link creation property list appropriate for this object + """ + return dlcpl + + def _e(self, name, lcpl=None): + """ Encode a name according to the current file settings. + + Returns name, or 2-tuple (name, lcpl) if lcpl is True + + - Binary strings are always passed as-is, h5t.CSET_ASCII + - Unicode strings are encoded utf8, h5t.CSET_UTF8 + + If name is None, returns either None or (None, None) appropriately. + """ + def get_lcpl(coding): + """ Create an appropriate link creation property list """ + lcpl = self._lcpl.copy() + lcpl.set_char_encoding(coding) + return lcpl + + if name is None: + return (None, None) if lcpl else None + + if isinstance(name, bytes): + coding = h5t.CSET_ASCII + elif isinstance(name, str): + try: + name = name.encode('ascii') + coding = h5t.CSET_ASCII + except UnicodeEncodeError: + name = name.encode('utf8') + coding = h5t.CSET_UTF8 + else: + raise TypeError(f"A name should be string or bytes, not {type(name)}") + + if lcpl: + return name, get_lcpl(coding) + return name + + def _d(self, name): + """ Decode a name according to the current file settings. + + - Try to decode utf8 + - Failing that, return the byte string + + If name is None, returns None. + """ + if name is None: + return None + + try: + return name.decode('utf8') + except UnicodeDecodeError: + pass + return name + + +class _RegionProxy: + + """ + Proxy object which handles region references. + + To create a new region reference (datasets only), use slicing syntax: + + >>> newref = obj.regionref[0:10:2] + + To determine the target dataset shape from an existing reference: + + >>> shape = obj.regionref.shape(existingref) + + where may be any object in the file. To determine the shape of + the selection in use on the target dataset: + + >>> selection_shape = obj.regionref.selection(existingref) + """ + + def __init__(self, obj): + self.obj = obj + self.id = obj.id + + def __getitem__(self, args): + if not isinstance(self.id, h5d.DatasetID): + raise TypeError("Region references can only be made to datasets") + from . import selections + with phil: + selection = selections.select(self.id.shape, args, dataset=self.obj) + return h5r.create(self.id, b'.', h5r.DATASET_REGION, selection.id) + + def shape(self, ref): + """ Get the shape of the target dataspace referred to by *ref*. """ + with phil: + sid = h5r.get_region(ref, self.id) + return sid.shape + + def selection(self, ref): + """ Get the shape of the target dataspace selection referred to by *ref* + """ + from . import selections + with phil: + sid = h5r.get_region(ref, self.id) + return selections.guess_shape(sid) + + +class HLObject(CommonStateObject): + + """ + Base class for high-level interface objects. + """ + + @property + def file(self): + """ Return a File instance associated with this object """ + from . import files + with phil: + return files.File(self.id) + + @property + @with_phil + def name(self): + """ Return the full name of this object. None if anonymous. """ + return self._d(h5i.get_name(self.id)) + + @property + @with_phil + def parent(self): + """Return the parent group of this object. + + This is always equivalent to obj.file[posixpath.dirname(obj.name)]. + ValueError if this object is anonymous. + """ + if self.name is None: + raise ValueError("Parent of an anonymous object is undefined") + return self.file[posixpath.dirname(self.name)] + + @property + @with_phil + def id(self): + """ Low-level identifier appropriate for this object """ + return self._id + + @property + @with_phil + def ref(self): + """ An (opaque) HDF5 reference to this object """ + return h5r.create(self.id, b'.', h5r.OBJECT) + + @property + @with_phil + def regionref(self): + """Create a region reference (Datasets only). + + The syntax is regionref[]. For example, dset.regionref[...] + creates a region reference in which the whole dataset is selected. + + Can also be used to determine the shape of the referenced dataset + (via .shape property), or the shape of the selection (via the + .selection property). + """ + return _RegionProxy(self) + + @property + def attrs(self): + """ Attributes attached to this object """ + from . import attrs + with phil: + return attrs.AttributeManager(self) + + @with_phil + def __init__(self, oid): + """ Setup this object, given its low-level identifier """ + self._id = oid + + @with_phil + def __hash__(self): + return hash(self.id) + + @with_phil + def __eq__(self, other): + if hasattr(other, 'id'): + return self.id == other.id + return NotImplemented + + def __bool__(self): + with phil: + return bool(self.id) + + def __getnewargs__(self): + """Disable pickle. + + Handles for HDF5 objects can't be reliably deserialised, because the + recipient may not have access to the same files. So we do this to + fail early. + + If you really want to pickle h5py objects and can live with some + limitations, look at the h5pickle project on PyPI. + """ + raise TypeError("h5py objects cannot be pickled") + + def __getstate__(self): + # Pickle protocols 0 and 1 use this instead of __getnewargs__ + raise TypeError("h5py objects cannot be pickled") + +# --- Dictionary-style interface ---------------------------------------------- + +# To implement the dictionary-style interface from groups and attributes, +# we inherit from the appropriate abstract base classes in collections. +# +# All locking is taken care of by the subclasses. +# We have to override ValuesView and ItemsView here because Group and +# AttributeManager can only test for key names. + + +class KeysViewHDF5(KeysView): + def __str__(self): + return "".format(list(self)) + + def __reversed__(self): + yield from reversed(self._mapping) + + __repr__ = __str__ + +class ValuesViewHDF5(ValuesView): + + """ + Wraps e.g. a Group or AttributeManager to provide a value view. + + Note that __contains__ will have poor performance as it has + to scan all the links or attributes. + """ + + def __contains__(self, value): + with phil: + for key in self._mapping: + if value == self._mapping.get(key): + return True + return False + + def __iter__(self): + with phil: + for key in self._mapping: + yield self._mapping.get(key) + + def __reversed__(self): + with phil: + for key in reversed(self._mapping): + yield self._mapping.get(key) + + +class ItemsViewHDF5(ItemsView): + + """ + Wraps e.g. a Group or AttributeManager to provide an items view. + """ + + def __contains__(self, item): + with phil: + key, val = item + if key in self._mapping: + return val == self._mapping.get(key) + return False + + def __iter__(self): + with phil: + for key in self._mapping: + yield (key, self._mapping.get(key)) + + def __reversed__(self): + with phil: + for key in reversed(self._mapping): + yield (key, self._mapping.get(key)) + + +class MappingHDF5(Mapping): + + """ + Wraps a Group, AttributeManager or DimensionManager object to provide + an immutable mapping interface. + + We don't inherit directly from MutableMapping because certain + subclasses, for example DimensionManager, are read-only. + """ + def keys(self): + """ Get a view object on member names """ + return KeysViewHDF5(self) + + def values(self): + """ Get a view object on member objects """ + return ValuesViewHDF5(self) + + def items(self): + """ Get a view object on member items """ + return ItemsViewHDF5(self) + + def _ipython_key_completions_(self): + """ Custom tab completions for __getitem__ in IPython >=5.0. """ + return sorted(self.keys()) + + +class MutableMappingHDF5(MappingHDF5, MutableMapping): + + """ + Wraps a Group or AttributeManager object to provide a mutable + mapping interface, in contrast to the read-only mapping of + MappingHDF5. + """ + + pass + + +class Empty: + + """ + Proxy object to represent empty/null dataspaces (a.k.a H5S_NULL). + + This can have an associated dtype, but has no shape or data. This is not + the same as an array with shape (0,). + """ + shape = None + size = None + + def __init__(self, dtype): + self.dtype = np.dtype(dtype) + + def __eq__(self, other): + if isinstance(other, Empty) and self.dtype == other.dtype: + return True + return False + + def __repr__(self): + return "Empty(dtype={0!r})".format(self.dtype) + + +def product(nums): + """Calculate a numeric product + + For small amounts of data (e.g. shape tuples), this simple code is much + faster than calling numpy.prod(). + """ + prod = 1 + for n in nums: + prod *= n + return prod + + +# Simple variant of cached_property: +# Unlike functools, this has no locking, so we don't have to worry about +# deadlocks with phil (see issue gh-2064). Unlike cached-property on PyPI, it +# doesn't try to import asyncio (which can be ~100 extra modules). +# Many projects seem to have similar variants of this, often without attribution, +# but to be cautious, this code comes from cached-property (Copyright (c) 2015, +# Daniel Greenfeld, BSD license), where it is attributed to bottle (Copyright +# (c) 2009-2022, Marcel Hellkamp, MIT license). + +class cached_property: + def __init__(self, func): + self.__doc__ = getattr(func, "__doc__") + self.func = func + + def __get__(self, obj, cls): + if obj is None: + return self + + value = obj.__dict__[self.func.__name__] = self.func(obj) + return value diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/compat.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..29ec1fcd572db6ef0fe138e7a988dce8911c0d0c --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/compat.py @@ -0,0 +1,46 @@ +""" +Compatibility module for high-level h5py +""" +import os +import sys +from ..version import hdf5_built_version_tuple + +# HDF5 supported passing paths as UTF-8 for Windows from 1.10.6, but this +# was broken again in 1.14.4 - https://github.com/HDFGroup/hdf5/issues/5037 . +# The change was reverted in 1.14.6. +if (1, 14, 4) <= hdf5_built_version_tuple < (1, 14, 6): + WINDOWS_ENCODING = "mbcs" +else: + WINDOWS_ENCODING = "utf-8" + + +def filename_encode(filename): + """ + Encode filename for use in the HDF5 library. + + Due to how HDF5 handles filenames on different systems, this should be + called on any filenames passed to the HDF5 library. See the documentation on + filenames in h5py for more information. + """ + filename = os.fspath(filename) + if sys.platform == "win32" and isinstance(filename, str): + return filename.encode(WINDOWS_ENCODING, "strict") + else: + return os.fsencode(filename) + + +def filename_decode(filename): + """ + Decode filename used by HDF5 library. + + Due to how HDF5 handles filenames on different systems, this should be + called on any filenames passed from the HDF5 library. See the documentation + on filenames in h5py for more information. + """ + if not isinstance(filename, (str, bytes)): + raise TypeError(f"expect bytes or str, not {type(filename).__name__}") + + if sys.platform == "win32" and isinstance(filename, bytes): + return filename.decode(WINDOWS_ENCODING, "strict") + else: + return os.fsdecode(filename) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/dataset.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..b8e3d0866fafbe77bbba9ee5d24893259d15b829 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/dataset.py @@ -0,0 +1,1223 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2020 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Implements support for high-level dataset access. +""" + +import posixpath as pp +import sys +from abc import ABC, abstractmethod + +import numpy + +from .. import h5, h5s, h5t, h5r, h5d, h5p, h5fd, h5ds, _selector +from .base import ( + array_for_new_object, cached_property, Empty, find_item_type, HLObject, + phil, product, with_phil, +) +from . import filters +from . import selections as sel +from . import selections2 as sel2 +from .datatype import Datatype +from .compat import filename_decode +from .vds import VDSmap, vds_support + +_LEGACY_GZIP_COMPRESSION_VALS = frozenset(range(10)) +MPI = h5.get_config().mpi + + +def make_new_dset(parent, shape=None, dtype=None, data=None, name=None, + chunks=None, compression=None, shuffle=None, + fletcher32=None, maxshape=None, compression_opts=None, + fillvalue=None, scaleoffset=None, track_times=False, + external=None, track_order=None, dcpl=None, dapl=None, + efile_prefix=None, virtual_prefix=None, allow_unknown_filter=False, + rdcc_nslots=None, rdcc_nbytes=None, rdcc_w0=None, *, + fill_time=None): + """ Return a new low-level dataset identifier """ + + # Convert data to a C-contiguous ndarray + if data is not None and not isinstance(data, Empty): + data = array_for_new_object(data, specified_dtype=dtype) + + # Validate shape + if shape is None: + if data is None: + if dtype is None: + raise TypeError("One of data, shape or dtype must be specified") + data = Empty(dtype) + shape = data.shape + else: + shape = (shape,) if isinstance(shape, int) else tuple(shape) + if data is not None and (product(shape) != product(data.shape)): + raise ValueError("Shape tuple is incompatible with data") + + if isinstance(maxshape, int): + maxshape = (maxshape,) + tmp_shape = maxshape if maxshape is not None else shape + + # Validate chunk shape + if isinstance(chunks, int) and not isinstance(chunks, bool): + chunks = (chunks,) + # Logically, the following `zip` could be strict, but it's happening + # before we've done checks elsewhere that raise more descriptive errors + if isinstance(chunks, tuple) and any( + chunk > dim for dim, chunk in zip(tmp_shape, chunks, strict=False) if dim is not None + ): + errmsg = "Chunk shape must not be greater than data shape in any dimension. "\ + "{} is not compatible with {}".format(chunks, shape) + raise ValueError(errmsg) + + if isinstance(dtype, Datatype): + # Named types are used as-is + tid = dtype.id + dtype = tid.dtype # Following code needs this + else: + # Validate dtype + if dtype is None and data is None: + dtype = numpy.dtype("=f4") + elif dtype is None and data is not None: + dtype = data.dtype + else: + dtype = numpy.dtype(dtype) + tid = h5t.py_create(dtype, logical=1) + + # Legacy + if any((compression, shuffle, fletcher32, maxshape, scaleoffset)) and chunks is False: + raise ValueError("Chunked format required for given storage options") + + # Legacy + if compression is True: + if compression_opts is None: + compression_opts = 4 + compression = 'gzip' + + # Legacy + if compression in _LEGACY_GZIP_COMPRESSION_VALS: + if compression_opts is not None: + raise TypeError("Conflict in compression options") + compression_opts = compression + compression = 'gzip' + dcpl = filters.fill_dcpl( + dcpl or h5p.create(h5p.DATASET_CREATE), shape, dtype, + chunks, compression, compression_opts, shuffle, fletcher32, + maxshape, scaleoffset, external, allow_unknown_filter, + fill_time=fill_time) + + # Check that compression roundtrips correctly if it was specified + if compression is not None: + if isinstance(compression, filters.FilterRefBase): + compression = compression.filter_id + if isinstance(compression, int): + compression = filters.get_filter_name(compression) + if compression not in filters.get_filters(dcpl): + raise ValueError(f'compression {compression!r} not in filters {filters.get_filters(dcpl)!r}') + + if fillvalue is not None: + # prepare string-type dtypes for fillvalue + string_info = h5t.check_string_dtype(dtype) + if string_info is not None: + # fake vlen dtype for fixed len string fillvalue + # to not trigger unwanted encoding + dtype = h5t.string_dtype(string_info.encoding) + fillvalue = numpy.array(fillvalue, dtype=dtype) + else: + fillvalue = numpy.array(fillvalue) + dcpl.set_fill_value(fillvalue) + + if track_times is None: + # In case someone explicitly passes None for the default + track_times = False + if track_times in (True, False): + dcpl.set_obj_track_times(track_times) + else: + raise TypeError("track_times must be either True or False") + if track_order is True: + dcpl.set_attr_creation_order( + h5p.CRT_ORDER_TRACKED | h5p.CRT_ORDER_INDEXED) + elif track_order is False: + dcpl.set_attr_creation_order(0) + elif track_order is not None: + raise TypeError("track_order must be either True or False") + + if maxshape is not None: + maxshape = tuple(m if m is not None else h5s.UNLIMITED for m in maxshape) + + if any([efile_prefix, virtual_prefix, rdcc_nbytes, rdcc_nslots, rdcc_w0]): + dapl = dapl or h5p.create(h5p.DATASET_ACCESS) + + if efile_prefix is not None: + dapl.set_efile_prefix(efile_prefix) + + if virtual_prefix is not None: + dapl.set_virtual_prefix(virtual_prefix) + + if rdcc_nbytes or rdcc_nslots or rdcc_w0: + cache_settings = list(dapl.get_chunk_cache()) + if rdcc_nslots is not None: + cache_settings[0] = rdcc_nslots + if rdcc_nbytes is not None: + cache_settings[1] = rdcc_nbytes + if rdcc_w0 is not None: + cache_settings[2] = rdcc_w0 + dapl.set_chunk_cache(*cache_settings) + + if isinstance(data, Empty): + sid = h5s.create(h5s.NULL) + else: + sid = h5s.create_simple(shape, maxshape) + + dset_id = h5d.create(parent.id, name, tid, sid, dcpl=dcpl, dapl=dapl) + + if (data is not None) and (not isinstance(data, Empty)): + dset_id.write(h5s.ALL, h5s.ALL, data) + + return dset_id + + +def open_dset(parent, name, dapl=None, efile_prefix=None, virtual_prefix=None, + rdcc_nslots=None, rdcc_nbytes=None, rdcc_w0=None, **kwds): + """ Return an existing low-level dataset identifier """ + + if any([efile_prefix, virtual_prefix, rdcc_nbytes, rdcc_nslots, rdcc_w0]): + dapl = dapl or h5p.create(h5p.DATASET_ACCESS) + + if efile_prefix is not None: + dapl.set_efile_prefix(efile_prefix) + + if virtual_prefix is not None: + dapl.set_virtual_prefix(virtual_prefix) + + if rdcc_nbytes or rdcc_nslots or rdcc_w0: + cache_settings = list(dapl.get_chunk_cache()) + if rdcc_nslots is not None: + cache_settings[0] = rdcc_nslots + if rdcc_nbytes is not None: + cache_settings[1] = rdcc_nbytes + if rdcc_w0 is not None: + cache_settings[2] = rdcc_w0 + dapl.set_chunk_cache(*cache_settings) + + dset_id = h5d.open(parent.id, name, dapl=dapl) + + return dset_id + + + +class AbstractView(ABC): + _dset: "Dataset" + + def __init__(self, dset): + self._dset = dset + + def __len__(self): + return len(self._dset) + + @property + @abstractmethod + def dtype(self): + ... # pragma: nocover + + @property + def ndim(self): + return self._dset.ndim + + @property + def shape(self): + return self._dset.shape + + @property + def size(self): + return self._dset.size + + @abstractmethod + def __getitem__(self, idx): + ... # pragma: nocover + + def __array__(self, dtype=None, copy=None): + if copy is False: + raise ValueError( + f"{self.__class__.__name__}.__array__ received {copy=} " + "but memory allocation cannot be avoided on read" + ) + + # If self.ndim == 0, convert np.generic back to np.ndarray + return numpy.asarray(self[()], dtype=dtype or self.dtype) + +class AsTypeView(AbstractView): + """Wrapper to convert data on reading from a dataset. + """ + def __init__(self, dset, dtype): + super().__init__(dset) + self._dtype = dtype + + @property + def dtype(self): + return self._dtype + + def __getitem__(self, idx): + return self._dset.__getitem__(idx, new_dtype=self._dtype) + + def __array__(self, dtype=None, copy=None): + return self._dset.__array__(dtype or self._dtype, copy) + + +class AsStrView(AbstractView): + """Wrapper to decode strings on reading the dataset""" + def __init__(self, dset, encoding, errors='strict'): + super().__init__(dset) + self.encoding = encoding + self.errors = errors + + @property + def dtype(self): + return numpy.dtype(object) + + def __getitem__(self, idx): + bytes_arr = self._dset[idx] + # numpy.char.decode() seems like the obvious thing to use. But it only + # accepts numpy string arrays, not object arrays of bytes (which we + # return from HDF5 variable-length strings). And the numpy + # implementation is not faster than doing it with a loop; in fact, by + # not converting the result to a numpy unicode array, the + # naive way can be faster! (Comparing with numpy 1.18.4, June 2020) + if numpy.isscalar(bytes_arr): + return bytes_arr.decode(self.encoding, self.errors) + + return numpy.array([ + b.decode(self.encoding, self.errors) for b in bytes_arr.flat + ], dtype=object).reshape(bytes_arr.shape) + + +class FieldsView(AbstractView): + """Wrapper to extract named fields from a dataset with a struct dtype""" + + def __init__(self, dset, prior_dtype, names): + super().__init__(dset) + if isinstance(names, str): + self.extract_field = names + names = [names] + else: + self.extract_field = None + self.read_dtype = readtime_dtype(prior_dtype, names) + + @property + def dtype(self): + t = self.read_dtype + if self.extract_field is not None: + t = t[self.extract_field] + return t + + def __getitem__(self, idx): + data = self._dset.__getitem__(idx, new_dtype=self.read_dtype) + if self.extract_field is not None: + data = data[self.extract_field] + return data + + +def readtime_dtype(basetype, names): + """Make a NumPy compound dtype with a subset of available fields""" + if basetype.names is None: # Names provided, but not compound + raise ValueError("Field names only allowed for compound types") + + for name in names: # Check all names are legal + if name not in basetype.names: + raise ValueError("Field %s does not appear in this type." % name) + + return numpy.dtype([(name, basetype.fields[name][0]) for name in names]) + + +if MPI: + class CollectiveContext: + + """ Manages collective I/O in MPI mode """ + + # We don't bother with _local as threads are forbidden in MPI mode + + def __init__(self, dset): + self._dset = dset + + def __enter__(self): + # pylint: disable=protected-access + self._dset._dxpl.set_dxpl_mpio(h5fd.MPIO_COLLECTIVE) + + def __exit__(self, *args): + # pylint: disable=protected-access + self._dset._dxpl.set_dxpl_mpio(h5fd.MPIO_INDEPENDENT) + + +class ChunkIterator: + """ + Class to iterate through list of chunks of a given dataset + """ + def __init__(self, dset, source_sel=None): + self._shape = dset.shape + rank = len(dset.shape) + + if not dset.chunks: + # can only use with chunked datasets + raise TypeError("Chunked dataset required") + + self._layout = dset.chunks + if source_sel is None: + # select over entire dataset + self._sel = tuple( + slice(0, self._shape[dim]) for dim in range(rank) + ) + else: + if isinstance(source_sel, (slice, int)): + sel = [source_sel] + else: + sel = list(source_sel) + if len(sel) != rank: + raise ValueError("Invalid selection - selection region must have same rank as dataset") + for dim, s in enumerate(sel): + start: int | None + stop: int | None + step: int | None + match s: + case int(): + start = s + stop = s + 1 + step = None + case slice(): + start = s.start or 0 + stop = s.stop or self._shape[dim] + step = s.step + case _: + # TODO: use typing.assert_never when Python 3.10 is dropped + raise AssertionError(f'{s}: Selection object must be a slice or integer') + sel[dim] = slice(start, stop, step) + self._sel = tuple(sel) + + self._chunk_index = [] + for dim in range(rank): + s = self._sel[dim] + if s.start < 0 or s.stop > self._shape[dim] or s.stop <= s.start: + raise ValueError("Invalid selection - selection region must be within dataset space") + index = s.start // self._layout[dim] + self._chunk_index.append(index) + + def __iter__(self): + return self + + def __next__(self): + rank = len(self._shape) + slices = [] + if rank == 0 or self._chunk_index[0] * self._layout[0] >= self._sel[0].stop: + # ran past the last chunk, end iteration + raise StopIteration() + + for dim in range(rank): + s = self._sel[dim] + start = self._chunk_index[dim] * self._layout[dim] + stop = (self._chunk_index[dim] + 1) * self._layout[dim] + # adjust the start if this is an edge chunk + if start < s.start: + start = s.start + if stop > s.stop: + stop = s.stop # trim to end of the selection + s = slice(start, stop, 1) + slices.append(s) + + # bump up the last index and carry forward if we run outside the selection + dim = rank - 1 + while dim >= 0: + s = self._sel[dim] + self._chunk_index[dim] += 1 + + chunk_end = self._chunk_index[dim] * self._layout[dim] + if chunk_end < s.stop: + # we still have room to extend along this dimensions + return tuple(slices) + + if dim > 0: + # reset to the start and continue iterating with higher dimension + self._chunk_index[dim] = s.start // self._layout[dim] + dim -= 1 + return tuple(slices) + + +class Dataset(HLObject): + + """ + Represents an HDF5 dataset + """ + + def astype(self, dtype): + """ Get a wrapper allowing you to perform reads to a + different destination type, e.g.: + + >>> double_precision = dataset.astype('f8')[0:100:2] + """ + dtype = numpy.dtype(dtype) + if dtype == self.dtype: + return self + + if dtype.kind == "T": + string_info = h5t.check_string_dtype(self.dtype) + if string_info is None: + raise TypeError( + f"dset.astype({dtype}) can only be used on datasets with " + "an HDF5 string datatype" + ) + + return AsTypeView(self, dtype) + + def asstr(self, encoding=None, errors='strict'): + """Get a wrapper to read string data as Python strings: + + >>> str_array = dataset.asstr()[:] + + The parameters have the same meaning as in ``bytes.decode()``. + If ``encoding`` is unspecified, it will use the encoding in the HDF5 + datatype (either ascii or utf-8). + + .. note:: + On NumPy 2.0 and later, it is recommended to use native NumPy + variable-width strings instead: + + >>> str_array = dataset.astype('T')[:] + """ + string_info = h5t.check_string_dtype(self.dtype) + if string_info is None: + raise TypeError( + "dset.asstr() can only be used on datasets with " + "an HDF5 string datatype" + ) + if encoding is None: + encoding = string_info.encoding + return AsStrView(self, encoding, errors=errors) + + def fields(self, names, *, _prior_dtype=None): + """Get a wrapper to read a subset of fields from a compound data type: + + >>> 2d_coords = dataset.fields(['x', 'y'])[:] + + If names is a string, a single field is extracted, and the resulting + arrays will have that dtype. Otherwise, it should be an iterable, + and the read data will have a compound dtype. + """ + if _prior_dtype is None: + _prior_dtype = self.dtype + return FieldsView(self, _prior_dtype, names) + + if MPI: + @property + @with_phil + def collective(self): + """ Context manager for MPI collective reads & writes """ + return CollectiveContext(self) + + @property + def dims(self): + """ Access dimension scales attached to this dataset. """ + from .dims import DimensionManager + with phil: + return DimensionManager(self) + + @property + @with_phil + def ndim(self): + """Numpy-style attribute giving the number of dimensions""" + return self.id.rank + + @property + def shape(self): + """Numpy-style shape tuple giving dataset dimensions""" + if 'shape' in self._cache_props: + return self._cache_props['shape'] + + with phil: + shape = self.id.shape + + # If the file is read-only, cache the shape to speed-up future uses. + # This cache is invalidated by .refresh() when using SWMR. + if self._readonly: + self._cache_props['shape'] = shape + return shape + + @shape.setter + @with_phil + def shape(self, shape): + # pylint: disable=missing-docstring + self.resize(shape) + + @property + def size(self): + """Numpy-style attribute giving the total dataset size""" + if 'size' in self._cache_props: + return self._cache_props['size'] + + if self._is_empty: + size = None + else: + size = product(self.shape) + + # If the file is read-only, cache the size to speed-up future uses. + # This cache is invalidated by .refresh() when using SWMR. + if self._readonly: + self._cache_props['size'] = size + return size + + @property + def nbytes(self): + """Numpy-style attribute giving the raw dataset size as the number of bytes""" + size = self.size + if size is None: # if we are an empty 0-D array, then there are no bytes in the dataset + return 0 + return self.dtype.itemsize * size + + @property + def _selector(self): + """Internal object for optimised selection of data""" + if '_selector' in self._cache_props: + return self._cache_props['_selector'] + + slr = _selector.Selector(self.id.get_space()) + + # If the file is read-only, cache the reader to speed up future uses. + # This cache is invalidated by .refresh() when using SWMR. + if self._readonly: + self._cache_props['_selector'] = slr + return slr + + @property + def _fast_reader(self): + """Internal object for optimised reading of data""" + if '_fast_reader' in self._cache_props: + return self._cache_props['_fast_reader'] + + rdr = _selector.Reader(self.id) + + # If the file is read-only, cache the reader to speed up future uses. + # This cache is invalidated by .refresh() when using SWMR. + if self._readonly: + self._cache_props['_fast_reader'] = rdr + return rdr + + @property + @with_phil + def dtype(self): + """Numpy dtype representing the datatype""" + return self.id.dtype + + @property + @with_phil + def chunks(self): + """Dataset chunks (or None)""" + dcpl = self._dcpl + if dcpl.get_layout() == h5d.CHUNKED: + return dcpl.get_chunk() + return None + + @property + @with_phil + def compression(self): + """Compression strategy (or None)""" + for x in ('gzip','lzf','szip'): + if x in self._filters: + return x + return None + + @property + @with_phil + def compression_opts(self): + """ Compression setting. Int(0-9) for gzip, 2-tuple for szip. """ + return self._filters.get(self.compression, None) + + @property + @with_phil + def shuffle(self): + """Shuffle filter present (T/F)""" + return 'shuffle' in self._filters + + @property + @with_phil + def fletcher32(self): + """Fletcher32 filter is present (T/F)""" + return 'fletcher32' in self._filters + + @property + @with_phil + def scaleoffset(self): + """Scale/offset filter settings. For integer data types, this is + the number of bits stored, or 0 for auto-detected. For floating + point data types, this is the number of decimal places retained. + If the scale/offset filter is not in use, this is None.""" + try: + return self._filters['scaleoffset'][1] + except KeyError: + return None + + @property + @with_phil + def external(self): + """External file settings. Returns a list of tuples of + (name, offset, size) for each external file entry, or returns None + if no external files are used.""" + count = self._dcpl.get_external_count() + if count<=0: + return None + ext_list = list() + for x in range(count): + (name, offset, size) = self._dcpl.get_external(x) + ext_list.append( (filename_decode(name), offset, size) ) + return ext_list + + @property + @with_phil + def maxshape(self): + """Shape up to which this dataset can be resized. Axes with value + None have no resize limit. """ + space = self.id.get_space() + dims = space.get_simple_extent_dims(True) + if dims is None: + return None + + return tuple(x if x != h5s.UNLIMITED else None for x in dims) + + @property + @with_phil + def fillvalue(self): + """Fill value for this dataset (0 by default)""" + arr = numpy.zeros((1,), dtype=self.dtype) + self._dcpl.get_fill_value(arr) + return arr[0] + + @cached_property + @with_phil + def _extent_type(self): + """Get extent type for this dataset - SIMPLE, SCALAR or NULL""" + return self.id.get_space().get_simple_extent_type() + + @cached_property + def _is_empty(self): + """Check if extent type is empty""" + return self._extent_type == h5s.NULL + + @cached_property + def _dcpl(self): + """ + The dataset creation property list used when this dataset was created. + """ + return self.id.get_create_plist() + + @cached_property + def _filters(self): + """ + The active filters of the dataset. + """ + return filters.get_filters(self._dcpl) + + @with_phil + def __init__(self, bind, *, readonly=False): + """ Create a new Dataset object by binding to a low-level DatasetID. + """ + if not isinstance(bind, h5d.DatasetID): + raise ValueError("%s is not a DatasetID" % bind) + super().__init__(bind) + + self._dxpl = h5p.create(h5p.DATASET_XFER) + self._readonly = readonly + self._cache_props = {} + + def resize(self, size, axis=None): + """ Resize the dataset, or the specified axis. + + The dataset must be stored in chunked format; it can be resized up to + the "maximum shape" (keyword maxshape) specified at creation time. + The rank of the dataset cannot be changed. + + "Size" should be a shape tuple, or if an axis is specified, an integer. + + BEWARE: This functions differently than the NumPy resize() method! + The data is not "reshuffled" to fit in the new shape; each axis is + grown or shrunk independently. The coordinates of existing data are + fixed. + """ + with phil: + if self.chunks is None: + raise TypeError("Only chunked datasets can be resized") + + if axis is not None: + if not (axis >=0 and axis < self.id.rank): + raise ValueError("Invalid axis (0 to %s allowed)" % (self.id.rank-1)) + try: + newlen = int(size) + except TypeError: + raise TypeError("Argument must be a single int if axis is specified") from None + size = list(self.shape) + size[axis] = newlen + + size = tuple(size) + self.id.set_extent(size) + #h5f.flush(self.id) # THG recommends + + @with_phil + def __len__(self): + """ The size of the first axis. TypeError if scalar. + + Limited to 2**32 on 32-bit systems; Dataset.len() is preferred. + """ + size = self.len() + if size > sys.maxsize: + raise OverflowError("Value too big for Python's __len__; use Dataset.len() instead.") + return size + + def len(self): + """ The size of the first axis. TypeError if scalar. + + Use of this method is preferred to len(dset), as Python's built-in + len() cannot handle values greater then 2**32 on 32-bit systems. + """ + with phil: + shape = self.shape + if len(shape) == 0: + raise TypeError("Attempt to take len() of scalar dataset") + return shape[0] + + @with_phil + def __iter__(self): + """ Iterate over the first axis. TypeError if scalar. + + BEWARE: Modifications to the yielded data are *NOT* written to file. + """ + shape = self.shape + if len(shape) == 0: + raise TypeError("Can't iterate over a scalar dataset") + for i in range(shape[0]): + yield self[i] + + @with_phil + def iter_chunks(self, sel=None): + """ Return chunk iterator. If set, the sel argument is a slice or + tuple of slices that defines the region to be used. If not set, the + entire dataspace will be used for the iterator. + + For each chunk within the given region, the iterator yields a tuple of + slices that gives the intersection of the given chunk with the + selection area. + + A TypeError will be raised if the dataset is not chunked. + + A ValueError will be raised if the selection region is invalid. + + """ + return ChunkIterator(self, sel) + + @cached_property + def _fast_read_ok(self): + """Is this dataset suitable for simple reading""" + return ( + self._extent_type == h5s.SIMPLE + and isinstance(self.id.get_type(), (h5t.TypeIntegerID, h5t.TypeFloatID)) + ) + + @with_phil + def __getitem__(self, args, new_dtype=None): + """ Read a slice from the HDF5 dataset. + + Takes slices and recarray-style field names (more than one is + allowed!) in any order. Obeys basic NumPy rules, including + broadcasting. + + Also supports: + + * Boolean "mask" array indexing + """ + args = args if isinstance(args, tuple) else (args,) + + if self._fast_read_ok and (new_dtype is None): + try: + return self._fast_reader.read(args) + except TypeError: + pass # Fall back to Python read pathway below + + if self._is_empty: + # Check 'is Ellipsis' to avoid equality comparison with an array: + # array equality returns an array, not a boolean. + if args == () or (len(args) == 1 and args[0] is Ellipsis): + return Empty(self.dtype) + raise ValueError("Empty datasets cannot be sliced") + + # Sort field names from the rest of the args. + names = tuple(x for x in args if isinstance(x, str)) + + if names: + # Read a subset of the fields in this structured dtype + if len(names) == 1: + names = names[0] # Read with simpler dtype of this field + args = tuple(x for x in args if not isinstance(x, str)) + return self.fields(names, _prior_dtype=new_dtype)[args] + + if new_dtype is None: + new_dtype = self.dtype + mtype = h5t.py_create(new_dtype) + + # === Special-case region references ==== + + if len(args) == 1 and isinstance(args[0], h5r.RegionReference): + + obj = h5r.dereference(args[0], self.id) + if obj != self.id: + raise ValueError("Region reference must point to this dataset") + + sid = h5r.get_region(args[0], self.id) + mshape = sel.guess_shape(sid) + if mshape is None: + # 0D with no data (NULL or deselected SCALAR) + return Empty(new_dtype) + out = numpy.zeros(mshape, dtype=new_dtype) + if out.size == 0: + return out + + sid_out = h5s.create_simple(mshape) + sid_out.select_all() + self.id.read(sid_out, sid, out, mtype) + return out + + # === Check for zero-sized datasets ===== + + if self.size == 0: + # Check 'is Ellipsis' to avoid equality comparison with an array: + # array equality returns an array, not a boolean. + if args == () or (len(args) == 1 and args[0] is Ellipsis): + return numpy.zeros(self.shape, dtype=new_dtype) + + # === Scalar dataspaces ================= + + if self.shape == (): + fspace = self.id.get_space() + selection = sel2.select_read(fspace, args) + if selection.mshape is None: + arr = numpy.zeros((), dtype=new_dtype) + else: + arr = numpy.zeros(selection.mshape, dtype=new_dtype) + for mspace, fspace in selection: + self.id.read(mspace, fspace, arr, mtype) + if selection.mshape is None: + return arr[()] + return arr + + # === Everything else =================== + + # Perform the dataspace selection. + selection = sel.select(self.shape, args, dataset=self) + + if selection.nselect == 0: + return numpy.zeros(selection.array_shape, dtype=new_dtype) + + arr = numpy.zeros(selection.array_shape, new_dtype, order='C') + + # Perform the actual read + mspace = h5s.create_simple(selection.mshape) + fspace = selection.id + self.id.read(mspace, fspace, arr, mtype, dxpl=self._dxpl) + + # Patch up the output for NumPy + if arr.shape == (): + return arr[()] # 0 dim array -> numpy scalar + return arr + + @with_phil + def __setitem__(self, args, val): + """ Write to the HDF5 dataset from a Numpy array. + + NumPy's broadcasting rules are honored, for "simple" indexing + (slices and integers). For advanced indexing, the shapes must + match. + """ + args = args if isinstance(args, tuple) else (args,) + + # Sort field indices from the slicing + names = tuple(x for x in args if isinstance(x, str)) + args = tuple(x for x in args if not isinstance(x, str)) + + # Generally we try to avoid converting the arrays on the Python + # side. However, for compound literals this is unavoidable. + vlen = h5t.check_vlen_dtype(self.dtype) + if vlen is not None and vlen not in (bytes, str): + try: + val = numpy.asarray(val, dtype=vlen) + except (ValueError, TypeError): + try: + val = numpy.array([numpy.array(x, dtype=vlen) + for x in val], dtype=self.dtype) + except (ValueError, TypeError): + pass + if vlen == val.dtype: + if val.ndim > 1: + tmp = numpy.empty(shape=val.shape[:-1], dtype=object) + tmp.ravel()[:] = [i for i in val.reshape( + (product(val.shape[:-1]), val.shape[-1]) + )] + else: + tmp = numpy.array([None], dtype=object) + tmp[0] = val + val = tmp + elif self.dtype.kind == "O" or \ + (self.dtype.kind == 'V' and \ + (not isinstance(val, numpy.ndarray) or val.dtype.kind != 'V') and \ + (self.dtype.subdtype is None)): + if len(names) == 1 and self.dtype.fields is not None: + # Single field selected for write, from a non-array source + if not names[0] in self.dtype.fields: + raise ValueError("No such field for indexing: %s" % names[0]) + dtype = self.dtype.fields[names[0]][0] + cast_compound = True + else: + dtype = self.dtype + cast_compound = False + + val = numpy.asarray(val, dtype=dtype.base, order='C') + if cast_compound: + val = val.view(numpy.dtype([(names[0], dtype)])) + val = val.reshape(val.shape[:len(val.shape) - len(dtype.shape)]) + elif (self.dtype.kind == 'S' + and (h5t.check_string_dtype(self.dtype).encoding == 'utf-8') + and (find_item_type(val) is str) + ): + # Writing str objects to a fixed-length UTF-8 string dataset. + # Numpy's normal conversion only handles ASCII characters, but + # when the destination is UTF-8, we want to allow any unicode. + # This *doesn't* handle numpy fixed-length unicode data ('U' dtype), + # as HDF5 has no equivalent, and converting fixed length UTF-32 + # to variable length UTF-8 would obscure what's going on. + str_array = numpy.asarray(val, order='C', dtype=object) + val = numpy.array([ + s.encode('utf-8') for s in str_array.flat + ], dtype=self.dtype).reshape(str_array.shape) + else: + # If the input data is already an array, let HDF5 do the conversion. + # If it's a list or similar, don't make numpy guess a dtype for it. + dt = None if isinstance(val, numpy.ndarray) else self.dtype.base + val = numpy.asarray(val, order='C', dtype=dt) + + # Check for array dtype compatibility and convert + if self.dtype.subdtype is not None: + shp = self.dtype.subdtype[1] + valshp = val.shape[-len(shp):] + if valshp != shp: # Last dimension has to match + raise TypeError("When writing to array types, last N dimensions have to match (got %s, but should be %s)" % (valshp, shp,)) + mtype = h5t.py_create(numpy.dtype((val.dtype, shp))) + mshape = val.shape[0:len(val.shape)-len(shp)] + + # Make a compound memory type if field-name slicing is required + elif len(names) != 0: + + mshape = val.shape + + # Catch common errors + if self.dtype.fields is None: + raise TypeError("Illegal slicing argument (not a compound dataset)") + mismatch = [x for x in names if x not in self.dtype.fields] + if len(mismatch) != 0: + mismatch = ", ".join('"%s"'%x for x in mismatch) + raise ValueError("Illegal slicing argument (fields %s not in dataset type)" % mismatch) + + # Write non-compound source into a single dataset field + if len(names) == 1 and val.dtype.fields is None: + subtype = h5t.py_create(val.dtype) + mtype = h5t.create(h5t.COMPOUND, subtype.get_size()) + mtype.insert(self._e(names[0]), 0, subtype) + + # Make a new source type keeping only the requested fields + else: + fieldnames = [x for x in val.dtype.names if x in names] # Keep source order + mtype = h5t.create(h5t.COMPOUND, val.dtype.itemsize) + for fieldname in fieldnames: + subtype = h5t.py_create(val.dtype.fields[fieldname][0]) + offset = val.dtype.fields[fieldname][1] + mtype.insert(self._e(fieldname), offset, subtype) + + # Use mtype derived from array (let DatasetID.write figure it out) + else: + mshape = val.shape + mtype = None + + # Perform the dataspace selection + selection = sel.select(self.shape, args, dataset=self) + + if selection.nselect == 0: + return + + # Broadcast scalars if necessary. + # In order to avoid slow broadcasting filling the destination by + # the scalar value, we create an intermediate array of the same + # size as the destination buffer provided that size is reasonable. + # We assume as reasonable a size smaller or equal as the used dataset + # chunk size if any. + # In case of dealing with a non-chunked destination dataset or with + # a selection whose size is larger than the dataset chunk size we fall + # back to using an intermediate array of size equal to the last dimension + # of the destination buffer. + # The reasoning behind is that it makes sense to assume the creator of + # the dataset used an appropriate chunk size according the available + # memory. In any case, if we cannot afford to create an intermediate + # array of the same size as the dataset chunk size, the user program has + # little hope to go much further. Solves h5py issue #1067 + if mshape == () and selection.array_shape != (): + if self.dtype.subdtype is not None: + raise TypeError("Scalar broadcasting is not supported for array dtypes") + if self.chunks and (product(self.chunks) >= product(selection.array_shape)): + val2 = numpy.empty(selection.array_shape, dtype=val.dtype) + else: + val2 = numpy.empty(selection.array_shape[-1], dtype=val.dtype) + val2[...] = val + val = val2 + mshape = val.shape + + # Perform the write, with broadcasting + mspace = h5s.create_simple(selection.expand_shape(mshape)) + for fspace in selection.broadcast(mshape): + self.id.write(mspace, fspace, val, mtype, dxpl=self._dxpl) + + def read_direct(self, dest, source_sel=None, dest_sel=None): + """ Read data directly from HDF5 into an existing NumPy array. + + The destination array must be C-contiguous and writable. + Selections must be the output of numpy.s_[]. + + Broadcasting is supported for simple indexing. + """ + with phil: + if self._is_empty: + raise TypeError("Empty datasets have no numpy representation") + if source_sel is None: + source_sel = sel.SimpleSelection(self.shape) + else: + source_sel = sel.select(self.shape, source_sel, self) # for numpy.s_ + fspace = source_sel.id + + if dest_sel is None: + dest_sel = sel.SimpleSelection(dest.shape) + else: + dest_sel = sel.select(dest.shape, dest_sel) + + for mspace in dest_sel.broadcast(source_sel.array_shape): + self.id.read(mspace, fspace, dest, dxpl=self._dxpl) + + def write_direct(self, source, source_sel=None, dest_sel=None): + """ Write data directly to HDF5 from a NumPy array. + + The source array must be C-contiguous. Selections must be + the output of numpy.s_[]. + + Broadcasting is supported for simple indexing. + """ + with phil: + if self._is_empty: + raise TypeError("Empty datasets cannot be written to") + if source_sel is None: + source_sel = sel.SimpleSelection(source.shape) + else: + source_sel = sel.select(source.shape, source_sel) # for numpy.s_ + mspace = source_sel.id + + if dest_sel is None: + dest_sel = sel.SimpleSelection(self.shape) + else: + dest_sel = sel.select(self.shape, dest_sel, self) + + for fspace in dest_sel.broadcast(source_sel.array_shape): + self.id.write(mspace, fspace, source, dxpl=self._dxpl) + + @with_phil + def __array__(self, dtype=None, copy=None): + """ Create a Numpy array containing the whole dataset. DON'T THINK + THIS MEANS DATASETS ARE INTERCHANGEABLE WITH ARRAYS. For one thing, + you have to read the whole dataset every time this method is called. + """ + if copy is False: + raise ValueError( + f"Dataset.__array__ received {copy=} " + "but memory allocation cannot be avoided on read" + ) + arr = numpy.zeros(self.shape, dtype=self.dtype if dtype is None else dtype) + + # Special case for (0,)*-shape datasets + if self.size == 0: + return arr + + self.read_direct(arr) + return arr + + @with_phil + def __repr__(self): + if not self: + return "" + + if self.name is None: + name = "(anonymous)" + else: + name = pp.basename(pp.normpath(self.name)) + name = f'"{name}"' + + return f'' + + @with_phil + def refresh(self): + """ Refresh the dataset metadata by reloading from the file. + + This is part of the SWMR features. + """ + self._id.refresh() + self._cache_props.clear() + + @with_phil + def flush(self): + """ Flush the dataset data and metadata to the file. + If the dataset is chunked, raw data chunks are written to the file. + + This is part of the SWMR features. + """ + self._id.flush() + + if vds_support: + @property + @with_phil + def is_virtual(self): + """Check if this is a virtual dataset""" + return self._dcpl.get_layout() == h5d.VIRTUAL + + @with_phil + def virtual_sources(self): + """Get a list of the data mappings for a virtual dataset""" + if not self.is_virtual: + raise RuntimeError("Not a virtual dataset") + dcpl = self._dcpl + return [ + VDSmap(dcpl.get_virtual_vspace(j), + dcpl.get_virtual_filename(j), + dcpl.get_virtual_dsetname(j), + dcpl.get_virtual_srcspace(j)) + for j in range(dcpl.get_virtual_count())] + + @with_phil + def make_scale(self, name=''): + """Make this dataset an HDF5 dimension scale. + + You can then attach it to dimensions of other datasets like this:: + + other_ds.dims[0].attach_scale(ds) + + You can optionally pass a name to associate with this scale. + """ + h5ds.set_scale(self._id, self._e(name)) + + @property + @with_phil + def is_scale(self): + """Return ``True`` if this dataset is also a dimension scale. + + Return ``False`` otherwise. + """ + return h5ds.is_scale(self._id) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/datatype.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/datatype.py new file mode 100644 index 0000000000000000000000000000000000000000..33e2b31007897987f0bf197058072434c1982d2c --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/datatype.py @@ -0,0 +1,55 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Implements high-level access to committed datatypes in the file. +""" + +import posixpath as pp + +from ..h5t import TypeID +from .base import HLObject, with_phil + +class Datatype(HLObject): + + """ + Represents an HDF5 named datatype stored in a file. + + To store a datatype, simply assign it to a name in a group: + + >>> MyGroup["name"] = numpy.dtype("f") + >>> named_type = MyGroup["name"] + >>> assert named_type.dtype == numpy.dtype("f") + """ + + @property + @with_phil + def dtype(self): + """Numpy dtype equivalent for this datatype""" + return self.id.dtype + + @with_phil + def __init__(self, bind): + """ Create a new Datatype object by binding to a low-level TypeID. + """ + if not isinstance(bind, TypeID): + raise ValueError("%s is not a TypeID" % bind) + super().__init__(bind) + + @with_phil + def __repr__(self): + if not self.id: + return "" + if self.name is None: + namestr = '("anonymous")' + else: + name = pp.basename(pp.normpath(self.name)) + namestr = '"%s"' % (name if name != '' else '/') + return '' % \ + (namestr, self.dtype.str) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/dims.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/dims.py new file mode 100644 index 0000000000000000000000000000000000000000..0cf4c9f36b85f13a866ef20c32e1142eb3c3b254 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/dims.py @@ -0,0 +1,181 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Implements support for HDF5 dimension scales. +""" + +import warnings + +from .. import h5ds +from ..h5py_warnings import H5pyDeprecationWarning +from . import base +from .base import phil, with_phil +from .dataset import Dataset + + +class DimensionProxy(base.CommonStateObject): + + """ + Represents an HDF5 "dimension". + """ + + @property + @with_phil + def label(self): + """ Get or set the dimension scale label """ + return self._d(h5ds.get_label(self._id, self._dimension)) + + @label.setter + @with_phil + def label(self, val): + # pylint: disable=missing-docstring + h5ds.set_label(self._id, self._dimension, self._e(val)) + + @with_phil + def __init__(self, id_, dimension): + self._id = id_ + self._dimension = dimension + + @with_phil + def __hash__(self): + return hash((type(self), self._id, self._dimension)) + + @with_phil + def __eq__(self, other): + return hash(self) == hash(other) + + @with_phil + def __iter__(self): + yield from self.keys() + + @with_phil + def __len__(self): + return h5ds.get_num_scales(self._id, self._dimension) + + @with_phil + def __getitem__(self, item): + + if isinstance(item, int): + scales = [] + h5ds.iterate(self._id, self._dimension, scales.append, 0) + return Dataset(scales[item]) + + else: + def f(dsid): + """ Iterate over scales to find a matching name """ + if h5ds.get_scale_name(dsid) == self._e(item): + return dsid + + res = h5ds.iterate(self._id, self._dimension, f, 0) + if res is None: + raise KeyError(item) + return Dataset(res) + + def attach_scale(self, dset): + """ Attach a scale to this dimension. + + Provide the Dataset of the scale you would like to attach. + """ + with phil: + h5ds.attach_scale(self._id, dset.id, self._dimension) + + def detach_scale(self, dset): + """ Remove a scale from this dimension. + + Provide the Dataset of the scale you would like to remove. + """ + with phil: + h5ds.detach_scale(self._id, dset.id, self._dimension) + + def items(self): + """ Get a list of (name, Dataset) pairs with all scales on this + dimension. + """ + with phil: + scales = [] + + # H5DSiterate raises an error if there are no dimension scales, + # rather than iterating 0 times. See #483. + if len(self) > 0: + h5ds.iterate(self._id, self._dimension, scales.append, 0) + + return [ + (self._d(h5ds.get_scale_name(x)), Dataset(x)) + for x in scales + ] + + def keys(self): + """ Get a list of names for the scales on this dimension. """ + with phil: + return [key for (key, _) in self.items()] + + def values(self): + """ Get a list of Dataset for scales on this dimension. """ + with phil: + return [val for (_, val) in self.items()] + + @with_phil + def __repr__(self): + if not self._id: + return "" + return ('<"%s" dimension %d of HDF5 dataset at %s>' + % (self.label, self._dimension, id(self._id))) + + +class DimensionManager(base.CommonStateObject): + + """ + Represents a collection of dimension associated with a dataset. + + Like AttributeManager, an instance of this class is returned when + accessing the ".dims" property on a Dataset. + """ + + @with_phil + def __init__(self, parent): + """ Private constructor. + """ + self._id = parent.id + + @with_phil + def __getitem__(self, index): + """ Return a Dimension object + """ + if index > len(self) - 1: + raise IndexError('Index out of range') + return DimensionProxy(self._id, index) + + @with_phil + def __len__(self): + """ Number of dimensions associated with the dataset. """ + return self._id.rank + + @with_phil + def __iter__(self): + """ Iterate over the dimensions. """ + for i in range(len(self)): + yield self[i] + + @with_phil + def __repr__(self): + if not self._id: + return "" + return "" % id(self._id) + + def create_scale(self, dset, name=''): + """ Create a new dimension, from an initial scale. + + Provide the dataset and a name for the scale. + """ + warnings.warn("other_ds.dims.create_scale(ds, name) is deprecated. " + "Use ds.make_scale(name) instead.", + H5pyDeprecationWarning, stacklevel=2, + ) + dset.make_scale(name) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/files.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/files.py new file mode 100644 index 0000000000000000000000000000000000000000..a138d634fd1a559096efd6a19b8bda2693715412 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/files.py @@ -0,0 +1,664 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Implements high-level support for HDF5 file objects. +""" + +import inspect +import os +import sys +from warnings import warn + +from .compat import filename_decode, filename_encode + +from .base import phil, with_phil +from .group import Group +from .. import h5, h5f, h5p, h5i, h5fd, _objects +from .. import version + +mpi = h5.get_config().mpi +ros3 = h5.get_config().ros3 +direct_vfd = h5.get_config().direct_vfd +hdf5_version = version.hdf5_version_tuple[0:3] + +swmr_support = True + + +libver_dict = {'earliest': h5f.LIBVER_EARLIEST, 'latest': h5f.LIBVER_LATEST, + 'v108': h5f.LIBVER_V18, 'v110': h5f.LIBVER_V110} +libver_dict_r = dict((y, x) for x, y in libver_dict.items()) + +if hdf5_version >= (1, 11, 4): + libver_dict.update({'v112': h5f.LIBVER_V112}) + libver_dict_r.update({h5f.LIBVER_V112: 'v112'}) + +if hdf5_version >= (1, 13, 0): + libver_dict.update({'v114': h5f.LIBVER_V114}) + libver_dict_r.update({h5f.LIBVER_V114: 'v114'}) + +if hdf5_version >= (2, 0, 0): + libver_dict.update({'v200': h5f.LIBVER_V200}) + libver_dict_r.update({h5f.LIBVER_V200: 'v200'}) + + +def _set_fapl_mpio(plist, **kwargs): + """Set file access property list for mpio driver""" + if not mpi: + raise ValueError("h5py was built without MPI support, can't use mpio driver") + + import mpi4py.MPI + kwargs.setdefault('info', mpi4py.MPI.Info()) + plist.set_fapl_mpio(**kwargs) + + +def _set_fapl_fileobj(plist, **kwargs): + """Set the Python file object driver in a file access property list""" + plist.set_fileobj_driver(h5fd.fileobj_driver, kwargs.get('fileobj')) + + +_drivers = { + 'sec2': lambda plist, **kwargs: plist.set_fapl_sec2(**kwargs), + 'stdio': lambda plist, **kwargs: plist.set_fapl_stdio(**kwargs), + 'core': lambda plist, **kwargs: plist.set_fapl_core(**kwargs), + 'family': lambda plist, **kwargs: plist.set_fapl_family( + memb_fapl=plist.copy(), + **kwargs + ), + 'mpio': _set_fapl_mpio, + 'fileobj': _set_fapl_fileobj, + 'split': lambda plist, **kwargs: plist.set_fapl_split(**kwargs), +} + +if ros3: + _drivers['ros3'] = lambda plist, **kwargs: plist.set_fapl_ros3(**kwargs) + +if direct_vfd: + _drivers['direct'] = lambda plist, **kwargs: plist.set_fapl_direct(**kwargs) # noqa + + +def register_driver(name, set_fapl): + """Register a custom driver. + + Parameters + ---------- + name : str + The name of the driver. + set_fapl : callable[PropFAID, **kwargs] -> NoneType + The function to set the fapl to use your custom driver. + """ + _drivers[name] = set_fapl + + +def unregister_driver(name): + """Unregister a custom driver. + + Parameters + ---------- + name : str + The name of the driver. + """ + del _drivers[name] + + +def registered_drivers(): + """Return a frozenset of the names of all of the registered drivers. + """ + return frozenset(_drivers) + + +def make_fapl( + driver, libver=None, rdcc_nslots=None, rdcc_nbytes=None, rdcc_w0=None, + locking=None, page_buf_size=None, min_meta_keep=0, min_raw_keep=0, + alignment_threshold=1, alignment_interval=1, meta_block_size=None, + **kwds +): + """ Set up a file access property list """ + plist = h5p.create(h5p.FILE_ACCESS) + + if libver is not None: + if libver in libver_dict: + low = libver_dict[libver] + high = h5f.LIBVER_LATEST + else: + low, high = (libver_dict[x] for x in libver) + else: + # we default to earliest + low, high = h5f.LIBVER_EARLIEST, h5f.LIBVER_LATEST + plist.set_libver_bounds(low, high) + plist.set_alignment(alignment_threshold, alignment_interval) + + cache_settings = list(plist.get_cache()) + if rdcc_nslots is not None: + cache_settings[1] = rdcc_nslots + if rdcc_nbytes is not None: + cache_settings[2] = rdcc_nbytes + if rdcc_w0 is not None: + cache_settings[3] = rdcc_w0 + plist.set_cache(*cache_settings) + + if page_buf_size: + plist.set_page_buffer_size(int(page_buf_size), int(min_meta_keep), + int(min_raw_keep)) + + if meta_block_size is not None: + plist.set_meta_block_size(int(meta_block_size)) + + if locking is not None: + if locking in ("false", False): + plist.set_file_locking(False, ignore_when_disabled=False) + elif locking in ("true", True): + plist.set_file_locking(True, ignore_when_disabled=False) + elif locking == "best-effort": + plist.set_file_locking(True, ignore_when_disabled=True) + else: + raise ValueError(f"Unsupported locking value: {locking}") + + if driver is None or (driver == 'windows' and sys.platform == 'win32'): + # Prevent swallowing unused key arguments + if kwds: + msg = "'{key}' is an invalid keyword argument for this function" \ + .format(key=next(iter(kwds))) + raise TypeError(msg) + return plist + + try: + set_fapl = _drivers[driver] + except KeyError as exc: + raise ValueError(f'Unknown driver type {driver!r}') from exc + else: + if driver == 'ros3': + token = kwds.pop('session_token', None) + set_fapl(plist, **kwds) + if token: + if hdf5_version < (1, 14, 2): + raise ValueError('HDF5 >= 1.14.2 required for AWS session token') + plist.set_fapl_ros3_token(token) + else: + set_fapl(plist, **kwds) + + return plist + + +def make_fcpl(track_order=False, track_times=False, fs_strategy=None, fs_persist=False, + fs_threshold=1, fs_page_size=None): + """ Set up a file creation property list """ + plist = h5p.create(h5p.FILE_CREATE) + if track_order: + plist.set_link_creation_order( + h5p.CRT_ORDER_TRACKED | h5p.CRT_ORDER_INDEXED) + plist.set_attr_creation_order( + h5p.CRT_ORDER_TRACKED | h5p.CRT_ORDER_INDEXED) + if track_times is None: + track_times = False # Allow explicit None to mean h5py's default + if track_times in (True, False): + plist.set_obj_track_times(track_times) + else: + raise TypeError("track_times must be either True or False") + if fs_strategy: + strategies = { + 'fsm': h5f.FSPACE_STRATEGY_FSM_AGGR, + 'page': h5f.FSPACE_STRATEGY_PAGE, + 'aggregate': h5f.FSPACE_STRATEGY_AGGR, + 'none': h5f.FSPACE_STRATEGY_NONE + } + fs_strat_num = strategies.get(fs_strategy, -1) + if fs_strat_num == -1: + raise ValueError("Invalid file space strategy type") + + plist.set_file_space_strategy(fs_strat_num, fs_persist, fs_threshold) + if fs_page_size and fs_strategy == 'page': + plist.set_file_space_page_size(int(fs_page_size)) + return plist + + +def make_fid(name, mode, userblock_size, fapl, fcpl=None, swmr=False): + """ Get a new FileID by opening or creating a file. + Also validates mode argument.""" + + if userblock_size is not None: + if mode in ('r', 'r+'): + raise ValueError("User block may only be specified " + "when creating a file") + try: + userblock_size = int(userblock_size) + except (TypeError, ValueError): + raise ValueError("User block size must be an integer") from None + if fcpl is None: + fcpl = h5p.create(h5p.FILE_CREATE) + fcpl.set_userblock(userblock_size) + + if mode == 'r': + flags = h5f.ACC_RDONLY + if swmr and swmr_support: + flags |= h5f.ACC_SWMR_READ + fid = h5f.open(name, flags, fapl=fapl) + elif mode == 'r+': + fid = h5f.open(name, h5f.ACC_RDWR, fapl=fapl) + elif mode in ['w-', 'x']: + fid = h5f.create(name, h5f.ACC_EXCL, fapl=fapl, fcpl=fcpl) + elif mode == 'w': + fid = h5f.create(name, h5f.ACC_TRUNC, fapl=fapl, fcpl=fcpl) + elif mode == 'a': + # Open in append mode (read/write). + # If that fails, create a new file only if it won't clobber an + # existing one (ACC_EXCL) + try: + fid = h5f.open(name, h5f.ACC_RDWR, fapl=fapl) + # Not all drivers raise FileNotFoundError (commented those that do not) + except FileNotFoundError if fapl.get_driver() in ( + h5fd.SEC2, + h5fd.DIRECT if direct_vfd else -1, + # h5fd.STDIO, + # h5fd.CORE, + h5fd.FAMILY, + h5fd.WINDOWS, + # h5fd.MPIO, + # h5fd.MPIPOSIX, + h5fd.fileobj_driver, + h5fd.ROS3D if ros3 else -1, + ) else OSError: + fid = h5f.create(name, h5f.ACC_EXCL, fapl=fapl, fcpl=fcpl) + else: + raise ValueError("Invalid mode; must be one of r, r+, w, w-, x, a") + + try: + if userblock_size is not None: + existing_fcpl = fid.get_create_plist() + if existing_fcpl.get_userblock() != userblock_size: + raise ValueError("Requested userblock size (%d) does not match that of existing file (%d)" % (userblock_size, existing_fcpl.get_userblock())) + except Exception as e: + fid.close() + raise e + + return fid + + +class File(Group): + + """ + Represents an HDF5 file. + """ + + @property + def attrs(self): + """ Attributes attached to this object """ + # hdf5 complains that a file identifier is an invalid location for an + # attribute. Instead of self, pass the root group to AttributeManager: + from . import attrs + with phil: + return attrs.AttributeManager(self['/']) + + @property + @with_phil + def filename(self): + """File name on disk""" + return filename_decode(h5f.get_name(self.id)) + + @property + @with_phil + def driver(self): + """Low-level HDF5 file driver used to open file""" + drivers = {h5fd.SEC2: 'sec2', + h5fd.STDIO: 'stdio', + h5fd.CORE: 'core', + h5fd.FAMILY: 'family', + h5fd.WINDOWS: 'windows', + h5fd.MPIO: 'mpio', + h5fd.MPIPOSIX: 'mpiposix', + h5fd.fileobj_driver: 'fileobj'} + if ros3: + drivers[h5fd.ROS3D] = 'ros3' + if direct_vfd: + drivers[h5fd.DIRECT] = 'direct' + return drivers.get(self.id.get_access_plist().get_driver(), 'unknown') + + @property + @with_phil + def mode(self): + """ Python mode used to open file """ + write_intent = h5f.ACC_RDWR + if swmr_support: + write_intent |= h5f.ACC_SWMR_WRITE + return 'r+' if self.id.get_intent() & write_intent else 'r' + + @property + @with_phil + def libver(self): + """File format version bounds (2-tuple: low, high)""" + bounds = self.id.get_access_plist().get_libver_bounds() + return tuple(libver_dict_r[x] for x in bounds) + + @property + @with_phil + def userblock_size(self): + """ User block size (in bytes) """ + fcpl = self.id.get_create_plist() + return fcpl.get_userblock() + + @property + @with_phil + def meta_block_size(self): + """ Meta block size (in bytes) """ + fapl = self.id.get_access_plist() + return fapl.get_meta_block_size() + + if mpi: + + @property + @with_phil + def atomic(self): + """ Set/get MPI-IO atomic mode + """ + return self.id.get_mpi_atomicity() + + @atomic.setter + @with_phil + def atomic(self, value): + # pylint: disable=missing-docstring + self.id.set_mpi_atomicity(value) + + @property + @with_phil + def swmr_mode(self): + """ Controls single-writer multiple-reader mode """ + return swmr_support and bool(self.id.get_intent() & (h5f.ACC_SWMR_READ | h5f.ACC_SWMR_WRITE)) + + @swmr_mode.setter + @with_phil + def swmr_mode(self, value): + # pylint: disable=missing-docstring + if value: + self.id.start_swmr_write() + else: + raise ValueError("It is not possible to forcibly switch SWMR mode off.") + + def __init__(self, name, mode='r', driver=None, libver=None, userblock_size=None, swmr=False, + rdcc_nslots=None, rdcc_nbytes=None, rdcc_w0=None, track_order=None, + fs_strategy=None, fs_persist=False, fs_threshold=1, fs_page_size=None, + page_buf_size=None, min_meta_keep=0, min_raw_keep=0, locking=None, + alignment_threshold=1, alignment_interval=1, meta_block_size=None, + *, track_times=False, **kwds): + """Create a new file object. + + See the h5py user guide for a detailed explanation of the options. + + name + Name of the file on disk, or file-like object. Note: for files + created with the 'core' driver, HDF5 still requires this be + non-empty. + mode + r Readonly, file must exist (default) + r+ Read/write, file must exist + w Create file, truncate if exists + w- or x Create file, fail if exists + a Read/write if exists, create otherwise + driver + Name of the driver to use. Legal values are None (default, + recommended), 'core', 'sec2', 'direct', 'stdio', 'mpio', 'ros3'. + libver + Library version bounds. Supported values: 'earliest', 'v108', + 'v110', 'v112', 'v114', 'v200' and 'latest' depending on the + version of libhdf5 h5py is built against. + userblock_size + Desired size of user block. Only allowed when creating a new + file (mode w, w- or x). + swmr + Open the file in SWMR read mode. Only used when mode = 'r'. + rdcc_nslots + The number of chunk slots in the raw data chunk cache for this + file. Increasing this value reduces the number of cache collisions, + but slightly increases the memory used. Due to the hashing + strategy, this value should ideally be a prime number. As a rule of + thumb, this value should be at least 10 times the number of chunks + that can fit in rdcc_nbytes bytes. For maximum performance, this + value should be set approximately 100 times that number of + chunks. The default value is 521. Applies to all datasets unless individually changed. + rdcc_nbytes + Total size of the dataset chunk cache in bytes. The default size per + dataset is 1024**2 (1 MiB) for HDF5 before 2.0 and 8 MiB for HDF5 + 2.0 and later. Applies to all datasets unless individually changed. + rdcc_w0 + The chunk preemption policy for all datasets. This must be + between 0 and 1 inclusive and indicates the weighting according to + which chunks which have been fully read or written are penalized + when determining which chunks to flush from cache. A value of 0 + means fully read or written chunks are treated no differently than + other chunks (the preemption is strictly LRU) while a value of 1 + means fully read or written chunks are always preempted before + other chunks. If your application only reads or writes data once, + this can be safely set to 1. Otherwise, this should be set lower + depending on how often you re-read or re-write the same data. The + default value is 0.75. Applies to all datasets unless individually changed. + track_order + Track dataset/group/attribute creation order under root group + if True. If None use global default h5.get_config().track_order. + track_times: bool or None, default: False + If True, store timestamps for this group in the file. + If None, fall back to the default value. + fs_strategy + The file space handling strategy to be used. Only allowed when + creating a new file (mode w, w- or x). Defined as: + "fsm" FSM, Aggregators, VFD + "page" Paged FSM, VFD + "aggregate" Aggregators, VFD + "none" VFD + If None use HDF5 defaults. + fs_page_size + File space page size in bytes. Only used when fs_strategy="page". If + None use the HDF5 default (4096 bytes). + fs_persist + A boolean value to indicate whether free space should be persistent + or not. Only allowed when creating a new file. The default value + is False. + fs_threshold + The smallest free-space section size that the free space manager + will track. Only allowed when creating a new file. The default + value is 1. + page_buf_size + Page buffer size in bytes. Only allowed for HDF5 files created with + fs_strategy="page". Must be a power of two value and greater or + equal than the file space page size when creating the file. It is + not used by default. + min_meta_keep + Minimum percentage of metadata to keep in the page buffer before + allowing pages containing metadata to be evicted. Applicable only if + page_buf_size is set. Default value is zero. + min_raw_keep + Minimum percentage of raw data to keep in the page buffer before + allowing pages containing raw data to be evicted. Applicable only if + page_buf_size is set. Default value is zero. + locking + The file locking behavior. Defined as: + + - False (or "false") -- Disable file locking + - True (or "true") -- Enable file locking + - "best-effort" -- Enable file locking but ignore some errors + - None -- Use HDF5 defaults + + .. warning:: + + The HDF5_USE_FILE_LOCKING environment variable can override + this parameter. + + alignment_threshold + Together with ``alignment_interval``, this property ensures that + any file object greater than or equal in size to the alignment + threshold (in bytes) will be aligned on an address which is a + multiple of alignment interval. + + alignment_interval + This property should be used in conjunction with + ``alignment_threshold``. See the description above. For more + details, see + https://support.hdfgroup.org/documentation/hdf5/latest/group___f_a_p_l.html#gab99d5af749aeb3896fd9e3ceb273677a + + meta_block_size + Set the current minimum size, in bytes, of new metadata block allocations. + See https://support.hdfgroup.org/documentation/hdf5/latest/group___f_a_p_l.html#ga8822e3dedc8e1414f20871a87d533cb1 + + Additional keywords + Passed on to the selected file driver. + """ + if driver == 'ros3': + if not ros3: + raise ValueError("h5py was built without ROS3 support, can't use ros3 driver") + if hdf5_version < (2, 0, 0): + from urllib.parse import urlparse + url = urlparse(name) + if url.scheme == 's3': + aws_region = kwds.get('aws_region', b'').decode('ascii') + if len(aws_region) == 0: + raise ValueError('AWS region required for s3:// location') + name = f'https://s3.{aws_region}.amazonaws.com/{url.netloc}{url.path}' + elif url.scheme not in ('https', 'http'): + raise ValueError(f'{name}: S3 location must begin with ' + 'either "https://", "http://", or "s3://"') + + if isinstance(name, _objects.ObjectID): + if fs_strategy: + raise ValueError("Unable to set file space strategy of an existing file") + + with phil: + fid = h5i.get_file_id(name) + else: + if hasattr(name, 'read') and hasattr(name, 'seek'): + if driver not in (None, 'fileobj'): + raise ValueError("Driver must be 'fileobj' for file-like object if specified.") + driver = 'fileobj' + if kwds.get('fileobj', name) != name: + raise ValueError("Invalid value of 'fileobj' argument; " + "must equal to file-like object if specified.") + kwds.update(fileobj=name) + name = repr(name).encode('ASCII', 'replace') + else: + name = filename_encode(name) + + if track_order is None: + track_order = h5.get_config().track_order + + if fs_strategy and mode not in ('w', 'w-', 'x'): + raise ValueError("Unable to set file space strategy of an existing file") + + if swmr and mode != 'r': + warn( + "swmr=True only affects read ('r') mode. For swmr write " + "mode, set f.swmr_mode = True after opening the file.", + stacklevel=2, + ) + + with phil: + fapl = make_fapl(driver, libver, rdcc_nslots, rdcc_nbytes, rdcc_w0, + locking, page_buf_size, min_meta_keep, min_raw_keep, + alignment_threshold=alignment_threshold, + alignment_interval=alignment_interval, + meta_block_size=meta_block_size, + **kwds) + fcpl = make_fcpl(track_order=track_order, track_times=track_times, + fs_strategy=fs_strategy, fs_persist=fs_persist, + fs_threshold=fs_threshold, fs_page_size=fs_page_size) + fid = make_fid(name, mode, userblock_size, fapl, fcpl, swmr=swmr) + + if isinstance(libver, tuple): + self._libver = libver + else: + self._libver = (libver, 'latest') + + super().__init__(fid) + + _in_memory_file_counter = 0 + + @classmethod + @with_phil + def in_memory(cls, file_image=None, **kwargs): + """Create an HDF5 file in memory, without an underlying file + + file_image + The initial file contents as bytes (or anything that supports the + Python buffer interface). HDF5 takes a copy of this data. + block_size + Chunk size for new memory alloactions (default 64 KiB). + + Other keyword arguments are like File(), although name, mode, + driver and locking can't be passed. + """ + for k in ('driver', 'locking', 'backing_store'): + if k in kwargs: + raise TypeError( + f"File.in_memory() got an unexpected keyword argument {k!r}" + ) + fcpl_kwargs = {} + for k in inspect.signature(make_fcpl).parameters: + if k in kwargs: + fcpl_kwargs[k] = kwargs.pop(k) + fcpl = make_fcpl(**fcpl_kwargs) + + fapl = make_fapl(driver="core", backing_store=False, **kwargs) + if file_image: + if fcpl_kwargs: + kw = ', '.join(fcpl_kwargs) + raise TypeError(f"{kw} parameters cannot be used with file_image") + fapl.set_file_image(file_image) + + # We have to give HDF5 a filename, but it should never use it. + # This is a hint both in memory, and in case a bug ever creates a file. + # The name also needs to be different from any other open file; + # we use a simple counter (protected by the 'phil' lock) for this. + name = b"h5py_in_memory_nonfile_%d" % cls._in_memory_file_counter + cls._in_memory_file_counter += 1 + + if file_image: + fid = h5f.open(name, h5f.ACC_RDWR, fapl=fapl) + else: + fid = h5f.create(name, h5f.ACC_EXCL, fapl=fapl, fcpl=fcpl) + return cls(fid) + + def close(self): + """ Close the file. All open objects become invalid """ + with phil: + # Check that the file is still open, otherwise skip + if self.id.valid: + # We have to explicitly murder all open objects related to the file + + # Close file-resident objects first, then the files. + # Otherwise we get errors in MPI mode. + self.id._close_open_objects(h5f.OBJ_LOCAL | ~h5f.OBJ_FILE) + self.id._close_open_objects(h5f.OBJ_LOCAL | h5f.OBJ_FILE) + + self.id.close() + _objects.nonlocal_close() + + def flush(self): + """ Tell the HDF5 library to flush its buffers. + """ + with phil: + h5f.flush(self.id) + + @with_phil + def __enter__(self): + return self + + @with_phil + def __exit__(self, *args): + if self.id: + self.close() + + @with_phil + def __repr__(self): + if not self.id: + r = '' + else: + # Filename has to be forced to Unicode if it comes back bytes + # Mode is always a "native" string + filename = self.filename + if isinstance(filename, bytes): # Can't decode fname + filename = filename.decode('utf8', 'replace') + r = f'' + + return r diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/filters.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..83f8d4939b64f6fcb1ce5d69baf42c9f4160f2d5 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/filters.py @@ -0,0 +1,412 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Implements support for HDF5 compression filters via the high-level + interface. The following types of filter are available: + + "gzip" + Standard DEFLATE-based compression, at integer levels from 0 to 9. + Built-in to all public versions of HDF5. Use this if you want a + decent-to-good ratio, good portability, and don't mind waiting. + + "lzf" + Custom compression filter for h5py. This filter is much, much faster + than gzip (roughly 10x in compression vs. gzip level 4, and 3x faster + in decompressing), but at the cost of a worse compression ratio. Use + this if you want cheap compression and portability is not a concern. + + "szip" + Access to the HDF5 SZIP encoder. SZIP is a non-mainstream compression + format used in space science on integer and float datasets. SZIP is + subject to license requirements, which means the encoder is not + guaranteed to be always available. However, it is also much faster + than gzip. + + The following constants in this module are also useful: + + decode + Tuple of available filter names for decoding + + encode + Tuple of available filter names for encoding +""" +from collections.abc import Mapping +import operator + +import numpy as np +from .base import product +from .compat import filename_encode +from .. import h5z, h5p, h5d, h5f + + +_COMP_FILTERS = {'gzip': h5z.FILTER_DEFLATE, + 'szip': h5z.FILTER_SZIP, + 'lzf': h5z.FILTER_LZF, + 'shuffle': h5z.FILTER_SHUFFLE, + 'fletcher32': h5z.FILTER_FLETCHER32, + 'scaleoffset': h5z.FILTER_SCALEOFFSET } +_FILL_TIME_ENUM = {'alloc': h5d.FILL_TIME_ALLOC, + 'never': h5d.FILL_TIME_NEVER, + 'ifset': h5d.FILL_TIME_IFSET, + } + +DEFAULT_GZIP = 4 +DEFAULT_SZIP = ('nn', 8) + +def _gen_filter_tuples(): + """ Bootstrap function to figure out what filters are available. """ + dec = [] + enc = [] + for name, code in _COMP_FILTERS.items(): + if h5z.filter_avail(code): + info = h5z.get_filter_info(code) + if info & h5z.FILTER_CONFIG_ENCODE_ENABLED: + enc.append(name) + if info & h5z.FILTER_CONFIG_DECODE_ENABLED: + dec.append(name) + + return tuple(dec), tuple(enc) + +decode, encode = _gen_filter_tuples() + +def _external_entry(entry): + """ Check for and return a well-formed entry tuple for + a call to h5p.set_external. """ + # We require only an iterable entry but also want to guard against + # raising a confusing exception from unpacking below a str or bytes that + # was mistakenly passed as an entry. We go further than that and accept + # only a tuple, which allows simpler documentation and exception + # messages. + if not isinstance(entry, tuple): + raise TypeError( + "Each external entry must be a tuple of (name, offset, size)") + name, offset, size = entry # raise ValueError without three elements + name = filename_encode(name) + offset = operator.index(offset) + size = operator.index(size) + return (name, offset, size) + +def _normalize_external(external): + """ Normalize external into a well-formed list of tuples and return. """ + if external is None: + return [] + try: + # Accept a solitary name---a str, bytes, or os.PathLike acceptable to + # filename_encode. + return [_external_entry((external, 0, h5f.UNLIMITED))] + except TypeError: + pass + # Check and rebuild each entry to be well-formed. + return [_external_entry(entry) for entry in external] + +class FilterRefBase(Mapping): + """Base class for referring to an HDF5 and describing its options + + Your subclass must define filter_id, and may define a filter_options tuple. + """ + filter_id = None + filter_options = () + + # Mapping interface supports using instances as **kwargs for compatibility + # with older versions of h5py + @property + def _kwargs(self): + return { + 'compression': self.filter_id, + 'compression_opts': self.filter_options + } + + def __hash__(self): + return hash((self.filter_id, self.filter_options)) + + def __eq__(self, other): + return ( + isinstance(other, FilterRefBase) + and self.filter_id == other.filter_id + and self.filter_options == other.filter_options + ) + + def __len__(self): + return len(self._kwargs) + + def __iter__(self): + return iter(self._kwargs) + + def __getitem__(self, item): + return self._kwargs[item] + +class Gzip(FilterRefBase): + filter_id = h5z.FILTER_DEFLATE + + def __init__(self, level=DEFAULT_GZIP): + self.filter_options = (level,) + +def fill_dcpl(plist, shape, dtype, chunks, compression, compression_opts, + shuffle, fletcher32, maxshape, scaleoffset, external, + allow_unknown_filter=False, *, fill_time=None): + """ Generate a dataset creation property list. + + Undocumented and subject to change without warning. + """ + + if shape is None or shape == (): + shapetype = 'Empty' if shape is None else 'Scalar' + if any((chunks, compression, compression_opts, shuffle, fletcher32, + scaleoffset is not None)): + raise TypeError( + f"{shapetype} datasets don't support chunk/filter options" + ) + if maxshape and maxshape != (): + raise TypeError(f"{shapetype} datasets cannot be extended") + return h5p.create(h5p.DATASET_CREATE) + + def rq_tuple(tpl, name): + """ Check if chunks/maxshape match dataset rank """ + if tpl in (None, True): + return + try: + tpl = tuple(tpl) + except TypeError as exc: + raise TypeError(f'{name!r} argument must be None or a sequence object') from exc + if len(tpl) != len(shape): + raise ValueError(f'{name!r} must have same rank as dataset shape') + + rq_tuple(chunks, 'chunks') + rq_tuple(maxshape, 'maxshape') + + if compression is not None: + if isinstance(compression, FilterRefBase): + compression_opts = compression.filter_options + compression = compression.filter_id + + if compression not in encode and not isinstance(compression, int): + raise ValueError('Compression filter "%s" is unavailable' % compression) + + if compression == 'gzip': + if compression_opts is None: + gzip_level = DEFAULT_GZIP + elif compression_opts in range(10): + gzip_level = compression_opts + else: + raise ValueError("GZIP setting must be an integer from 0-9, not %r" % compression_opts) + + elif compression == 'lzf': + if compression_opts is not None: + raise ValueError("LZF compression filter accepts no options") + + elif compression == 'szip': + if compression_opts is None: + compression_opts = DEFAULT_SZIP + + err = "SZIP options must be a 2-tuple ('ec'|'nn', even integer 0-32)" + try: + szmethod, szpix = compression_opts + except TypeError as exc: + raise TypeError(err) from exc + if szmethod not in ('ec', 'nn'): + raise ValueError(err) + if not (0= 0') + + if dtype.kind == 'f': + if scaleoffset is True: + raise ValueError('integer scaleoffset must be provided for ' + 'floating point types') + elif dtype.kind in ('u', 'i'): + if scaleoffset is True: + scaleoffset = h5z.SO_INT_MINBITS_DEFAULT + else: + raise TypeError('scale/offset filter only supported for integer ' + 'and floating-point types') + + # Scale/offset following fletcher32 in the filter chain will (almost?) + # always triggers a read error, as most scale/offset settings are + # lossy. Since fletcher32 must come first (see comment below) we + # simply prohibit the combination of fletcher32 and scale/offset. + if fletcher32: + raise ValueError('fletcher32 cannot be used with potentially lossy' + ' scale/offset filter') + + external = _normalize_external(external) + # End argument validation + + if (chunks is True) or (chunks is None and any(( + shuffle, + fletcher32, + compression, + (maxshape and not len(external)), + scaleoffset is not None, + ))): + chunks = guess_chunk(shape, maxshape, dtype.itemsize) + + if maxshape is True: + maxshape = (None,)*len(shape) + + if chunks is not None: + plist.set_chunk(chunks) + + if fill_time is not None: + if (ft := _FILL_TIME_ENUM.get(fill_time)) is not None: + plist.set_fill_time(ft) + else: + msg = ("fill_time must be one of the following choices: 'alloc', " + f"'never' or 'ifset', but it is {fill_time}.") + raise ValueError(msg) + + # scale-offset must come before shuffle and compression + if scaleoffset is not None: + if dtype.kind in ('u', 'i'): + plist.set_scaleoffset(h5z.SO_INT, scaleoffset) + else: # dtype.kind == 'f' + plist.set_scaleoffset(h5z.SO_FLOAT_DSCALE, scaleoffset) + + for item in external: + plist.set_external(*item) + + if shuffle: + plist.set_shuffle() + + if compression == 'gzip': + plist.set_deflate(gzip_level) + elif compression == 'lzf': + plist.set_filter(h5z.FILTER_LZF, h5z.FLAG_OPTIONAL) + elif compression == 'szip': + opts = {'ec': h5z.SZIP_EC_OPTION_MASK, 'nn': h5z.SZIP_NN_OPTION_MASK} + plist.set_szip(opts[szmethod], szpix) + elif isinstance(compression, int): + if not allow_unknown_filter and not h5z.filter_avail(compression): + raise ValueError("Unknown compression filter number: %s" % compression) + + plist.set_filter(compression, h5z.FLAG_OPTIONAL, compression_opts) + + # `fletcher32` must come after `compression`, otherwise, if `compression` + # is "szip" and the data is 64bit, the fletcher32 checksum will be wrong + # (see GitHub issue #953). + if fletcher32: + plist.set_fletcher32() + + return plist + +def get_filter_name(code): + """ + Return the name of the compression filter for a given filter identifier. + + Undocumented and subject to change without warning. + """ + filters = {h5z.FILTER_DEFLATE: 'gzip', h5z.FILTER_SZIP: 'szip', + h5z.FILTER_SHUFFLE: 'shuffle', h5z.FILTER_FLETCHER32: 'fletcher32', + h5z.FILTER_LZF: 'lzf', h5z.FILTER_SCALEOFFSET: 'scaleoffset'} + return filters.get(code, str(code)) + +def get_filters(plist): + """ Extract a dictionary of active filters from a DCPL, along with + their settings. + + Undocumented and subject to change without warning. + """ + + pipeline = {} + + nfilters = plist.get_nfilters() + + for i in range(nfilters): + + code, _, vals, _ = plist.get_filter(i) + + if code == h5z.FILTER_DEFLATE: + vals = vals[0] # gzip level + + elif code == h5z.FILTER_SZIP: + mask, pixels = vals[0:2] + if mask & h5z.SZIP_EC_OPTION_MASK: + mask = 'ec' + elif mask & h5z.SZIP_NN_OPTION_MASK: + mask = 'nn' + else: + raise TypeError("Unknown SZIP configuration") + vals = (mask, pixels) + elif code == h5z.FILTER_LZF: + vals = None + else: + if len(vals) == 0: + vals = None + + pipeline[get_filter_name(code)] = vals + + return pipeline + +CHUNK_BASE = 16*1024 # Multiplier by which chunks are adjusted +CHUNK_MIN = 8*1024 # Soft lower limit (8k) +CHUNK_MAX = 1024*1024 # Hard upper limit (1M) + +def guess_chunk(shape, maxshape, typesize): + """ Guess an appropriate chunk layout for a dataset, given its shape and + the size of each element in bytes. Will allocate chunks only as large + as MAX_SIZE. Chunks are generally close to some power-of-2 fraction of + each axis, slightly favoring bigger values for the last index. + + Undocumented and subject to change without warning. + """ + # pylint: disable=unused-argument + + # For unlimited dimensions we have to guess 1024 + shape = tuple((x if x!=0 else 1024) for i, x in enumerate(shape)) + + ndims = len(shape) + if ndims == 0: + raise ValueError("Chunks not allowed for scalar datasets.") + + chunks = np.array(shape, dtype='=f8') + if not np.all(np.isfinite(chunks)): + raise ValueError("Illegal value in chunk tuple") + + # Determine the optimal chunk size in bytes using a PyTables expression. + # This is kept as a float. + dset_size = product(chunks)*typesize + target_size = CHUNK_BASE * (2**np.log10(dset_size/(1024.*1024))) + + if target_size > CHUNK_MAX: + target_size = CHUNK_MAX + elif target_size < CHUNK_MIN: + target_size = CHUNK_MIN + + idx = 0 + while True: + # Repeatedly loop over the axes, dividing them by 2. Stop when: + # 1a. We're smaller than the target chunk size, OR + # 1b. We're within 50% of the target chunk size, AND + # 2. The chunk is smaller than the maximum chunk size + + chunk_bytes = product(chunks)*typesize + + if (chunk_bytes < target_size or \ + abs(chunk_bytes-target_size)/target_size < 0.5) and \ + chunk_bytes < CHUNK_MAX: + break + + if product(chunks) == 1: + break # Element size larger than CHUNK_MAX + + chunks[idx%ndims] = np.ceil(chunks[idx%ndims] / 2.0) + idx += 1 + + return tuple(int(x) for x in chunks) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/group.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/group.py new file mode 100644 index 0000000000000000000000000000000000000000..c185e30bafb1ba2281611bf7f072e87dcd6d642f --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/group.py @@ -0,0 +1,811 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Implements support for high-level access to HDF5 groups. +""" + +from contextlib import contextmanager +import posixpath as pp +import numpy + + +from .compat import filename_decode, filename_encode + +from .. import h5, h5g, h5i, h5o, h5r, h5t, h5l, h5p +from . import base +from .base import HLObject, MutableMappingHDF5, phil, with_phil +from . import dataset +from . import datatype +from .vds import vds_support + + +class Group(HLObject, MutableMappingHDF5): + + """ Represents an HDF5 group. + """ + + def __init__(self, bind): + """ Create a new Group object by binding to a low-level GroupID. + """ + with phil: + if not isinstance(bind, h5g.GroupID): + raise ValueError("%s is not a GroupID" % bind) + super().__init__(bind) + + def create_group(self, name, track_order=None, *, track_times=False): + """ Create and return a new subgroup. + + Name may be absolute or relative. Fails if the target name already + exists. + + track_order + Track dataset/group/attribute creation order under this group + if True. If None use global default h5.get_config().track_order. + track_times: bool or None, default: False + If True, store timestamps for this group in the file. + If None, fall back to the default value. + """ + if track_order is None: + track_order = h5.get_config().track_order + + with phil: + name, lcpl = self._e(name, lcpl=True) + gcpl = h5p.create(h5p.GROUP_CREATE) + if track_order: + order_flags = h5p.CRT_ORDER_TRACKED | h5p.CRT_ORDER_INDEXED + gcpl.set_link_creation_order(order_flags) + gcpl.set_attr_creation_order(order_flags) + if track_times is None: + track_times = False # Allow explicit None to mean h5py's default + if track_times in (True, False): + gcpl.set_obj_track_times(track_times) + else: + raise TypeError("track_times must be either True, False, or None") + gid = h5g.create(self.id, name, lcpl=lcpl, gcpl=gcpl) + return Group(gid) + + def create_dataset(self, name, shape=None, dtype=None, data=None, **kwds): + """ Create a new HDF5 dataset + + name + Name of the dataset (absolute or relative). Provide None to make + an anonymous dataset. + shape + Dataset shape. Use "()" for scalar datasets. Required if "data" + isn't provided. + dtype + Numpy dtype or string. If omitted, dtype('f') will be used. + Required if "data" isn't provided; otherwise, overrides data + array's dtype. + data + Provide data to initialize the dataset. If used, you can omit + shape and dtype arguments. + + Keyword-only arguments: + + chunks + (Tuple or int) Chunk shape, or True to enable auto-chunking. Integers can + be used for 1D shape. + + maxshape + (Tuple or int) Make the dataset resizable up to this shape. Use None for + axes within the tuple you want to be unlimited. Integers can be used for 1D shape. + For 1D datasets with unlimited maxshape, a shape tuple of length 1 must be + provided, ``(None,)``. Passing ``None`` sets ``maxshape` to `shape`, making the + dataset un-resizable, which is the default. + compression + (String or int) Compression strategy. Legal values are 'gzip', + 'szip', 'lzf'. If an integer in range(10), this indicates gzip + compression level. Otherwise, an integer indicates the number of a + dynamically loaded compression filter. + compression_opts + Compression settings. This is an integer for gzip, 2-tuple for + szip, etc. If specifying a dynamically loaded compression filter + number, this must be a tuple of values. + scaleoffset + (Integer) Enable scale/offset filter for (usually) lossy + compression of integer or floating-point data. For integer + data, the value of scaleoffset is the number of bits to + retain (pass 0 to let HDF5 determine the minimum number of + bits necessary for lossless compression). For floating point + data, scaleoffset is the number of digits after the decimal + place to retain; stored values thus have absolute error + less than 0.5*10**(-scaleoffset). + shuffle + (T/F) Enable shuffle filter. + fletcher32 + (T/F) Enable fletcher32 error detection. Not permitted in + conjunction with the scale/offset filter. + fillvalue + (Scalar) Use this value for uninitialized parts of the dataset. + track_times + (T/F) Enable dataset creation timestamps. + track_order + (T/F) Track attribute creation order if True. If omitted use + global default h5.get_config().track_order. + external + (Iterable of tuples) Sets the external storage property, thus + designating that the dataset will be stored in one or more + non-HDF5 files external to the HDF5 file. Adds each tuple + of (name, offset, size) to the dataset's list of external files. + Each name must be a str, bytes, or os.PathLike; each offset and + size, an integer. If only a name is given instead of an iterable + of tuples, it is equivalent to [(name, 0, h5py.h5f.UNLIMITED)]. + efile_prefix + (String) External dataset file prefix for dataset access property + list. Does not persist in the file. + virtual_prefix + (String) Virtual dataset file prefix for dataset access property + list. Does not persist in the file. + allow_unknown_filter + (T/F) Do not check that the requested filter is available for use. + This should only be used with ``write_direct_chunk``, where the caller + compresses the data before handing it to h5py. + rdcc_nbytes + Total size of the dataset's chunk cache in bytes. The default size + is 1024**2 (1 MiB) for HDF5 before 2.0 and 8 MiB for HDF5 2.0 or later. + rdcc_w0 + The chunk preemption policy for this dataset. This must be + between 0 and 1 inclusive and indicates the weighting according to + which chunks which have been fully read or written are penalized + when determining which chunks to flush from cache. A value of 0 + means fully read or written chunks are treated no differently than + other chunks (the preemption is strictly LRU) while a value of 1 + means fully read or written chunks are always preempted before + other chunks. If your application only reads or writes data once, + this can be safely set to 1. Otherwise, this should be set lower + depending on how often you re-read or re-write the same data. The + default value is 0.75. + rdcc_nslots + The number of chunk slots in the dataset's chunk cache. Increasing + this value reduces the number of cache collisions, but slightly + increases the memory used. Due to the hashing strategy, this value + should ideally be a prime number. As a rule of thumb, this value + should be at least 10 times the number of chunks that can fit in + rdcc_nbytes bytes. For maximum performance, this value should be set + approximately 100 times that number of chunks. The default value is + 521. + """ + if 'track_order' not in kwds: + kwds['track_order'] = h5.get_config().track_order + + if 'efile_prefix' in kwds: + kwds['efile_prefix'] = self._e(kwds['efile_prefix']) + + if 'virtual_prefix' in kwds: + kwds['virtual_prefix'] = self._e(kwds['virtual_prefix']) + + with phil: + group = self + if name: + name = self._e(name) + if b'/' in name.lstrip(b'/'): + parent_path, name = name.rsplit(b'/', 1) + group = self.require_group(parent_path) + + dsid = dataset.make_new_dset(group, shape, dtype, data, name, **kwds) + dset = dataset.Dataset(dsid) + return dset + + if vds_support: + def create_virtual_dataset(self, name, layout, fillvalue=None): + """Create a new virtual dataset in this group. + + See virtual datasets in the docs for more information. + + name + (str) Name of the new dataset + + layout + (VirtualLayout) Defines the sources for the virtual dataset + + fillvalue + The value to use where there is no data. + + """ + with phil: + group = self + + if name: + name = self._e(name) + if b'/' in name.lstrip(b'/'): + parent_path, name = name.rsplit(b'/', 1) + group = self.require_group(parent_path) + + dsid = layout.make_dataset( + group, name=name, fillvalue=fillvalue, + ) + dset = dataset.Dataset(dsid) + + return dset + + @contextmanager + def build_virtual_dataset( + self, name, shape, dtype, maxshape=None, fillvalue=None + ): + """Assemble a virtual dataset in this group. + + This is used as a context manager:: + + with f.build_virtual_dataset('virt', (10, 1000), np.uint32) as layout: + layout[0] = h5py.VirtualSource('foo.h5', 'data', (1000,)) + + name + (str) Name of the new dataset + shape + (tuple) Shape of the dataset + dtype + A numpy dtype for data read from the virtual dataset + maxshape + (tuple, optional) Maximum dimensions if the dataset can grow. + Use None for unlimited dimensions. + fillvalue + The value used where no data is available. + """ + from .vds import VirtualLayout + layout = VirtualLayout(shape, dtype, maxshape, self.file.filename) + yield layout + + self.create_virtual_dataset(name, layout, fillvalue) + + def require_dataset(self, name, shape, dtype, exact=False, **kwds): + """ Open a dataset, creating it if it doesn't exist. + + If keyword "exact" is False (default), an existing dataset must have + the same shape and a conversion-compatible dtype to be returned. If + True, the shape and dtype must match exactly. + + If keyword "maxshape" is given, the maxshape and dtype must match + instead. + + If any of the keywords "rdcc_nslots", "rdcc_nbytes", or "rdcc_w0" are + given, they will be used to configure the dataset's chunk cache. + + Other dataset keywords (see create_dataset) may be provided, but are + only used if a new dataset is to be created. + + Raises TypeError if an incompatible object already exists, or if the + shape, maxshape or dtype don't match according to the above rules. + """ + if 'efile_prefix' in kwds: + kwds['efile_prefix'] = self._e(kwds['efile_prefix']) + + if 'virtual_prefix' in kwds: + kwds['virtual_prefix'] = self._e(kwds['virtual_prefix']) + + with phil: + if name not in self: + return self.create_dataset(name, *(shape, dtype), **kwds) + + if isinstance(shape, int): + shape = (shape,) + + try: + dsid = dataset.open_dset(self, self._e(name), **kwds) + dset = dataset.Dataset(dsid) + except KeyError as exc: + dset = self[name] + raise TypeError(f"Incompatible object ({dset.__class__.__name__}) already exists") from exc + + if shape != dset.shape: + if "maxshape" not in kwds: + raise TypeError("Shapes do not match (existing %s vs new %s)" % (dset.shape, shape)) + elif kwds["maxshape"] != dset.maxshape: + raise TypeError("Max shapes do not match (existing %s vs new %s)" % (dset.maxshape, kwds["maxshape"])) + + if exact: + if dtype != dset.dtype: + raise TypeError("Datatypes do not exactly match (existing %s vs new %s)" % (dset.dtype, dtype)) + elif not numpy.can_cast(dtype, dset.dtype): + raise TypeError("Datatypes cannot be safely cast (existing %s vs new %s)" % (dset.dtype, dtype)) + + return dset + + def create_dataset_like(self, name, other, **kwupdate): + """ Create a dataset similar to `other`. + + name + Name of the dataset (absolute or relative). Provide None to make + an anonymous dataset. + other + The dataset which the new dataset should mimic. All properties, such + as shape, dtype, chunking, ... will be taken from it, but no data + or attributes are being copied. + + Any dataset keywords (see create_dataset) may be provided, including + shape and dtype, in which case the provided values take precedence over + those from `other`. + """ + for k in ('shape', 'dtype', 'chunks', 'compression', + 'compression_opts', 'scaleoffset', 'shuffle', 'fletcher32', + 'fillvalue'): + kwupdate.setdefault(k, getattr(other, k)) + # TODO: more elegant way to pass these (dcpl to create_dataset?) + dcpl = other.id.get_create_plist() + kwupdate.setdefault('track_times', dcpl.get_obj_track_times()) + kwupdate.setdefault('track_order', dcpl.get_attr_creation_order() > 0) + + # Special case: the maxshape property always exists, but if we pass it + # to create_dataset, the new dataset will automatically get chunked + # layout. So we copy it only if it is different from shape. + if other.maxshape != other.shape: + kwupdate.setdefault('maxshape', other.maxshape) + + return self.create_dataset(name, **kwupdate) + + def require_group(self, name): + # TODO: support kwargs like require_dataset + """Return a group, creating it if it doesn't exist. + + TypeError is raised if something with that name already exists that + isn't a group. + """ + with phil: + if name not in self: + return self.create_group(name) + grp = self[name] + if not isinstance(grp, Group): + raise TypeError("Incompatible object (%s) already exists" % grp.__class__.__name__) + return grp + + @with_phil + def __getitem__(self, name): + """ Open an object in the file """ + + if isinstance(name, h5r.Reference): + oid = h5r.dereference(name, self.id) + if oid is None: + raise ValueError("Invalid HDF5 object reference") + elif isinstance(name, (bytes, str)): + oid = h5o.open(self.id, self._e(name), lapl=self._lapl) + else: + raise TypeError("Accessing a group is done with bytes or str, " + "not {}".format(type(name))) + + otype = h5i.get_type(oid) + if otype == h5i.GROUP: + return Group(oid) + elif otype == h5i.DATASET: + return dataset.Dataset(oid, readonly=(self.file.mode == 'r')) + elif otype == h5i.DATATYPE: + return datatype.Datatype(oid) + else: + raise TypeError("Unknown object type") + + def get(self, name, default=None, getclass=False, getlink=False): + """ Retrieve an item or other information. + + "name" given only: + Return the item, or "default" if it doesn't exist + + "getclass" is True: + Return the class of object (Group, Dataset, etc.), or "default" + if nothing with that name exists + + "getlink" is True: + Return HardLink, SoftLink or ExternalLink instances. Return + "default" if nothing with that name exists. + + "getlink" and "getclass" are True: + Return HardLink, SoftLink and ExternalLink classes. Return + "default" if nothing with that name exists. + + Example: + + >>> cls = group.get('foo', getclass=True) + >>> if cls == SoftLink: + """ + # pylint: disable=arguments-differ + + with phil: + if not (getclass or getlink): + try: + return self[name] + except KeyError: + return default + + if name not in self: + return default + + elif getclass and not getlink: + typecode = h5o.get_info(self.id, self._e(name), lapl=self._lapl).type + + try: + return {h5o.TYPE_GROUP: Group, + h5o.TYPE_DATASET: dataset.Dataset, + h5o.TYPE_NAMED_DATATYPE: datatype.Datatype}[typecode] + except KeyError as exc: + raise TypeError("Unknown object type") from exc + + elif getlink: + typecode = self.id.links.get_info(self._e(name), lapl=self._lapl).type + + if typecode == h5l.TYPE_SOFT: + if getclass: + return SoftLink + linkbytes = self.id.links.get_val(self._e(name), lapl=self._lapl) + return SoftLink(self._d(linkbytes)) + + elif typecode == h5l.TYPE_EXTERNAL: + if getclass: + return ExternalLink + filebytes, linkbytes = self.id.links.get_val(self._e(name), lapl=self._lapl) + return ExternalLink( + filename_decode(filebytes), self._d(linkbytes) + ) + + elif typecode == h5l.TYPE_HARD: + return HardLink if getclass else HardLink() + + else: + raise TypeError("Unknown link type") + + def __setitem__(self, name, obj): + """ Add an object to the group. The name must not already be in use. + + The action taken depends on the type of object assigned: + + Named HDF5 object (Dataset, Group, Datatype) + A hard link is created at "name" which points to the + given object. + + SoftLink or ExternalLink + Create the corresponding link. + + Numpy ndarray + The array is converted to a dataset object, with default + settings (contiguous storage, etc.). + + Numpy dtype + Commit a copy of the datatype as a named datatype in the file. + + Anything else + Attempt to convert it to an ndarray and store it. Scalar + values are stored as scalar datasets. Raise ValueError if we + can't understand the resulting array dtype. + """ + with phil: + name, lcpl = self._e(name, lcpl=True) + + if isinstance(obj, HLObject): + h5o.link(obj.id, self.id, name, lcpl=lcpl, lapl=self._lapl) + + elif isinstance(obj, SoftLink): + self.id.links.create_soft(name, self._e(obj.path), lcpl=lcpl, lapl=self._lapl) + + elif isinstance(obj, ExternalLink): + fn = filename_encode(obj.filename) + self.id.links.create_external(name, fn, self._e(obj.path), + lcpl=lcpl, lapl=self._lapl) + + elif isinstance(obj, numpy.dtype): + htype = h5t.py_create(obj, logical=True) + htype.commit(self.id, name, lcpl=lcpl) + + else: + ds = self.create_dataset(None, data=obj) + h5o.link(ds.id, self.id, name, lcpl=lcpl) + + @with_phil + def __delitem__(self, name): + """ Delete (unlink) an item from this group. """ + self.id.unlink(self._e(name)) + + @with_phil + def __len__(self): + """ Number of members attached to this group """ + return self.id.get_num_objs() + + @with_phil + def __iter__(self): + """ Iterate over member names """ + for x in self.id.__iter__(): + yield self._d(x) + + @with_phil + def __reversed__(self): + """ Iterate over member names in reverse order. """ + for x in self.id.__reversed__(): + yield self._d(x) + + @with_phil + def __contains__(self, name): + """ Test if a member name exists """ + if hasattr(h5g, "_path_valid"): + if not self.id: + return False + return h5g._path_valid(self.id, self._e(name), self._lapl) + return self._e(name) in self.id + + def copy(self, source, dest, name=None, + shallow=False, expand_soft=False, expand_external=False, + expand_refs=False, without_attrs=False): + """Copy an object or group. + + The source can be a path, Group, Dataset, or Datatype object. The + destination can be either a path or a Group object. The source and + destinations need not be in the same file. + + If the source is a Group object, all objects contained in that group + will be copied recursively. + + When the destination is a Group object, by default the target will + be created in that group with its current name (basename of obj.name). + You can override that by setting "name" to a string. + + There are various options which all default to "False": + + - shallow: copy only immediate members of a group. + + - expand_soft: expand soft links into new objects. + + - expand_external: expand external links into new objects. + + - expand_refs: copy objects that are pointed to by references. + + - without_attrs: copy object without copying attributes. + + Example: + + >>> f = File('myfile.hdf5', 'w') + >>> f.create_group("MyGroup") + >>> list(f.keys()) + ['MyGroup'] + >>> f.copy('MyGroup', 'MyCopy') + >>> list(f.keys()) + ['MyGroup', 'MyCopy'] + + """ + with phil: + if isinstance(source, HLObject): + source_path = '.' + else: + # Interpret source as a path relative to this group + source_path = source + source = self + + if isinstance(dest, Group): + if name is not None: + dest_path = name + elif source_path == '.': + dest_path = pp.basename(h5i.get_name(source.id)) + else: + # copy source into dest group: dest_name/source_name + dest_path = pp.basename(h5i.get_name(source[source_path].id)) + + elif isinstance(dest, HLObject): + raise TypeError("Destination must be path or Group object") + else: + # Interpret destination as a path relative to this group + dest_path = dest + dest = self + + flags = 0 + if shallow: + flags |= h5o.COPY_SHALLOW_HIERARCHY_FLAG + if expand_soft: + flags |= h5o.COPY_EXPAND_SOFT_LINK_FLAG + if expand_external: + flags |= h5o.COPY_EXPAND_EXT_LINK_FLAG + if expand_refs: + flags |= h5o.COPY_EXPAND_REFERENCE_FLAG + if without_attrs: + flags |= h5o.COPY_WITHOUT_ATTR_FLAG + if flags: + copypl = h5p.create(h5p.OBJECT_COPY) + copypl.set_copy_object(flags) + else: + copypl = None + + h5o.copy(source.id, self._e(source_path), dest.id, self._e(dest_path), + copypl, base.dlcpl) + + def move(self, source, dest): + """ Move a link to a new location in the file. + + If "source" is a hard link, this effectively renames the object. If + "source" is a soft or external link, the link itself is moved, with its + value unmodified. + """ + with phil: + if source == dest: + return + self.id.links.move(self._e(source), self.id, self._e(dest), + lapl=self._lapl, lcpl=self._lcpl) + + def visit(self, func): + """ Recursively visit all names in this group and subgroups. + + Note: visit ignores soft and external links. To visit those, use + visit_links. + + You supply a callable (function, method or callable object); it + will be called exactly once for each link in this group and every + group below it. Your callable must conform to the signature: + + func() => + + Returning None continues iteration, returning anything else stops + and immediately returns that value from the visit method. The + iteration order is lexicographic. + + Example: + + >>> # List the entire contents of the file + >>> f = File("foo.hdf5") + >>> list_of_names = [] + >>> f.visit(list_of_names.append) + """ + with phil: + def proxy(name): + """ Call the function with the text name, not bytes """ + return func(self._d(name)) + return h5o.visit(self.id, proxy) + + def visititems(self, func): + """ Recursively visit names and objects in this group. + + Note: visititems ignores soft and external links. To visit those, use + visititems_links. + + You supply a callable (function, method or callable object); it + will be called exactly once for each link in this group and every + group below it. Your callable must conform to the signature: + + func(, ) => + + Returning None continues iteration, returning anything else stops + and immediately returns that value from the visit method. The + iteration order is lexicographic. + + Example: + + # Get a list of all datasets in the file + >>> mylist = [] + >>> def func(name, obj): + ... if isinstance(obj, Dataset): + ... mylist.append(name) + ... + >>> f = File('foo.hdf5') + >>> f.visititems(func) + """ + with phil: + def proxy(name): + """ Use the text name of the object, not bytes """ + name = self._d(name) + return func(name, self[name]) + return h5o.visit(self.id, proxy) + + def visit_links(self, func): + """ Recursively visit all names in this group and subgroups. + Each link will be visited exactly once, regardless of its target. + + You supply a callable (function, method or callable object); it + will be called exactly once for each link in this group and every + group below it. Your callable must conform to the signature: + + func() => + + Returning None continues iteration, returning anything else stops + and immediately returns that value from the visit method. The + iteration order is lexicographic. + + Example: + + >>> # List the entire contents of the file + >>> f = File("foo.hdf5") + >>> list_of_names = [] + >>> f.visit_links(list_of_names.append) + """ + with phil: + def proxy(name): + """ Call the function with the text name, not bytes """ + return func(self._d(name)) + return self.id.links.visit(proxy) + + def visititems_links(self, func): + """ Recursively visit links in this group. + Each link will be visited exactly once, regardless of its target. + + You supply a callable (function, method or callable object); it + will be called exactly once for each link in this group and every + group below it. Your callable must conform to the signature: + + func(, ) => + + Returning None continues iteration, returning anything else stops + and immediately returns that value from the visit method. The + iteration order is lexicographic. + + Example: + + # Get a list of all softlinks in the file + >>> mylist = [] + >>> def func(name, link): + ... if isinstance(link, SoftLink): + ... mylist.append(name) + ... + >>> f = File('foo.hdf5') + >>> f.visititems_links(func) + """ + with phil: + def proxy(name): + """ Use the text name of the object, not bytes """ + name = self._d(name) + return func(name, self.get(name, getlink=True)) + return self.id.links.visit(proxy) + + @with_phil + def __repr__(self): + if not self: + r = u"" + else: + namestr = ( + '"%s"' % self.name + ) if self.name is not None else u"(anonymous)" + r = '' % (namestr, len(self)) + + return r + + +class HardLink: + + """ + Represents a hard link in an HDF5 file. Provided only so that + Group.get works in a sensible way. Has no other function. + """ + + pass + + +class SoftLink: + + """ + Represents a symbolic ("soft") link in an HDF5 file. The path + may be absolute or relative. No checking is performed to ensure + that the target actually exists. + """ + + @property + def path(self): + """ Soft link value. Not guaranteed to be a valid path. """ + return self._path + + def __init__(self, path): + self._path = str(path) + + def __repr__(self): + return '' % self.path + + +class ExternalLink: + + """ + Represents an HDF5 external link. Paths may be absolute or relative. + No checking is performed to ensure either the target or file exists. + """ + + @property + def path(self): + """ Soft link path, i.e. the part inside the HDF5 file. """ + return self._path + + @property + def filename(self): + """ Path to the external HDF5 file in the filesystem. """ + return self._filename + + def __init__(self, filename, path): + self._filename = filename_decode(filename_encode(filename)) + self._path = path + + def __repr__(self): + return ' Create a new selection on "shape"-tuple + __getitem__(args) => Perform a selection with the range specified. + What args are allowed depends on the + particular subclass in use. + + id (read-only) => h5py.h5s.SpaceID instance + shape (read-only) => The shape of the dataspace. + mshape (read-only) => The shape of the selection region. + Not guaranteed to fit within "shape", although + the total number of points is less than + product(shape). + nselect (read-only) => Number of selected points. Always equal to + product(mshape). + + broadcast(target_shape) => Return an iterable which yields dataspaces + for read, based on target_shape. + + The base class represents "unshaped" selections (1-D). + """ + + def __init__(self, shape, spaceid=None): + """ Create a selection. Shape may be None if spaceid is given. """ + if spaceid is not None: + self._id = spaceid + self._shape = spaceid.shape + else: + shape = tuple(shape) + self._shape = shape + self._id = h5s.create_simple(shape, (h5s.UNLIMITED,)*len(shape)) + self._id.select_all() + + @property + def id(self): + """ SpaceID instance """ + return self._id + + @property + def shape(self): + """ Shape of whole dataspace """ + return self._shape + + @property + def nselect(self): + """ Number of elements currently selected """ + return self._id.get_select_npoints() + + @property + def mshape(self): + """ Shape of selection (always 1-D for this class) """ + return (self.nselect,) + + @property + def array_shape(self): + """Shape of array to read/write (always 1-D for this class)""" + return self.mshape + + # expand_shape and broadcast only really make sense for SimpleSelection + def expand_shape(self, source_shape): + if product(source_shape) != self.nselect: + raise TypeError("Broadcasting is not supported for point-wise selections") + return source_shape + + def broadcast(self, source_shape): + """ Get an iterable for broadcasting """ + if product(source_shape) != self.nselect: + raise TypeError("Broadcasting is not supported for point-wise selections") + yield self._id + + def __getitem__(self, args): + raise NotImplementedError("This class does not support indexing") + +class PointSelection(Selection): + + """ + Represents a point-wise selection. You can supply sequences of + points to the three methods append(), prepend() and set(), or + instantiate it with a single boolean array using from_mask(). + """ + def __init__(self, shape, spaceid=None, points=None): + super().__init__(shape, spaceid) + if points is not None: + self._perform_selection(points, h5s.SELECT_SET) + + def _perform_selection(self, points, op): + """ Internal method which actually performs the selection """ + points = np.asarray(points, order='C', dtype='u8') + if len(points.shape) == 1: + points.shape = (1,points.shape[0]) + + if self._id.get_select_type() != h5s.SEL_POINTS: + op = h5s.SELECT_SET + + if len(points) == 0: + self._id.select_none() + else: + self._id.select_elements(points, op) + + @classmethod + def from_mask(cls, mask, spaceid=None): + """Create a point-wise selection from a NumPy boolean array """ + if not (isinstance(mask, np.ndarray) and mask.dtype.kind == 'b'): + raise TypeError("PointSelection.from_mask only works with bool arrays") + + points = np.transpose(mask.nonzero()) + return cls(mask.shape, spaceid, points=points) + + def append(self, points): + """ Add the sequence of points to the end of the current selection """ + self._perform_selection(points, h5s.SELECT_APPEND) + + def prepend(self, points): + """ Add the sequence of points to the beginning of the current selection """ + self._perform_selection(points, h5s.SELECT_PREPEND) + + def set(self, points): + """ Replace the current selection with the given sequence of points""" + self._perform_selection(points, h5s.SELECT_SET) + + +class SimpleSelection(Selection): + + """ A single "rectangular" (regular) selection composed of only slices + and integer arguments. Can participate in broadcasting. + """ + + @property + def mshape(self): + """ Shape of current selection """ + return self._sel[1] + + @property + def array_shape(self): + scalar = self._sel[3] + return tuple(x for x, s in zip(self.mshape, scalar, strict=True) if not s) + + def __init__(self, shape, spaceid=None, hyperslab=None): + super().__init__(shape, spaceid) + if hyperslab is not None: + self._sel = hyperslab + else: + # No hyperslab specified - select all + rank = len(self.shape) + self._sel = ((0,)*rank, self.shape, (1,)*rank, (False,)*rank) + + def expand_shape(self, source_shape): + """Match the dimensions of an array to be broadcast to the selection + + The returned shape describes an array of the same size as the input + shape, but its dimensions + + E.g. with a dataset shape (10, 5, 4, 2), writing like this:: + + ds[..., 0] = np.ones((5, 4)) + + The source shape (5, 4) will expand to (1, 5, 4, 1). + Then the broadcast method below repeats that chunk 10 + times to write to an effective shape of (10, 5, 4, 1). + """ + start, count, step, scalar = self._sel + + rank = len(count) + remaining_src_dims = list(source_shape) + + eshape = [] + for idx in range(1, rank + 1): + if len(remaining_src_dims) == 0 or scalar[-idx]: # Skip scalar axes + eshape.append(1) + else: + t = remaining_src_dims.pop() + if t == 1 or count[-idx] == t: + eshape.append(t) + else: + raise TypeError("Can't broadcast %s -> %s" % (source_shape, self.array_shape)) # array shape + + if any([n > 1 for n in remaining_src_dims]): + # All dimensions from target_shape should either have been popped + # to match the selection shape, or be 1. + raise TypeError("Can't broadcast %s -> %s" % (source_shape, self.array_shape)) # array shape + + # We have built eshape backwards, so now reverse it + return tuple(eshape[::-1]) + + + def broadcast(self, source_shape): + """ Return an iterator over target dataspaces for broadcasting. + + Follows the standard NumPy broadcasting rules against the current + selection shape (self.mshape). + """ + if self.shape == (): + if product(source_shape) != 1: + raise TypeError("Can't broadcast %s to scalar" % source_shape) + self._id.select_all() + yield self._id + return + + start, count, step, scalar = self._sel + + rank = len(count) + tshape = self.expand_shape(source_shape) + + # Avoid ZeroDivisionError below (after the shape checks in expand_source) + if any(d == 0 for d in count): + return + + chunks = tuple(x//y for x, y in zip(count, tshape, strict=True)) + nchunks = product(chunks) + + if nchunks == 1: + yield self._id + else: + sid = self._id.copy() + sid.select_hyperslab((0,)*rank, tshape, step) + for idx in range(nchunks): + offset = tuple(x*y*z + s for x, y, z, s in zip(np.unravel_index(idx, chunks), tshape, step, start, strict=True)) + sid.offset_simple(offset) + yield sid + + +class FancySelection(Selection): + + """ + Implements advanced NumPy-style selection operations in addition to + the standard slice-and-int behavior. + + Indexing arguments may be ints, slices, lists of indices, or + per-axis (1D) boolean arrays. + + Broadcasting is not supported for these selections. + """ + + @property + def mshape(self): + return self._mshape + + @property + def array_shape(self): + return self._array_shape + + def __init__(self, shape, spaceid=None, mshape=None, array_shape=None): + super().__init__(shape, spaceid) + if mshape is None: + mshape = self.shape + if array_shape is None: + array_shape = mshape + self._mshape = mshape + self._array_shape = array_shape + + def expand_shape(self, source_shape): + if not source_shape == self.array_shape: + raise TypeError("Broadcasting is not supported for complex selections") + return source_shape + + def broadcast(self, source_shape): + if not source_shape == self.array_shape: + raise TypeError("Broadcasting is not supported for complex selections") + yield self._id + + +def guess_shape(sid): + """ Given a dataspace, try to deduce the shape of the selection. + + Returns one of: + * A tuple with the selection shape, same length as the dataspace + * A 1D selection shape for point-based and multiple-hyperslab selections + * None, for unselected scalars and for NULL dataspaces + """ + + sel_class = sid.get_simple_extent_type() # Dataspace class + sel_type = sid.get_select_type() # Flavor of selection in use + + if sel_class == h5s.NULL: + # NULL dataspaces don't support selections + return None + + elif sel_class == h5s.SCALAR: + # NumPy has no way of expressing empty 0-rank selections, so we use None + if sel_type == h5s.SEL_NONE: return None + if sel_type == h5s.SEL_ALL: return tuple() + + elif sel_class != h5s.SIMPLE: + raise TypeError("Unrecognized dataspace class %s" % sel_class) + + # We have a "simple" (rank >= 1) dataspace + + N = sid.get_select_npoints() + rank = len(sid.shape) + + if sel_type == h5s.SEL_NONE: + return (0,)*rank + + elif sel_type == h5s.SEL_ALL: + return sid.shape + + elif sel_type == h5s.SEL_POINTS: + # Like NumPy, point-based selections yield 1D arrays regardless of + # the dataspace rank + return (N,) + + elif sel_type != h5s.SEL_HYPERSLABS: + raise TypeError("Unrecognized selection method %s" % sel_type) + + # We have a hyperslab-based selection + + if N == 0: + return (0,)*rank + + bottomcorner, topcorner = (np.array(x) for x in sid.get_select_bounds()) + + # Shape of full selection box + boxshape = topcorner - bottomcorner + np.ones((rank,)) + + def get_n_axis(sid, axis): + """ Determine the number of elements selected along a particular axis. + + To do this, we "mask off" the axis by making a hyperslab selection + which leaves only the first point along the axis. For a 2D dataset + with selection box shape (X, Y), for axis 1, this would leave a + selection of shape (X, 1). We count the number of points N_leftover + remaining in the selection and compute the axis selection length by + N_axis = N/N_leftover. + """ + + if(boxshape[axis]) == 1: + return 1 + + start = bottomcorner.copy() + start[axis] += 1 + count = boxshape.copy() + count[axis] -= 1 + + # Throw away all points along this axis + masked_sid = sid.copy() + masked_sid.select_hyperslab(tuple(start), tuple(count), op=h5s.SELECT_NOTB) + + N_leftover = masked_sid.get_select_npoints() + + return N//N_leftover + + + shape = tuple(get_n_axis(sid, x) for x in range(rank)) + + if product(shape) != N: + # This means multiple hyperslab selections are in effect, + # so we fall back to a 1D shape + return (N,) + + return shape diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/selections2.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/selections2.py new file mode 100644 index 0000000000000000000000000000000000000000..e28224d43751dbd5dba56dce562c8573404cf583 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/selections2.py @@ -0,0 +1,103 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Implements a portion of the selection operations. +""" + +import numpy as np +from .. import h5s + +def read_dtypes(dataset_dtype, names): + """ Returns a 2-tuple containing: + + 1. Output dataset dtype + 2. Dtype containing HDF5-appropriate description of destination + """ + + if len(names) == 0: # Not compound, or all fields needed + format_dtype = dataset_dtype + + elif dataset_dtype.names is None: + raise ValueError("Field names only allowed for compound types") + + elif any(x not in dataset_dtype.names for x in names): + raise ValueError("Field does not appear in this type.") + + else: + format_dtype = np.dtype([(name, dataset_dtype.fields[name][0]) for name in names]) + + if len(names) == 1: + # We don't preserve the field information if only one explicitly selected. + output_dtype = format_dtype.fields[names[0]][0] + + else: + output_dtype = format_dtype + + return output_dtype, format_dtype + + +def read_selections_scalar(dsid, args): + """ Returns a 2-tuple containing: + + 1. Output dataset shape + 2. HDF5 dataspace containing source selection. + + Works for scalar datasets. + """ + + if dsid.shape != (): + raise RuntimeError("Illegal selection function for non-scalar dataset") + + if args == (): + # This is a signal that an array scalar should be returned instead + # of an ndarray with shape () + out_shape = None + + elif args == (Ellipsis,): + out_shape = () + + else: + raise ValueError("Illegal slicing argument for scalar dataspace") + + source_space = dsid.get_space() + source_space.select_all() + + return out_shape, source_space + +class ScalarReadSelection: + + """ + Implements slicing for scalar datasets. + """ + + def __init__(self, fspace, args): + if args == (): + self.mshape = None + elif args == (Ellipsis,): + self.mshape = () + else: + raise ValueError("Illegal slicing argument for scalar dataspace") + + self.mspace = h5s.create(h5s.SCALAR) + self.fspace = fspace + + def __iter__(self): + self.mspace.select_all() + yield self.fspace, self.mspace + +def select_read(fspace, args): + """ Top-level dispatch function for reading. + + At the moment, only supports reading from scalar datasets. + """ + if fspace.shape == (): + return ScalarReadSelection(fspace, args) + + raise NotImplementedError() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/vds.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/vds.py new file mode 100644 index 0000000000000000000000000000000000000000..fac9c3be88488e694449552c1b1e9cc565808922 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_hl/vds.py @@ -0,0 +1,250 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + High-level interface for creating HDF5 virtual datasets +""" + +from copy import deepcopy as copy +from collections import namedtuple + +import numpy as np + +from .compat import filename_encode +from .datatype import Datatype +from .selections import SimpleSelection, select +from .. import h5d, h5p, h5s, h5t + + +class VDSmap(namedtuple('VDSmap', ('vspace', 'file_name', + 'dset_name', 'src_space'))): + '''Defines a region in a virtual dataset mapping to part of a source dataset + ''' + + +vds_support = True + + +def _convert_space_for_key(space, key): + """ + Converts the space with the given key. Mainly used to allow unlimited + dimensions in virtual space selection. + """ + key = key if isinstance(key, tuple) else (key,) + type_code = space.get_select_type() + + # check for unlimited selections in case where selection is regular + # hyperslab, which is the only allowed case for h5s.UNLIMITED to be + # in the selection + if type_code == h5s.SEL_HYPERSLABS and space.is_regular_hyperslab(): + rank = space.get_simple_extent_ndims() + nargs = len(key) + + idx_offset = 0 + start, stride, count, block = space.get_regular_hyperslab() + # iterate through keys. we ignore numeral indices. if we get a + # slice, we check for an h5s.UNLIMITED value as the stop + # if we get an ellipsis, we offset index by (rank - nargs) + for i, sl in enumerate(key): + if isinstance(sl, slice): + if sl.stop == h5s.UNLIMITED: + counts = list(count) + idx = i + idx_offset + counts[idx] = h5s.UNLIMITED + count = tuple(counts) + elif sl is Ellipsis: + idx_offset = rank - nargs + + space.select_hyperslab(start, count, stride, block) + + +class VirtualSource: + """Source definition for virtual data sets. + + Instantiate this class to represent an entire source dataset, and then + slice it to indicate which regions should be used in the virtual dataset. + + path_or_dataset + The path to a file, or an h5py dataset. If a dataset is given, + no other parameters are allowed, as the relevant values are taken from + the dataset instead. + name + The name of the source dataset within the file. + shape + A tuple giving the shape of the dataset. + dtype + Numpy dtype or string. + maxshape + The source dataset is resizable up to this shape. Use None for + axes you want to be unlimited. + """ + def __init__(self, path_or_dataset, name=None, + shape=None, dtype=None, maxshape=None): + from .dataset import Dataset + if isinstance(path_or_dataset, Dataset): + failed = {k: v + for k, v in + {'name': name, 'shape': shape, + 'dtype': dtype, 'maxshape': maxshape}.items() + if v is not None} + if failed: + raise TypeError("If a Dataset is passed as the first argument " + "then no other arguments may be passed. You " + "passed {failed}".format(failed=failed)) + ds = path_or_dataset + path = ds.file.filename + name = ds.name + shape = ds.shape + dtype = ds.dtype + maxshape = ds.maxshape + else: + path = path_or_dataset + if name is None: + raise TypeError("The name parameter is required when " + "specifying a source by path") + if shape is None: + raise TypeError("The shape parameter is required when " + "specifying a source by path") + elif isinstance(shape, int): + shape = (shape,) + + if isinstance(maxshape, int): + maxshape = (maxshape,) + + self.path = path + self.name = name + self.dtype = dtype + + if maxshape is None: + self.maxshape = shape + else: + self.maxshape = tuple([h5s.UNLIMITED if ix is None else ix + for ix in maxshape]) + self.sel = SimpleSelection(shape) + self._all_selected = True + + @property + def shape(self): + return self.sel.array_shape + + def __getitem__(self, key): + if not self._all_selected: + raise RuntimeError("VirtualSource objects can only be sliced once.") + tmp = copy(self) + tmp.sel = select(self.shape, key, dataset=None) + _convert_space_for_key(tmp.sel.id, key) + tmp._all_selected = False + return tmp + +class VirtualLayout: + """Object for building a virtual dataset. + + Instantiate this class to define a virtual dataset, assign to slices of it + (using VirtualSource objects), and then pass it to + group.create_virtual_dataset() to add the virtual dataset to a file. + + This class does not allow access to the data; the virtual dataset must + be created in a file before it can be used. + + shape + A tuple giving the shape of the dataset. + dtype + Numpy dtype or string. + maxshape + The virtual dataset is resizable up to this shape. Use None for + axes you want to be unlimited. + filename + The name of the destination file, if known in advance. Mappings from + data in the same file will be stored with filename '.', allowing the + file to be renamed later. + """ + def __init__(self, shape, dtype, maxshape=None, filename=None): + self.shape = (shape,) if isinstance(shape, int) else shape + self.dtype = dtype + self.maxshape = (maxshape,) if isinstance(maxshape, int) else maxshape + self._filename = filename + self._src_filenames = set() + self.dcpl = h5p.create(h5p.DATASET_CREATE) + self.dcpl.set_layout(h5d.VIRTUAL) + + def __setitem__(self, key, source): + sel = select(self.shape, key, dataset=None) + _convert_space_for_key(sel.id, key) + src_filename = self._source_file_name(source.path, self._filename) + + self.dcpl.set_virtual( + sel.id, src_filename, source.name.encode('utf-8'), source.sel.id + ) + if self._filename is None: + self._src_filenames.add(src_filename) + + @staticmethod + def _source_file_name(src_filename, dst_filename) -> bytes: + src_filename = filename_encode(src_filename) + if dst_filename and (src_filename == filename_encode(dst_filename)): + # use relative path if the source dataset is in the same + # file, in order to keep the virtual dataset valid in case + # the file is renamed. + return b'.' + return filename_encode(src_filename) + + def _get_dcpl(self, dst_filename): + """Get the property list containing virtual dataset mappings + + If the destination filename wasn't known when the VirtualLayout was + created, it is handled here. + """ + dst_filename = filename_encode(dst_filename) + if self._filename is not None: + # filename was known in advance; check dst_filename matches + if dst_filename != filename_encode(self._filename): + raise Exception(f"{dst_filename!r} != {self._filename!r}") + return self.dcpl + + # destination file not known in advance + if dst_filename in self._src_filenames: + # At least 1 source file is the same as the destination file, + # but we didn't know this when making the mapping. Copy the mappings + # to a new property list, replacing the dest filename with '.' + new_dcpl = h5p.create(h5p.DATASET_CREATE) + new_dcpl.set_layout(h5d.VIRTUAL) + for i in range(self.dcpl.get_virtual_count()): + src_filename = self.dcpl.get_virtual_filename(i) + new_dcpl.set_virtual( + self.dcpl.get_virtual_vspace(i), + self._source_file_name(src_filename, dst_filename), + self.dcpl.get_virtual_dsetname(i).encode('utf-8'), + self.dcpl.get_virtual_srcspace(i), + ) + return new_dcpl + else: + return self.dcpl # Mappings are all from other files + + def make_dataset(self, parent, name, fillvalue=None): + """ Return a new low-level dataset identifier for a virtual dataset """ + dcpl = self._get_dcpl(parent.file.filename) + + if fillvalue is not None: + dcpl.set_fill_value(np.array([fillvalue])) + + maxshape = self.maxshape + if maxshape is not None: + maxshape = tuple(m if m is not None else h5s.UNLIMITED for m in maxshape) + + virt_dspace = h5s.create_simple(self.shape, maxshape) + + if isinstance(self.dtype, Datatype): + # Named types are used as-is + tid = self.dtype.id + else: + dtype = np.dtype(self.dtype) + tid = h5t.py_create(dtype, logical=1) + + return h5d.create(parent.id, name=name, tid=tid, space=virt_dspace, + dcpl=dcpl) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_npystrings.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_npystrings.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..4e8e9861371ebb85e310219ae888ecc5d91f03f6 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_npystrings.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e538080a2e0ba91b628b230e73a2039d74549ac16108407d77d06eff5ada0112 +size 154713 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_objects.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_objects.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..20d8645fcd2fc651da459852f496aab45460830b --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_objects.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:45aed78e67ec2f23438f5676a40a13251ef685486a44351aa2c54170b7d5c372 +size 336073 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_proxy.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_proxy.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..4d7d2088c9c1a87a72743401d72700ef23f9eac7 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_proxy.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0ba4dc93198a7b3d288f187e58df3e05e6a68d9f2dd11bbd64976fcf55f98ec +size 146297 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_selector.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_selector.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..3263356e97516590e6e20b96c38760068b610c53 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/_selector.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a48e44ae39ecab47b737ce8b4cd95f76dfd597726074985cbf32d3b827a5d05e +size 377161 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/defs.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/defs.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..033c65ac2f5325db69db3220066e390febaa8422 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/defs.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5122310da9983f7e6b65cd09890d8de69a77513088077032314ba11d075b7ed7 +size 635329 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..440cbece079bc2fb5f37f332e3d3a177a9c57415 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f3f12c6a27fce8790f7599a116b7375efaefda66899cca27c559c6b23406ee46 +size 265817 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5a.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5a.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e69b511869051fad4b5d737ada4c52b154762d53 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5a.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c10c7d44a8ab85da1fe2e72fc1c5927d9a3ebfd61206dbd695ec7435f9c0981d +size 331289 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5ac.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5ac.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..1d1ce6589aca777fa90ff59038c259810333a6df --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5ac.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0fc3edc112c31ee1c5c5d7db922beebc97b0d01c4072e32910bed5bd8a532471 +size 216217 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5d.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5d.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..de55c61d5077099686ca66be44d97304d43c0ea1 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5d.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:220164ecbf8a72a617459a1910d1371e0028d13b06f785192cb5165796779a5d +size 627081 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5ds.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5ds.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..df141d2666fd2e673b4ce24a6be46168d066952c --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5ds.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9131f3247d66972bfdfa54f1f0512cf864d56b1be6448b9f375e8a434f0e1dd5 +size 228801 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5f.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5f.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..1695b500a5f92ec8acc43ad0ea171ded8bb14b71 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5f.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c02560c3b15f61a9df756efbbf41ea57b58e67c2f4cd90373714d8f5ac2ec3c +size 380633 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5fd.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5fd.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..257018de24e9735134db4c626caeed13df502b45 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5fd.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:274dcdd9b3f0739a448c6be97979e7f5694633974369c14ba68ad0630f9382b8 +size 389409 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5g.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5g.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..40871ec2c891c265e273d4dfe60c7810b696b651 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5g.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a8b3d7c13725b2edf7730067ee38294a6ed33c467dd67df05b36cecb6a71f27d +size 409601 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5i.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5i.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f931afd0fbcb23261d1da7e9943613855908d453 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5i.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:274ba314e2d3d4aae933ad2d9e598550ccb966c12d4ea0fb09eb33168b524238 +size 175281 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5l.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5l.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..337ff43a5c70c3b789fc0e2836aa4614ebf0132e --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5l.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:beaf4437c7d6b6f411b6eae772bc0af7e49438e3b6745303e77f8908f0bd4e3e +size 290289 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5o.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5o.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..27df017082688c7f57fe36e8cd4d0e45780ac8a0 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5o.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be7e5d81f11f1e39f3a390374b2cb9fd27f8a261d137a7f70e0b39874b5c299d +size 363993 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5p.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5p.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..1758d9676a1b31039bc29ea6d85f0bf359b794ad --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5p.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:becfb4ac79746524b6c38c6dd17b5e5316019bd52399fafcba41028d83fec190 +size 962817 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5pl.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5pl.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d2408d21b0c95cbf483bdd4b2dde8059be7e35b8 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5pl.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3964c86c2221fbee072ef5a8110d282eb2166daa62a1625fb8fd5411959041da +size 162849 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5py_warnings.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5py_warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..c30c56f7ff77c8703667d27dc550193a6f52e9ed --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5py_warnings.py @@ -0,0 +1,21 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + This module contains the warning classes for h5py. These classes are part of + the public API of h5py, and should be imported from this module. +""" + + +class H5pyWarning(UserWarning): + pass + + +class H5pyDeprecationWarning(H5pyWarning): + pass diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5r.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5r.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7b2bd293f30fabf8711ec866a2584bb86b9c6d75 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5r.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:86d0112d7672181ee2775f544acff4906a1812f738ae1b7cdacd2ea58c7a949a +size 200049 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5s.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5s.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..5ac60c1f5d923ba725dd78f7757a25925949d661 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5s.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a37b474d5e70320072864be7d16affbf907cf0933516d5405122a872cd87387e +size 327097 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5t.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5t.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..8f197ceab95e38ced7448132573f0c12bb08917f --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5t.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0bb8f6256a922dbd1c1d23b4d6717c06eb690bc2c6314c06d9c5a8411acc9e19 +size 923009 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5z.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5z.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..4e0b12bc0feb78504826ac71398722d08c22c0dc --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/h5z.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:481feeb9c85decb2786c9b429be9db525414f27c18d59665db335b1b7d432e46 +size 167017 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/ipy_completer.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/ipy_completer.py new file mode 100644 index 0000000000000000000000000000000000000000..aa68f3ea612894ae9d135b76948b116061ef6cd7 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/ipy_completer.py @@ -0,0 +1,156 @@ +#+ +# +# This file is part of h5py, a low-level Python interface to the HDF5 library. +# +# Contributed by Darren Dale +# +# Copyright (C) 2009 Darren Dale +# +# http://h5py.org +# License: BSD (See LICENSE.txt for full license) +# +#- + +# pylint: disable=eval-used,protected-access + +""" + This is the h5py completer extension for ipython. It is loaded by + calling the function h5py.enable_ipython_completer() from within an + interactive IPython session. + + It will let you do things like:: + + f=File('foo.h5') + f[' + # or: + f['ite + + which will do tab completion based on the subgroups of `f`. Also:: + + f['item1'].at + + will perform tab completion for the attributes in the usual way. This should + also work:: + + a = b = f['item1'].attrs. + + as should:: + + f['item1/item2/it +""" + +import posixpath +import re +from ._hl.attrs import AttributeManager +from ._hl.base import HLObject + + +from IPython import get_ipython + +from IPython.core.error import TryNext +from IPython.utils import generics + +re_attr_match = re.compile(r"(?:.*\=)?(.+\[.*\].*)\.(\w*)$") +re_item_match = re.compile(r"""(?:.*\=)?(.*)\[(?P['|"])(?!.*(?P=s))(.*)$""") +re_object_match = re.compile(r"(?:.*\=)?(.+?)(?:\[)") + + +def _retrieve_obj(name, context): + """ Filter function for completion. """ + + # we don't want to call any functions, but I couldn't find a robust regex + # that filtered them without unintended side effects. So keys containing + # "(" will not complete. + + if '(' in name: + raise ValueError() + + return eval(name, context.user_ns) + + +def h5py_item_completer(context, command): + """Compute possible item matches for dict-like objects""" + + base, item = re_item_match.split(command)[1:4:2] + + try: + obj = _retrieve_obj(base, context) + except Exception: + return [] + + path, _ = posixpath.split(item) + + try: + if path: + items = (posixpath.join(path, name) for name in obj[path].keys()) + else: + items = obj.keys() + except AttributeError: + return [] + + items = list(items) + + return [i for i in items if i[:len(item)] == item] + + +def h5py_attr_completer(context, command): + """Compute possible attr matches for nested dict-like objects""" + + base, attr = re_attr_match.split(command)[1:3] + base = base.strip() + + try: + obj = _retrieve_obj(base, context) + except Exception: + return [] + + attrs = dir(obj) + try: + attrs = generics.complete_object(obj, attrs) + except TryNext: + pass + + try: + # support >=ipython-0.12 + omit__names = get_ipython().Completer.omit__names + except AttributeError: + omit__names = 0 + + if omit__names == 1: + attrs = [a for a in attrs if not a.startswith('__')] + elif omit__names == 2: + attrs = [a for a in attrs if not a.startswith('_')] + + return ["%s.%s" % (base, a) for a in attrs if a[:len(attr)] == attr] + + +def h5py_completer(self, event): + """ Completer function to be loaded into IPython """ + base = re_object_match.split(event.line)[1] + + try: + obj = self._ofind(base).obj + except AttributeError: + obj = self._ofind(base).get('obj') + + if not isinstance(obj, (AttributeManager, HLObject)): + raise TryNext + + try: + return h5py_attr_completer(self, event.line) + except ValueError: + pass + + try: + return h5py_item_completer(self, event.line) + except ValueError: + pass + + return [] + + +def load_ipython_extension(ip=None): + """ Load completer function into IPython """ + if ip is None: + ip = get_ipython() + ip.set_hook('complete_command', h5py_completer, re_key=r"(?:.*\=)?(.+?)\[") diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2d07acacf489ae1dd86c6b68d19c9cf4f5aa967a --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/__init__.py @@ -0,0 +1,21 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. +import sys +import shlex +from importlib.util import find_spec +from subprocess import call + +def run_tests(args=''): + if find_spec("pytest") is None: + print("Tests require pytest, pytest not installed") + return 1 + + cli = [sys.executable, "-m", "pytest", "--pyargs", "h5py"] + cli.extend(shlex.split(args)) + return call(cli) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/common.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/common.py new file mode 100644 index 0000000000000000000000000000000000000000..fa8648654781a560c218baec45a7768f4658bac3 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/common.py @@ -0,0 +1,238 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +import sys +import os +import shutil +import inspect +import tempfile +import subprocess +from contextlib import contextmanager +from functools import wraps + +import numpy as np +from numpy.lib.recfunctions import repack_fields +import h5py + +import unittest as ut + + +# Check if non-ascii filenames are supported +# Evidently this is the most reliable way to check +# See also h5py issue #263 and ipython #466 +# To test for this, run the testsuite with LC_ALL=C +try: + testfile, fname = tempfile.mkstemp(chr(0x03b7)) +except UnicodeError: + UNICODE_FILENAMES = False +else: + UNICODE_FILENAMES = True + os.close(testfile) + os.unlink(fname) + del fname + del testfile + + +class TestCase(ut.TestCase): + + """ + Base class for unit tests. + """ + + @classmethod + def setUpClass(cls): + cls.tempdir = tempfile.mkdtemp(prefix='h5py-test_') + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tempdir) + + def mktemp(self, suffix='.hdf5', prefix='', dir=None): + if dir is None: + dir = self.tempdir + return tempfile.mktemp(suffix, prefix, dir=dir) + + def mktemp_mpi(self, comm=None, suffix='.hdf5', prefix='', dir=None): + if comm is None: + from mpi4py import MPI + comm = MPI.COMM_WORLD + fname = None + if comm.Get_rank() == 0: + fname = self.mktemp(suffix, prefix, dir) + fname = comm.bcast(fname, 0) + return fname + + def setUp(self): + self.f = h5py.File(self.mktemp(), 'w') + + def tearDown(self): + try: + if self.f: + self.f.close() + except: + pass + + def assertSameElements(self, a, b): + for x in a: + match = False + for y in b: + if x == y: + match = True + if not match: + raise AssertionError("Item '%s' appears in a but not b" % x) + + for x in b: + match = False + for y in a: + if x == y: + match = True + if not match: + raise AssertionError("Item '%s' appears in b but not a" % x) + + def assertArrayEqual(self, dset, arr, message=None, precision=None, check_alignment=True): + """ Make sure dset and arr have the same shape, dtype and contents, to + within the given precision, optionally ignoring differences in dtype alignment. + + Note that dset may be a NumPy array or an HDF5 dataset. + """ + if precision is None: + precision = 1e-5 + if message is None: + message = '' + else: + message = ' (%s)' % message + + if np.isscalar(dset) or np.isscalar(arr): + assert np.isscalar(dset) and np.isscalar(arr), \ + 'Scalar/array mismatch ("%r" vs "%r")%s' % (dset, arr, message) + dset = np.asarray(dset) + arr = np.asarray(arr) + + assert dset.shape == arr.shape, \ + "Shape mismatch (%s vs %s)%s" % (dset.shape, arr.shape, message) + if dset.dtype != arr.dtype: + if check_alignment: + normalized_dset_dtype = dset.dtype + normalized_arr_dtype = arr.dtype + else: + normalized_dset_dtype = repack_fields(dset.dtype) + normalized_arr_dtype = repack_fields(arr.dtype) + + assert normalized_dset_dtype == normalized_arr_dtype, \ + "Dtype mismatch (%s vs %s)%s" % (normalized_dset_dtype, normalized_arr_dtype, message) + + if not check_alignment: + if normalized_dset_dtype != dset.dtype: + dset = repack_fields(np.asarray(dset)) + if normalized_arr_dtype != arr.dtype: + arr = repack_fields(np.asarray(arr)) + + if arr.dtype.names is not None: + for n in arr.dtype.names: + message = '[FIELD %s] %s' % (n, message) + self.assertArrayEqual(dset[n], arr[n], message=message, precision=precision, check_alignment=check_alignment) + elif arr.dtype.kind in ('i', 'f'): + assert np.all(np.abs(dset[...] - arr[...]) < precision), \ + "Arrays differ by more than %.3f%s" % (precision, message) + elif arr.dtype.kind == 'O': + for v1, v2 in zip(dset.flat, arr.flat, strict=True): + self.assertArrayEqual(v1, v2, message=message, precision=precision, check_alignment=check_alignment) + else: + assert np.all(dset[...] == arr[...]), \ + "Arrays are not equal (dtype %s) %s" % (arr.dtype.str, message) + + def assertNumpyBehavior(self, dset, arr, s, skip_fast_reader=False): + """ Apply slicing arguments "s" to both dset and arr. + + Succeeds if the results of the slicing are identical, or the + exception raised is of the same type for both. + + "arr" must be a Numpy array; "dset" may be a NumPy array or dataset. + """ + exc = None + try: + arr_result = arr[s] + except Exception as e: + exc = type(e) + + s_fast = s if isinstance(s, tuple) else (s,) + + if exc is None: + self.assertArrayEqual(dset[s], arr_result) + + if not skip_fast_reader: + self.assertArrayEqual( + dset._fast_reader.read(s_fast), + arr_result, + ) + else: + with self.assertRaises(exc): + dset[s] + + if not skip_fast_reader: + with self.assertRaises(exc): + dset._fast_reader.read(s_fast) + +NUMPY_RELEASE_VERSION = tuple([int(i) for i in np.__version__.split(".")[0:2]]) + +@contextmanager +def closed_tempfile(suffix='', text=None): + """ + Context manager which yields the path to a closed temporary file with the + suffix `suffix`. The file will be deleted on exiting the context. An + additional argument `text` can be provided to have the file contain `text`. + """ + with tempfile.NamedTemporaryFile( + 'w+t', suffix=suffix, delete=False + ) as test_file: + file_name = test_file.name + if text is not None: + test_file.write(text) + test_file.flush() + yield file_name + shutil.rmtree(file_name, ignore_errors=True) + + +def insubprocess(f): + """Runs a test in its own subprocess""" + @wraps(f) + def wrapper(request, *args, **kwargs): + curr_test = inspect.getsourcefile(f) + "::" + request.node.name + # get block around test name + insub = "IN_SUBPROCESS_" + curr_test + for c in "/\\,:.": + insub = insub.replace(c, "_") + defined = os.environ.get(insub, None) + # fork process + if defined: + return f(request, *args, **kwargs) + else: + os.environ[insub] = '1' + env = os.environ.copy() + env[insub] = '1' + env.update(getattr(f, 'subproc_env', {})) + + with closed_tempfile() as stdout: + with open(stdout, 'w+t') as fh: + rtn = subprocess.call([sys.executable, '-m', 'pytest', curr_test], + stdout=fh, stderr=fh, env=env) + with open(stdout, 'rt') as fh: + out = fh.read() + + assert rtn == 0, "\n" + out + return wrapper + + +def subproc_env(d): + """Set environment variables for the @insubprocess decorator""" + def decorator(f): + f.subproc_env = d + return f + + return decorator diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/conftest.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..7a24883e19635532a9ab6a78b1ca732e05d0366e --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/conftest.py @@ -0,0 +1,22 @@ +import h5py +import pytest + + +@pytest.fixture() +def writable_file(tmp_path): + with h5py.File(tmp_path / 'test.h5', 'w') as f: + yield f + + +def pytest_addoption(parser): + parser.addoption( + '--no-network', action='store_true', default=False, help='No network access' + ) + + +def pytest_collection_modifyitems(config, items): + if config.getoption('--no-network'): + nonet = pytest.mark.skip(reason='No Internet') + for item in items: + if 'network' in item.keywords: + item.add_marker(nonet) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/data_files/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/data_files/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0dce8d8acda31e72201857a438d7867b583274fe --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/data_files/__init__.py @@ -0,0 +1,7 @@ +from os.path import dirname, join + +def get_data_file_path(basename): + """ + Returns the path to the test data file given by `basename` + """ + return join(dirname(__file__), basename) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/data_files/vlen_string_dset.h5 b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/data_files/vlen_string_dset.h5 new file mode 100644 index 0000000000000000000000000000000000000000..dbf021d4c80f66b6343fead92e5d7a6ea8ab647e --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/data_files/vlen_string_dset.h5 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:900f8baf19d3d8c4d1193ac1ac6019ee7774005e85c030af44e6757b38d29793 +size 6304 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/data_files/vlen_string_dset_utc.h5 b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/data_files/vlen_string_dset_utc.h5 new file mode 100644 index 0000000000000000000000000000000000000000..ca72c33de37d93f49b7121526b855f52bd927c47 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/data_files/vlen_string_dset_utc.h5 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85b728382b833c1da61627b9a334e22822d5c1cb359fe3ba6f25262af4532f63 +size 169904 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/data_files/vlen_string_s390x.h5 b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/data_files/vlen_string_s390x.h5 new file mode 100644 index 0000000000000000000000000000000000000000..bca4b91ad9029e3d0f0118aff12c28094edc95af --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/data_files/vlen_string_s390x.h5 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea990c68e0371bafab4966f752fa1355b3b9f64360066f6d9daff8f1b7e74ca5 +size 9008 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_attribute_create.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_attribute_create.py new file mode 100644 index 0000000000000000000000000000000000000000..11e4c1ad979394c66d2d3256b442102b9dcae908 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_attribute_create.py @@ -0,0 +1,95 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Tests the h5py.AttributeManager.create() method. +""" + +import numpy as np +from .. import h5t, h5a + +from .common import TestCase + +class TestArray(TestCase): + + """ + Check that top-level array types can be created and read. + """ + + def test_int(self): + # See issue 498 + + dt = np.dtype('(3,)i') + data = np.arange(3, dtype='i') + + self.f.attrs.create('x', data=data, dtype=dt) + + aid = h5a.open(self.f.id, b'x') + + htype = aid.get_type() + self.assertEqual(htype.get_class(), h5t.ARRAY) + + out = self.f.attrs['x'] + + self.assertArrayEqual(out, data) + + def test_string_dtype(self): + # See issue 498 discussion + + self.f.attrs.create('x', data=42, dtype='i8') + + def test_str(self): + # See issue 1057 + self.f.attrs.create('x', chr(0x03A9)) + out = self.f.attrs['x'] + self.assertEqual(out, chr(0x03A9)) + self.assertIsInstance(out, str) + + def test_tuple_of_unicode(self): + # Test that a tuple of unicode strings can be set as an attribute. It will + # be converted to a numpy array of vlen unicode type: + data = ('a', 'b') + self.f.attrs.create('x', data=data) + result = self.f.attrs['x'] + self.assertTrue(all(result == data)) + self.assertEqual(result.dtype, np.dtype('O')) + + # However, a numpy array of type U being passed in will not be + # automatically converted, and should raise an error as it does + # not map to a h5py dtype + data_as_U_array = np.array(data) + self.assertEqual(data_as_U_array.dtype, np.dtype('U1')) + with self.assertRaises(TypeError): + self.f.attrs.create('y', data=data_as_U_array) + + def test_shape(self): + self.f.attrs.create('x', data=42, shape=1) + result = self.f.attrs['x'] + self.assertEqual(result.shape, (1,)) + + self.f.attrs.create('y', data=np.arange(3), shape=3) + result = self.f.attrs['y'] + self.assertEqual(result.shape, (3,)) + + def test_dtype(self): + dt = np.dtype('(3,)i') + array = np.arange(3, dtype='i') + self.f.attrs.create('x', data=array, dtype=dt) + # Array dtype shape is incompatible with data shape + array = np.arange(4, dtype='i') + with self.assertRaises(ValueError): + self.f.attrs.create('x', data=array, dtype=dt) + # Shape of new attribute conflicts with shape of data + dt = np.dtype('()i') + with self.assertRaises(ValueError): + self.f.attrs.create('x', data=array, shape=(5,), dtype=dt) + + def test_key_type(self): + with self.assertRaises(TypeError): + self.f.attrs.create(1, data=('a', 'b')) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_attrs.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_attrs.py new file mode 100644 index 0000000000000000000000000000000000000000..5dbc4b19fc400cb5dd32288e3b687bebe2febbb3 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_attrs.py @@ -0,0 +1,299 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Attributes testing module + + Covers all operations which access the .attrs property, with the + exception of data read/write and type conversion. Those operations + are tested by module test_attrs_data. +""" + +import numpy as np + +from collections.abc import MutableMapping + +from .common import TestCase + +import h5py +from h5py import File +from h5py import h5a, h5t +from h5py import AttributeManager + + +class BaseAttrs(TestCase): + + def setUp(self): + self.f = File(self.mktemp(), 'w') + + def tearDown(self): + if self.f: + self.f.close() + +class TestRepr(TestCase): + + """ Feature: AttributeManager provide a helpful + __repr__ string + """ + + def test_repr(self): + grp = self.f.create_group('grp') + grp.attrs.create('att', 1) + self.assertIsInstance(repr(grp.attrs), str) + grp.id.close() + self.assertIsInstance(repr(grp.attrs), str) + + +class TestAccess(BaseAttrs): + + """ + Feature: Attribute creation/retrieval via special methods + """ + + def test_create(self): + """ Attribute creation by direct assignment """ + self.f.attrs['a'] = 4.0 + self.assertEqual(list(self.f.attrs.keys()), ['a']) + self.assertEqual(self.f.attrs['a'], 4.0) + + def test_create_2(self): + """ Attribute creation by create() method """ + self.f.attrs.create('a', 4.0) + self.assertEqual(list(self.f.attrs.keys()), ['a']) + self.assertEqual(self.f.attrs['a'], 4.0) + + def test_modify(self): + """ Attributes are modified by direct assignment""" + self.f.attrs['a'] = 3 + self.assertEqual(list(self.f.attrs.keys()), ['a']) + self.assertEqual(self.f.attrs['a'], 3) + self.f.attrs['a'] = 4 + self.assertEqual(list(self.f.attrs.keys()), ['a']) + self.assertEqual(self.f.attrs['a'], 4) + + def test_modify_2(self): + """ Attributes are modified by modify() method """ + self.f.attrs.modify('a',3) + self.assertEqual(list(self.f.attrs.keys()), ['a']) + self.assertEqual(self.f.attrs['a'], 3) + + self.f.attrs.modify('a', 4) + self.assertEqual(list(self.f.attrs.keys()), ['a']) + self.assertEqual(self.f.attrs['a'], 4) + + # If the attribute doesn't exist, create new + self.f.attrs.modify('b', 5) + self.assertEqual(list(self.f.attrs.keys()), ['a', 'b']) + self.assertEqual(self.f.attrs['a'], 4) + self.assertEqual(self.f.attrs['b'], 5) + + # Shape of new value is incompatible with the previous + new_value = np.arange(5) + with self.assertRaises(TypeError): + self.f.attrs.modify('b', new_value) + + def test_overwrite(self): + """ Attributes are silently overwritten """ + self.f.attrs['a'] = 4.0 + self.f.attrs['a'] = 5.0 + self.assertEqual(self.f.attrs['a'], 5.0) + + def test_rank(self): + """ Attribute rank is preserved """ + self.f.attrs['a'] = (4.0, 5.0) + self.assertEqual(self.f.attrs['a'].shape, (2,)) + self.assertArrayEqual(self.f.attrs['a'], np.array((4.0,5.0))) + + def test_single(self): + """ Attributes of shape (1,) don't become scalars """ + self.f.attrs['a'] = np.ones((1,)) + out = self.f.attrs['a'] + self.assertEqual(out.shape, (1,)) + self.assertEqual(out[()], 1) + + def test_access_exc(self): + """ Attempt to access missing item raises KeyError """ + with self.assertRaises(KeyError): + self.f.attrs['a'] + + def test_get_id(self): + self.f.attrs['a'] = 4.0 + aid = self.f.attrs.get_id('a') + assert isinstance(aid, h5a.AttrID) + + with self.assertRaises(KeyError): + self.f.attrs.get_id('b') + +class TestDelete(BaseAttrs): + + """ + Feature: Deletion of attributes using __delitem__ + """ + + def test_delete(self): + """ Deletion via "del" """ + self.f.attrs['a'] = 4.0 + self.assertIn('a', self.f.attrs) + del self.f.attrs['a'] + self.assertNotIn('a', self.f.attrs) + + def test_delete_exc(self): + """ Attempt to delete missing item raises KeyError """ + with self.assertRaises(KeyError): + del self.f.attrs['a'] + + +class TestUnicode(BaseAttrs): + + """ + Feature: Attributes can be accessed via Unicode or byte strings + """ + + def test_ascii(self): + """ Access via pure-ASCII byte string """ + self.f.attrs[b"ascii"] = 42 + out = self.f.attrs[b"ascii"] + self.assertEqual(out, 42) + + def test_raw(self): + """ Access via non-ASCII byte string """ + name = b"non-ascii\xfe" + self.f.attrs[name] = 42 + out = self.f.attrs[name] + self.assertEqual(out, 42) + + def test_unicode(self): + """ Access via Unicode string with non-ascii characters """ + name = "Omega" + chr(0x03A9) + self.f.attrs[name] = 42 + out = self.f.attrs[name] + self.assertEqual(out, 42) + + +class TestCreate(BaseAttrs): + + """ + Options for explicit attribute creation + """ + + def test_named(self): + """ Attributes created from named types link to the source type object + """ + self.f['type'] = np.dtype('u8') + self.f.attrs.create('x', 42, dtype=self.f['type']) + self.assertEqual(self.f.attrs['x'], 42) + aid = h5a.open(self.f.id, b'x') + htype = aid.get_type() + htype2 = self.f['type'].id + self.assertEqual(htype, htype2) + self.assertTrue(htype.committed()) + + def test_empty(self): + # https://github.com/h5py/h5py/issues/1540 + """ Create attribute with h5py.Empty value + """ + self.f.attrs.create('empty', h5py.Empty('f')) + self.assertEqual(self.f.attrs['empty'], h5py.Empty('f')) + + self.f.attrs.create('empty', h5py.Empty(None)) + self.assertEqual(self.f.attrs['empty'], h5py.Empty(None)) + +class TestMutableMapping(BaseAttrs): + '''Tests if the registration of AttributeManager as a MutableMapping + behaves as expected + ''' + def test_resolution(self): + assert issubclass(AttributeManager, MutableMapping) + assert isinstance(self.f.attrs, MutableMapping) + + def test_validity(self): + ''' + Test that the required functions are implemented. + ''' + AttributeManager.__getitem__ + AttributeManager.__setitem__ + AttributeManager.__delitem__ + AttributeManager.__iter__ + AttributeManager.__len__ + +class TestVlen(BaseAttrs): + def test_vlen(self): + a = np.array([np.arange(3), np.arange(4)], + dtype=h5t.vlen_dtype(int)) + self.f.attrs['a'] = a + self.assertArrayEqual(self.f.attrs['a'][0], a[0]) + + def test_vlen_s1(self): + dt = h5py.vlen_dtype(np.dtype('S1')) + a = np.empty((1,), dtype=dt) + a[0] = np.array([b'a', b'b'], dtype='S1') + + self.f.attrs.create('test', a) + self.assertArrayEqual(self.f.attrs['test'][0], a[0]) + + +class TestTrackOrder(BaseAttrs): + def fill_attrs(self, track_order): + attrs = self.f.create_group('test', track_order=track_order).attrs + for i in range(100): + attrs[str(i)] = i + return attrs + + # https://forum.hdfgroup.org/t/bug-h5arename-fails-unexpectedly/4881 + def test_track_order(self): + attrs = self.fill_attrs(track_order=True) # creation order + self.assertEqual(list(attrs), + [str(i) for i in range(100)]) + + def test_no_track_order(self): + attrs = self.fill_attrs(track_order=False) # name alphanumeric + self.assertEqual(list(attrs), + sorted([str(i) for i in range(100)])) + + def fill_attrs2(self, track_order): + group = self.f.create_group('test', track_order=track_order) + for i in range(12): + group.attrs[str(i)] = i + return group + + def test_track_order_overwrite_delete(self): + # issue 1385 + group = self.fill_attrs2(track_order=True) # creation order + self.assertEqual(group.attrs["11"], 11) + # overwrite attribute + group.attrs['11'] = 42.0 + self.assertEqual(group.attrs["11"], 42.0) + # delete attribute + self.assertIn('10', group.attrs) + del group.attrs['10'] + self.assertNotIn('10', group.attrs) + + +class TestDatatype(BaseAttrs): + + def test_datatype(self): + self.f['foo'] = np.dtype('f') + dt = self.f['foo'] + self.assertEqual(list(dt.attrs.keys()), []) + dt.attrs.create('a', 4.0) + self.assertEqual(list(dt.attrs.keys()), ['a']) + self.assertEqual(list(dt.attrs.values()), [4.0]) + +def test_python_int_uint64(writable_file): + f = writable_file + data = [np.iinfo(np.int64).max, np.iinfo(np.int64).max + 1] + + # Check creating a new attribute + f.attrs.create('a', data, dtype=np.uint64) + assert f.attrs['a'].dtype == np.dtype(np.uint64) + np.testing.assert_array_equal(f.attrs['a'], np.array(data, dtype=np.uint64)) + + # Check modifying an existing attribute + f.attrs.modify('a', data) + np.testing.assert_array_equal(f.attrs['a'], np.array(data, dtype=np.uint64)) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_attrs_data.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_attrs_data.py new file mode 100644 index 0000000000000000000000000000000000000000..26172b047bcae6dc4143e505dc344c35242977c4 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_attrs_data.py @@ -0,0 +1,311 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Attribute data transfer testing module + + Covers all data read/write and type-conversion operations for attributes. +""" + +import numpy as np + +from .common import TestCase + +import h5py +from h5py import h5a, h5s, h5t +from h5py import File +from h5py._hl.base import is_empty_dataspace + + +class BaseAttrs(TestCase): + + def setUp(self): + self.f = File(self.mktemp(), 'w') + + def tearDown(self): + if self.f: + self.f.close() + + +class TestScalar(BaseAttrs): + + """ + Feature: Scalar types map correctly to array scalars + """ + + def test_int(self): + """ Integers are read as correct NumPy type """ + self.f.attrs['x'] = np.array(1, dtype=np.int8) + out = self.f.attrs['x'] + self.assertIsInstance(out, np.int8) + + def test_compound(self): + """ Compound scalars are read as numpy.void """ + dt = np.dtype([('a', 'i'), ('b', 'f')]) + data = np.array((1, 4.2), dtype=dt) + self.f.attrs['x'] = data + out = self.f.attrs['x'] + self.assertIsInstance(out, np.void) + self.assertEqual(out, data) + self.assertEqual(out['b'], data['b']) + + def test_compound_with_vlen_fields(self): + """ Compound scalars with vlen fields can be written and read """ + dt = np.dtype([('a', h5py.vlen_dtype(np.int32)), + ('b', h5py.vlen_dtype(np.int32))]) + + data = np.array((np.array(list(range(1, 5)), dtype=np.int32), + np.array(list(range(8, 10)), dtype=np.int32)), dtype=dt)[()] + + self.f.attrs['x'] = data + out = self.f.attrs['x'] + + # Specifying check_alignment=False because vlen fields have 8 bytes of padding + # because the vlen datatype in hdf5 occupies 16 bytes + self.assertArrayEqual(out, data, check_alignment=False) + + def test_nesting_compound_with_vlen_fields(self): + """ Compound scalars with nested compound vlen fields can be written and read """ + dt_inner = np.dtype([('a', h5py.vlen_dtype(np.int32)), + ('b', h5py.vlen_dtype(np.int32))]) + + dt = np.dtype([('f1', h5py.vlen_dtype(dt_inner)), + ('f2', np.int64)]) + + inner1 = (np.array(range(1, 3), dtype=np.int32), + np.array(range(6, 9), dtype=np.int32)) + + inner2 = (np.array(range(10, 14), dtype=np.int32), + np.array(range(16, 20), dtype=np.int32)) + + data = np.array((np.array([inner1, inner2], dtype=dt_inner), + 2), + dtype=dt)[()] + + self.f.attrs['x'] = data + out = self.f.attrs['x'] + self.assertArrayEqual(out, data, check_alignment=False) + + def test_vlen_compound_with_vlen_string(self): + """ Compound scalars with vlen compounds containing vlen strings can be written and read """ + dt_inner = np.dtype([('a', h5py.string_dtype()), + ('b', h5py.string_dtype())]) + + dt = np.dtype([('f', h5py.vlen_dtype(dt_inner))]) + + data = np.array((np.array([(b"apples", b"bananas"), (b"peaches", b"oranges")], dtype=dt_inner),),dtype=dt)[()] + self.f.attrs['x'] = data + out = self.f.attrs['x'] + self.assertArrayEqual(out, data, check_alignment=False) + + +class TestArray(BaseAttrs): + + """ + Feature: Non-scalar types are correctly retrieved as ndarrays + """ + + def test_single(self): + """ Single-element arrays are correctly recovered """ + data = np.ndarray((1,), dtype='f') + self.f.attrs['x'] = data + out = self.f.attrs['x'] + self.assertIsInstance(out, np.ndarray) + self.assertEqual(out.shape, (1,)) + + def test_multi(self): + """ Rank-1 arrays are correctly recovered """ + data = np.ndarray((42,), dtype='f') + data[:] = 42.0 + data[10:35] = -47.0 + self.f.attrs['x'] = data + out = self.f.attrs['x'] + self.assertIsInstance(out, np.ndarray) + self.assertEqual(out.shape, (42,)) + self.assertArrayEqual(out, data) + + +class TestTypes(BaseAttrs): + + """ + Feature: All supported types can be stored in attributes + """ + + def test_int(self): + """ Storage of integer types """ + dtypes = (np.int8, np.int16, np.int32, np.int64, + np.uint8, np.uint16, np.uint32, np.uint64) + for dt in dtypes: + data = np.ndarray((1,), dtype=dt) + data[...] = 42 + self.f.attrs['x'] = data + out = self.f.attrs['x'] + self.assertEqual(out.dtype, dt) + self.assertArrayEqual(out, data) + + def test_float(self): + """ Storage of floating point types """ + dtypes = tuple(np.dtype(x) for x in ('f4', '>f8', 'c8', 'c16')) + + for dt in dtypes: + data = np.ndarray((1,), dtype=dt) + data[...] = -4.2j + 35.9 + self.f.attrs['x'] = data + out = self.f.attrs['x'] + self.assertEqual(out.dtype, dt) + self.assertArrayEqual(out, data) + + def test_string(self): + """ Storage of fixed-length strings """ + dtypes = tuple(np.dtype(x) for x in ('|S1', '|S10')) + + for dt in dtypes: + data = np.ndarray((1,), dtype=dt) + data[...] = 'h' + self.f.attrs['x'] = data + out = self.f.attrs['x'] + self.assertEqual(out.dtype, dt) + self.assertEqual(out[0], data[0]) + + def test_bool(self): + """ Storage of NumPy booleans """ + + data = np.ndarray((2,), dtype=np.bool_) + data[...] = True, False + self.f.attrs['x'] = data + out = self.f.attrs['x'] + self.assertEqual(out.dtype, data.dtype) + self.assertEqual(out[0], data[0]) + self.assertEqual(out[1], data[1]) + + def test_vlen_string_array(self): + """ Storage of vlen byte string arrays""" + dt = h5py.string_dtype(encoding='ascii') + + data = np.ndarray((2,), dtype=dt) + data[...] = "Hello", "Hi there! This is HDF5!" + + self.f.attrs['x'] = data + out = self.f.attrs['x'] + self.assertEqual(out.dtype, dt) + self.assertEqual(out[0], data[0]) + self.assertEqual(out[1], data[1]) + + def test_string_scalar(self): + """ Storage of variable-length byte string scalars (auto-creation) """ + + self.f.attrs['x'] = b'Hello' + out = self.f.attrs['x'] + + self.assertEqual(out, 'Hello') + self.assertEqual(type(out), str) + + aid = h5py.h5a.open(self.f.id, b"x") + tid = aid.get_type() + self.assertEqual(type(tid), h5py.h5t.TypeStringID) + self.assertEqual(tid.get_cset(), h5py.h5t.CSET_ASCII) + self.assertTrue(tid.is_variable_str()) + + def test_unicode_scalar(self): + """ Storage of variable-length unicode strings (auto-creation) """ + + self.f.attrs['x'] = u"Hello" + chr(0x2340) + u"!!" + out = self.f.attrs['x'] + self.assertEqual(out, u"Hello" + chr(0x2340) + u"!!") + self.assertEqual(type(out), str) + + aid = h5py.h5a.open(self.f.id, b"x") + tid = aid.get_type() + self.assertEqual(type(tid), h5py.h5t.TypeStringID) + self.assertEqual(tid.get_cset(), h5py.h5t.CSET_UTF8) + self.assertTrue(tid.is_variable_str()) + + +class TestEmpty(BaseAttrs): + + def setUp(self): + BaseAttrs.setUp(self) + sid = h5s.create(h5s.NULL) + tid = h5t.C_S1.copy() + tid.set_size(10) + aid = h5a.create(self.f.id, b'x', tid, sid) + self.empty_obj = h5py.Empty(np.dtype("S10")) + + def test_read(self): + self.assertEqual( + self.empty_obj, self.f.attrs['x'] + ) + + def test_write(self): + self.f.attrs["y"] = self.empty_obj + self.assertTrue(is_empty_dataspace(h5a.open(self.f.id, b'y'))) + + def test_modify(self): + with self.assertRaises(OSError): + self.f.attrs.modify('x', 1) + + def test_values(self): + # list() is for Py3 where these are iterators + values = list(self.f.attrs.values()) + self.assertEqual( + [self.empty_obj], values + ) + + def test_items(self): + items = list(self.f.attrs.items()) + self.assertEqual( + [(u"x", self.empty_obj)], items + ) + + def test_itervalues(self): + values = list(self.f.attrs.values()) + self.assertEqual( + [self.empty_obj], values + ) + + def test_iteritems(self): + items = list(self.f.attrs.items()) + self.assertEqual( + [(u"x", self.empty_obj)], items + ) + + +class TestWriteException(BaseAttrs): + + """ + Ensure failed attribute writes don't leave garbage behind. + """ + + def test_write(self): + """ ValueError on string write wipes out attribute """ + + s = b"Hello\x00Hello" + + try: + self.f.attrs['x'] = s + except ValueError: + pass + + with self.assertRaises(KeyError): + self.f.attrs['x'] diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_base.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..31b324a23e76314af82560a7aa8a31138bac70c4 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_base.py @@ -0,0 +1,146 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Common high-level operations test + + Tests features common to all high-level objects, like the .name property. +""" + +from h5py import File +from h5py._hl.base import is_hdf5, Empty +from .common import ut, TestCase, UNICODE_FILENAMES + +import numpy as np +import os +import tempfile + +class BaseTest(TestCase): + + def setUp(self): + self.f = File(self.mktemp(), 'w') + + def tearDown(self): + if self.f: + self.f.close() + + +class TestName(BaseTest): + + """ + Feature: .name attribute returns the object name + """ + + def test_anonymous(self): + """ Anonymous objects have name None """ + grp = self.f.create_group(None) + self.assertIs(grp.name, None) + +class TestParent(BaseTest): + + """ + test the parent group of the high-level interface objects + """ + + def test_object_parent(self): + # Anonymous objects + grp = self.f.create_group(None) + # Parent of an anonymous object is undefined + with self.assertRaises(ValueError): + grp.parent + + # Named objects + grp = self.f.create_group("bar") + sub_grp = grp.create_group("foo") + parent = sub_grp.parent.name + self.assertEqual(parent, "/bar") + +class TestMapping(BaseTest): + + """ + Test if the registration of Group as a + Mapping behaves as expected + """ + + def setUp(self): + super().setUp() + data = ('a', 'b') + self.grp = self.f.create_group('bar') + self.attr = self.f.attrs.create('x', data) + + def test_keys(self): + key_1 = self.f.keys() + self.assertIsInstance(repr(key_1), str) + key_2 = self.grp.keys() + self.assertIsInstance(repr(key_2), str) + + def test_values(self): + value_1 = self.f.values() + self.assertIsInstance(repr(value_1), str) + value_2 = self.grp.values() + self.assertIsInstance(repr(value_2), str) + + def test_items(self): + item_1 = self.f.items() + self.assertIsInstance(repr(item_1), str) + item_2 = self.grp.items() + self.assertIsInstance(repr(item_1), str) + + +class TestRepr(BaseTest): + + """ + repr() works correctly with Unicode names + """ + + USTRING = chr(0xfc) + chr(0xdf) + + def _check_type(self, obj): + self.assertIsInstance(repr(obj), str) + + def test_group(self): + """ Group repr() with unicode """ + grp = self.f.create_group(self.USTRING) + self._check_type(grp) + + def test_dataset(self): + """ Dataset repr() with unicode """ + dset = self.f.create_dataset(self.USTRING, (1,)) + self._check_type(dset) + + def test_namedtype(self): + """ Named type repr() with unicode """ + self.f['type'] = np.dtype('f') + typ = self.f['type'] + self._check_type(typ) + + def test_empty(self): + data = Empty(dtype='f') + self.assertNotEqual(Empty(dtype='i'), data) + self._check_type(data) + + @ut.skipIf(not UNICODE_FILENAMES, "Filesystem unicode support required") + def test_file(self): + """ File object repr() with unicode """ + fname = tempfile.mktemp(self.USTRING+'.hdf5') + try: + with File(fname,'w') as f: + self._check_type(f) + finally: + try: + os.unlink(fname) + except Exception: + pass + +def test_is_hdf5(): + filename = File(tempfile.mktemp(), "w").filename + assert is_hdf5(filename) + # non-existing HDF5 file + filename = tempfile.mktemp() + assert not is_hdf5(filename) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_big_endian_file.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_big_endian_file.py new file mode 100644 index 0000000000000000000000000000000000000000..26d2bfe86cba70c7fd2d30cc69ec4fddac7cb426 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_big_endian_file.py @@ -0,0 +1,49 @@ + +import numpy as np +from h5py import File +from .common import TestCase +from .data_files import get_data_file_path + + +def test_vlen_big_endian(): + with File(get_data_file_path("vlen_string_s390x.h5")) as f: + assert f.attrs["created_on_s390x"] == 1 + + dset = f["DSvariable"] + assert dset[0] == b"Parting" + assert dset[1] == b"is such" + assert dset[2] == b"sweet" + assert dset[3] == b"sorrow..." + + dset = f["DSLEfloat"] + assert dset[0] == 3.14 + assert dset[1] == 1.61 + assert dset[2] == 2.71 + assert dset[3] == 2.41 + assert dset[4] == 1.2 + assert dset.dtype == "f8" + + assert f["DSLEint"][0] == 1 + assert f["DSLEint"].dtype == "i8" + + +class TestEndianess(TestCase): + def test_simple_int_be(self): + fname = self.mktemp() + + arr = np.ndarray(shape=(1,), dtype=">i4", buffer=bytearray([0, 1, 3, 2])) + be_number = 0 * 256 ** 3 + 1 * 256 ** 2 + 3 * 256 ** 1 + 2 * 256 ** 0 + + with File(fname, mode="w") as f: + f.create_dataset("int", data=arr) + + with File(fname, mode="r") as f: + assert f["int"][()][0] == be_number diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_completions.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_completions.py new file mode 100644 index 0000000000000000000000000000000000000000..6c0e43541f1081b79eb30040c5cc1fcccbd097e2 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_completions.py @@ -0,0 +1,52 @@ +from .common import TestCase + + +class TestCompletions(TestCase): + + def test_group_completions(self): + # Test completions on top-level file. + g = self.f.create_group('g') + self.f.create_group('h') + self.f.create_dataset('data', [1, 2, 3]) + self.assertEqual( + self.f._ipython_key_completions_(), + ['data', 'g', 'h'], + ) + + self.f.create_group('data2', [1, 2, 3]) + self.assertEqual( + self.f._ipython_key_completions_(), + ['data', 'data2', 'g', 'h'], + ) + + # Test on subgroup. + g.create_dataset('g_data1', [1, 2, 3]) + g.create_dataset('g_data2', [4, 5, 6]) + self.assertEqual( + g._ipython_key_completions_(), + ['g_data1', 'g_data2'], + ) + + g.create_dataset('g_data3', [7, 8, 9]) + self.assertEqual( + g._ipython_key_completions_(), + ['g_data1', 'g_data2', 'g_data3'], + ) + + def test_attrs_completions(self): + attrs = self.f.attrs + + # Write out of alphabetical order to test that completions come back in + # alphabetical order, as opposed to, say, insertion order. + attrs['b'] = 1 + attrs['a'] = 2 + self.assertEqual( + attrs._ipython_key_completions_(), + ['a', 'b'] + ) + + attrs['c'] = 3 + self.assertEqual( + attrs._ipython_key_completions_(), + ['a', 'b', 'c'] + ) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dataset.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..1205d4dbff160c500b67f283d36e8a06ed6cf455 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dataset.py @@ -0,0 +1,2242 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Dataset testing operations. + + Tests all dataset operations, including creation, with the exception of: + + 1. Slicing operations for read and write, handled by module test_slicing + 2. Type conversion for read and write (currently untested) +""" + +import pathlib +import os +import sys +import numpy as np +import platform +import pytest +import threading +from concurrent.futures import ThreadPoolExecutor + +from .common import ut, TestCase +from .data_files import get_data_file_path +from h5py import File, Dataset +from h5py._hl.base import is_empty_dataspace, product +from h5py import h5f, h5t +import h5py +from h5py.tests.common import NUMPY_RELEASE_VERSION + +class BaseDataset(TestCase): + def setUp(self): + self.f = File(self.mktemp(), 'w') + + def tearDown(self): + if self.f: + self.f.close() + + +class TestRepr(BaseDataset): + """ + Feature: repr(Dataset) behaves sensibly + """ + endian_mark = '>' if sys.byteorder=='big' else '<' + + def test_repr_basic(self): + ds = self.f.create_dataset('foo', (4,), dtype='int32') + assert repr(ds) == f'' + + def test_repr_closed(self): + """ repr() works on live and dead datasets """ + ds = self.f.create_dataset('foo', (4,)) + self.f.close() + assert repr(ds) == '' + + def test_repr_anonymous(self): + ds = self.f.create_dataset(None, (4,), dtype='int32') + assert repr(ds) == f'' + + +class TestCreateShape(BaseDataset): + + """ + Feature: Datasets can be created from a shape only + """ + + def test_create_scalar(self): + """ Create a scalar dataset """ + dset = self.f.create_dataset('foo', ()) + self.assertEqual(dset.shape, ()) + + def test_create_simple(self): + """ Create a size-1 dataset """ + dset = self.f.create_dataset('foo', (1,)) + self.assertEqual(dset.shape, (1,)) + + def test_create_integer(self): + """ Create a size-1 dataset with integer shape""" + dset = self.f.create_dataset('foo', 1) + self.assertEqual(dset.shape, (1,)) + + def test_create_extended(self): + """ Create an extended dataset """ + dset = self.f.create_dataset('foo', (63,)) + self.assertEqual(dset.shape, (63,)) + self.assertEqual(dset.size, 63) + dset = self.f.create_dataset('bar', (6, 10)) + self.assertEqual(dset.shape, (6, 10)) + self.assertEqual(dset.size, (60)) + + def test_create_integer_extended(self): + """ Create an extended dataset """ + dset = self.f.create_dataset('foo', 63) + self.assertEqual(dset.shape, (63,)) + self.assertEqual(dset.size, 63) + dset = self.f.create_dataset('bar', (6, 10)) + self.assertEqual(dset.shape, (6, 10)) + self.assertEqual(dset.size, (60)) + + def test_default_dtype(self): + """ Confirm that the default dtype is float """ + dset = self.f.create_dataset('foo', (63,)) + self.assertEqual(dset.dtype, np.dtype('=f4')) + + def test_missing_shape(self): + """ Missing shape raises TypeError """ + with self.assertRaises(TypeError): + self.f.create_dataset('foo') + + def test_long_double(self): + """ Confirm that the default dtype is float """ + dset = self.f.create_dataset('foo', (63,), dtype=np.longdouble) + if platform.machine() in ['ppc64le']: + pytest.xfail("Storage of long double deactivated on %s" % platform.machine()) + self.assertEqual(dset.dtype, np.longdouble) + + @ut.skipIf(not hasattr(np, "complex256"), "No support for complex256") + def test_complex256(self): + """ Confirm that the default dtype is float """ + dset = self.f.create_dataset('foo', (63,), + dtype=np.dtype('complex256')) + self.assertEqual(dset.dtype, np.dtype('complex256')) + + def test_name_bytes(self): + dset = self.f.create_dataset(b'foo', (1,)) + self.assertEqual(dset.shape, (1,)) + + dset2 = self.f.create_dataset(b'bar/baz', (2,)) + self.assertEqual(dset2.shape, (2,)) + +class TestCreateData(BaseDataset): + + """ + Feature: Datasets can be created from existing data + """ + + def test_create_scalar(self): + """ Create a scalar dataset from existing array """ + data = np.ones((), 'f') + dset = self.f.create_dataset('foo', data=data) + self.assertEqual(dset.shape, data.shape) + + def test_create_extended(self): + """ Create an extended dataset from existing data """ + data = np.ones((63,), 'f') + dset = self.f.create_dataset('foo', data=data) + self.assertEqual(dset.shape, data.shape) + + def test_dataset_intermediate_group(self): + """ Create dataset with missing intermediate groups """ + ds = self.f.create_dataset("/foo/bar/baz", shape=(10, 10), dtype=' 0 + + si = ds.get_chunk_info_by_coord((0, 0)) + assert si.chunk_offset == (0, 0) + assert si.filter_mask == 0 + assert si.byte_offset is not None + assert si.size > 0 + + +@ut.skipUnless(h5py.version.hdf5_version_tuple >= (1, 12, 3) or + (h5py.version.hdf5_version_tuple >= (1, 10, 10) and h5py.version.hdf5_version_tuple < (1, 10, 99)), + "chunk iteration requires HDF5 1.10.10 and later 1.10, or 1.12.3 and later") +def test_chunk_iter(): + """H5Dchunk_iter() for chunk information""" + from io import BytesIO + buf = BytesIO() + with h5py.File(buf, 'w') as f: + f.create_dataset('test', shape=(100, 100), chunks=(10, 10), dtype='i4') + f['test'][:] = 1 + + buf.seek(0) + with h5py.File(buf, 'r') as f: + dsid = f['test'].id + + num_chunks = dsid.get_num_chunks() + assert num_chunks == 100 + ci = {} + for j in range(num_chunks): + si = dsid.get_chunk_info(j) + ci[si.chunk_offset] = si + + def callback(chunk_info): + known = ci[chunk_info.chunk_offset] + assert chunk_info.chunk_offset == known.chunk_offset + assert chunk_info.filter_mask == known.filter_mask + assert chunk_info.byte_offset == known.byte_offset + assert chunk_info.size == known.size + + dsid.chunk_iter(callback) + + +def test_empty_shape(writable_file): + ds = writable_file.create_dataset('empty', dtype='int32') + assert ds.shape is None + assert ds.maxshape is None + + +def test_zero_storage_size(): + # https://github.com/h5py/h5py/issues/1475 + from io import BytesIO + buf = BytesIO() + with h5py.File(buf, 'w') as fout: + fout.create_dataset('empty', dtype='uint8') + + buf.seek(0) + with h5py.File(buf, 'r') as fin: + assert fin['empty'].chunks is None + assert fin['empty'].id.get_offset() is None + assert fin['empty'].id.get_storage_size() == 0 + + +def test_python_int_uint64(writable_file): + # https://github.com/h5py/h5py/issues/1547 + data = [np.iinfo(np.int64).max, np.iinfo(np.int64).max + 1] + + # Check creating a new dataset + ds = writable_file.create_dataset('x', data=data, dtype=np.uint64) + assert ds.dtype == np.dtype(np.uint64) + np.testing.assert_array_equal(ds[:], np.array(data, dtype=np.uint64)) + + # Check writing to an existing dataset + ds[:] = data + np.testing.assert_array_equal(ds[:], np.array(data, dtype=np.uint64)) + + +def test_setitem_fancy_indexing(writable_file): + # https://github.com/h5py/h5py/issues/1593 + arr = writable_file.create_dataset('data', (5, 1000, 2), dtype=np.uint8) + block = np.random.randint(255, size=(5, 3, 2)) + arr[:, [0, 2, 4], ...] = block + + +def test_vlen_spacepad(): + with File(get_data_file_path("vlen_string_dset.h5")) as f: + assert f["DS1"][0] == b"Parting" + + +def test_vlen_nullterm(): + with File(get_data_file_path("vlen_string_dset_utc.h5")) as f: + assert f["ds1"][0] == b"2009-12-20T10:16:18.662409Z" + + +def test_allow_unknown_filter(writable_file): + # apparently 256-511 are reserved for testing purposes + fake_filter_id = 256 + ds = writable_file.create_dataset( + 'data', shape=(10, 10), dtype=np.uint8, compression=fake_filter_id, + allow_unknown_filter=True + ) + assert str(fake_filter_id) in ds._filters + + +def test_dset_chunk_cache(): + """Chunk cache configuration for individual datasets.""" + from io import BytesIO + buf = BytesIO() + with h5py.File(buf, 'w') as fout: + ds = fout.create_dataset( + 'x', shape=(10, 20), chunks=(5, 4), dtype='i4', + rdcc_nbytes=2 * 1024 * 1024, rdcc_w0=0.2, rdcc_nslots=997) + ds_chunk_cache = ds.id.get_access_plist().get_chunk_cache() + assert fout.id.get_access_plist().get_cache()[1:] != ds_chunk_cache + assert ds_chunk_cache == (997, 2 * 1024 * 1024, 0.2) + + buf.seek(0) + with h5py.File(buf, 'r') as fin: + ds = fin.require_dataset( + 'x', shape=(10, 20), dtype='i4', + rdcc_nbytes=3 * 1024 * 1024, rdcc_w0=0.67, rdcc_nslots=709) + ds_chunk_cache = ds.id.get_access_plist().get_chunk_cache() + assert fin.id.get_access_plist().get_cache()[1:] != ds_chunk_cache + assert ds_chunk_cache == (709, 3 * 1024 * 1024, 0.67) + + +class TestCommutative(BaseDataset): + """ + Test the symmetry of operators, at least with the numpy types. + Issue: https://github.com/h5py/h5py/issues/1947 + """ + def test_numpy_commutative(self,): + """ + Create a h5py dataset, extract one element convert to numpy + Check that it returns symmetric response to == and != + """ + shape = (100,1) + dset = self.f.create_dataset("test", shape, dtype=float, + data=np.random.rand(*shape)) + + # grab a value from the elements, ie dset[0, 0] + # check that mask arrays are commutative wrt ==, != + val = np.float64(dset[0, 0]) + + assert np.all((val == dset) == (dset == val)) + assert np.all((val != dset) == (dset != val)) + + # generate sample not in the dset, ie max(dset)+delta + # check that mask arrays are commutative wrt ==, != + delta = 0.001 + nval = np.nanmax(dset)+delta + + assert np.all((nval == dset) == (dset == nval)) + assert np.all((nval != dset) == (dset != nval)) + + def test_basetype_commutative(self,): + """ + Create a h5py dataset and check basetype compatibility. + Check that operation is symmetric, even if it is potentially + not meaningful. + """ + shape = (100,1) + dset = self.f.create_dataset("test", shape, dtype=float, + data=np.random.rand(*shape)) + + # generate float type, sample float(0.) + # check that operation is symmetric (but potentially meaningless) + val = float(0.) + assert (val == dset) == (dset == val) + assert (val != dset) == (dset != val) + +class TestVirtualPrefix(BaseDataset): + """ + Test setting virtual prefix + """ + def test_virtual_prefix_create(self): + shape = (100,1) + virtual_prefix = "/path/to/virtual" + dset = self.f.create_dataset("test", shape, dtype=float, + data=np.random.rand(*shape), + virtual_prefix = virtual_prefix) + + virtual_prefix_readback = pathlib.Path(dset.id.get_access_plist().get_virtual_prefix().decode()).as_posix() + assert virtual_prefix_readback == virtual_prefix + + def test_virtual_prefix_require(self): + virtual_prefix = "/path/to/virtual" + dset = self.f.require_dataset('foo', (10, 3), 'f', virtual_prefix = virtual_prefix) + virtual_prefix_readback = pathlib.Path(dset.id.get_access_plist().get_virtual_prefix().decode()).as_posix() + self.assertEqual(virtual_prefix, virtual_prefix_readback) + self.assertIsInstance(dset, Dataset) + self.assertEqual(dset.shape, (10, 3)) + + +def ds_str(file, shape=(10, )): + dt = h5py.string_dtype(encoding='ascii') + fill_value = b'fill' + return file.create_dataset('x', shape, dtype=dt, fillvalue=fill_value) + + +def ds_fields(file, shape=(10, )): + dt = np.dtype([ + ('foo', h5py.string_dtype(encoding='ascii')), + ('bar', np.float64), + ]) + fill_value = np.asarray(('fill', 0.0), dtype=dt) + file['x'] = np.broadcast_to(fill_value, shape) + return file['x'] + + +view_getters = pytest.mark.parametrize( + "view_getter,make_ds", + [ + (lambda ds: ds, ds_str), + (lambda ds: ds.astype(dtype=object), ds_str), + (lambda ds: ds.asstr(), ds_str), + (lambda ds: ds.fields("foo"), ds_fields), + ], + ids=["ds", "astype", "asstr", "fields"], +) + + +COPY_IF_NEEDED = False if NUMPY_RELEASE_VERSION < (2, 0) else None + +@pytest.mark.parametrize("copy", [True, COPY_IF_NEEDED]) +@view_getters +def test_array_copy(view_getter, make_ds, copy, writable_file): + ds = make_ds(writable_file) + view = view_getter(ds) + np.array(view, copy=copy) + + +@pytest.mark.skipif( + NUMPY_RELEASE_VERSION < (2, 0), + reason="forbidding copies requires numpy 2", +) +@view_getters +def test_array_copy_false(view_getter, make_ds, writable_file): + ds = make_ds(writable_file) + view = view_getter(ds) + with pytest.raises(ValueError, match="memory allocation cannot be avoided"): + np.array(view, copy=False) + + +@view_getters +def test_array_dtype(view_getter, make_ds, writable_file): + ds = make_ds(writable_file) + view = view_getter(ds) + assert np.array(view, dtype='|S10').dtype == np.dtype('|S10') + + +@view_getters +def test_array_scalar(view_getter, make_ds, writable_file): + ds = make_ds(writable_file, shape=()) + view = view_getter(ds) + assert isinstance(view[()], (bytes, str)) + assert np.array(view).shape == () + + +@view_getters +def test_array_nd(view_getter, make_ds, writable_file): + ds = make_ds(writable_file, shape=(5, 6)) + view = view_getter(ds) + assert np.array(view).shape == (5, 6) + + +@view_getters +def test_view_properties(view_getter, make_ds, writable_file): + ds = make_ds(writable_file, shape=(5, 6)) + view = view_getter(ds) + assert view.dtype == np.dtype(object) + assert view.ndim == 2 + assert view.shape == (5, 6) + assert view.size == 30 + assert len(view) == 5 + + +def test_concurrent_dataset_creation(writable_file): + N_THREADS = 25 + N_DATASETS_PER_THREAD = 5 + # Defines a thread barrier that will be spawned before parallel execution + # this increases the probability of concurrent access clashes. + barrier = threading.Barrier(N_THREADS) + + def closure(ithread): + # Ensure that all threads reach this point before concurrent execution. + barrier.wait() + for j in range(N_DATASETS_PER_THREAD): + writable_file.create_dataset(f'concurrent_{ithread:02d}_{j:02d}', (1000,), dtype='i4') + + with ThreadPoolExecutor(max_workers=N_THREADS) as executor: + futures = [executor.submit(closure, ithread) for ithread in range(N_THREADS)] + + [f.result() for f in futures] + expected = set(f'concurrent_{i:02d}_{j:02d}' for i in range(N_THREADS) for j in range(N_DATASETS_PER_THREAD)) + assert set(writable_file) == expected diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dataset_getitem.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dataset_getitem.py new file mode 100644 index 0000000000000000000000000000000000000000..65271e0ef138bf91a8dd1af33810e77677eda5ca --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dataset_getitem.py @@ -0,0 +1,618 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Tests the h5py.Dataset.__getitem__ method. + + This module does not specifically test type conversion. The "type" axis + therefore only tests objects which interact with the slicing system in + unreliable ways; for example, compound and array types. + + See test_dataset_getitem_types for type-conversion tests. + + Tests are organized into TestCases by dataset shape and type. Test + methods vary by slicing arg type. + + 1. Dataset shape: + Empty + Scalar + 1D + 3D + + 2. Type: + Float + Compound + Array + + 3. Slicing arg types: + Ellipsis + Empty tuple + Regular slice + MultiBlockSlice + Indexing + Index list + Boolean mask + Field names +""" + +import sys + +import numpy as np +import h5py + +from .common import ut, TestCase + + +class TestEmpty(TestCase): + + def setUp(self): + TestCase.setUp(self) + sid = h5py.h5s.create(h5py.h5s.NULL) + tid = h5py.h5t.C_S1.copy() + tid.set_size(10) + dsid = h5py.h5d.create(self.f.id, b'x', tid, sid) + self.dset = h5py.Dataset(dsid) + self.empty_obj = h5py.Empty(np.dtype("S10")) + + def test_ndim(self): + """ Verify number of dimensions """ + self.assertEqual(self.dset.ndim, 0) + + def test_shape(self): + """ Verify shape """ + self.assertEqual(self.dset.shape, None) + + def test_size(self): + """ Verify shape """ + self.assertEqual(self.dset.size, None) + + def test_nbytes(self): + """ Verify nbytes """ + self.assertEqual(self.dset.nbytes, 0) + + def test_ellipsis(self): + self.assertEqual(self.dset[...], self.empty_obj) + + def test_tuple(self): + self.assertEqual(self.dset[()], self.empty_obj) + + def test_slice(self): + """ slice -> ValueError """ + with self.assertRaises(ValueError): + self.dset[0:4] + + def test_multi_block_slice(self): + """ MultiBlockSlice -> ValueError """ + with self.assertRaises(ValueError): + self.dset[h5py.MultiBlockSlice()] + + def test_index(self): + """ index -> ValueError """ + with self.assertRaises(ValueError): + self.dset[0] + + def test_indexlist(self): + """ index list -> ValueError """ + with self.assertRaises(ValueError): + self.dset[[1,2,5]] + + def test_mask(self): + """ mask -> ValueError """ + mask = np.array(True, dtype='bool') + with self.assertRaises(ValueError): + self.dset[mask] + + def test_fieldnames(self): + """ field name -> ValueError """ + with self.assertRaises(ValueError): + self.dset['field'] + + +class TestScalarFloat(TestCase): + + def setUp(self): + TestCase.setUp(self) + self.data = np.array(42.5, dtype=np.double) + self.dset = self.f.create_dataset('x', data=self.data) + + def test_ndim(self): + """ Verify number of dimensions """ + self.assertEqual(self.dset.ndim, 0) + + def test_size(self): + """ Verify size """ + self.assertEqual(self.dset.size, 1) + + def test_nbytes(self): + """ Verify nbytes """ + self.assertEqual(self.dset.nbytes, self.data.dtype.itemsize) # not sure if 'f' is always alias for 'f4' + + def test_shape(self): + """ Verify shape """ + self.assertEqual(self.dset.shape, tuple()) + + def test_ellipsis(self): + """ Ellipsis -> scalar ndarray """ + out = self.dset[...] + self.assertArrayEqual(out, self.data) + + def test_tuple(self): + """ () -> bare item """ + out = self.dset[()] + self.assertArrayEqual(out, self.data.item()) + + def test_slice(self): + """ slice -> ValueError """ + with self.assertRaises(ValueError): + self.dset[0:4] + + def test_multi_block_slice(self): + """ MultiBlockSlice -> ValueError """ + with self.assertRaises(ValueError): + self.dset[h5py.MultiBlockSlice()] + + def test_index(self): + """ index -> ValueError """ + with self.assertRaises(ValueError): + self.dset[0] + + # FIXME: NumPy has IndexError instead + def test_indexlist(self): + """ index list -> ValueError """ + with self.assertRaises(ValueError): + self.dset[[1,2,5]] + + # FIXME: NumPy permits this + def test_mask(self): + """ mask -> ValueError """ + mask = np.array(True, dtype='bool') + with self.assertRaises(ValueError): + self.dset[mask] + + def test_fieldnames(self): + """ field name -> ValueError (no fields) """ + with self.assertRaises(ValueError): + self.dset['field'] + + +class TestScalarCompound(TestCase): + + def setUp(self): + TestCase.setUp(self) + self.data = np.array((42.5, -118, "Hello"), dtype=[('a', 'f'), ('b', 'i'), ('c', '|S10')]) + self.dset = self.f.create_dataset('x', data=self.data) + + def test_ndim(self): + """ Verify number of dimensions """ + self.assertEqual(self.dset.ndim, 0) + + def test_shape(self): + """ Verify shape """ + self.assertEqual(self.dset.shape, tuple()) + + def test_size(self): + """ Verify size """ + self.assertEqual(self.dset.size, 1) + + def test_nbytes(self): + """ Verify nbytes """ + self.assertEqual(self.dset.nbytes, self.data.dtype.itemsize) + + def test_ellipsis(self): + """ Ellipsis -> scalar ndarray """ + out = self.dset[...] + # assertArrayEqual doesn't work with compounds; do manually + self.assertIsInstance(out, np.ndarray) + self.assertEqual(out.shape, self.data.shape) + self.assertEqual(out.dtype, self.data.dtype) + + def test_tuple(self): + """ () -> np.void instance """ + out = self.dset[()] + self.assertIsInstance(out, np.void) + self.assertEqual(out.dtype, self.data.dtype) + + def test_slice(self): + """ slice -> ValueError """ + with self.assertRaises(ValueError): + self.dset[0:4] + + def test_multi_block_slice(self): + """ MultiBlockSlice -> ValueError """ + with self.assertRaises(ValueError): + self.dset[h5py.MultiBlockSlice()] + + def test_index(self): + """ index -> ValueError """ + with self.assertRaises(ValueError): + self.dset[0] + + # FIXME: NumPy has IndexError instead + def test_indexlist(self): + """ index list -> ValueError """ + with self.assertRaises(ValueError): + self.dset[[1,2,5]] + + # FIXME: NumPy permits this + def test_mask(self): + """ mask -> ValueError """ + mask = np.array(True, dtype='bool') + with self.assertRaises(ValueError): + self.dset[mask] + + # FIXME: NumPy returns a scalar ndarray + def test_fieldnames(self): + """ field name -> bare value """ + out = self.dset['a'] + self.assertIsInstance(out, np.float32) + self.assertEqual(out, self.dset['a']) + + +class TestScalarArray(TestCase): + + def setUp(self): + TestCase.setUp(self) + self.dt = np.dtype('(3,2)f') + self.data = np.array([(3.2, -119), (42, 99.8), (3.14, 0)], dtype='f') + self.dset = self.f.create_dataset('x', (), dtype=self.dt) + self.dset[...] = self.data + + def test_ndim(self): + """ Verify number of dimensions """ + self.assertEqual(self.data.ndim, 2) + self.assertEqual(self.dset.ndim, 0) + + def test_size(self): + """ Verify size """ + self.assertEqual(self.dset.size, 1) + + def test_nbytes(self): + """ Verify nbytes """ + self.assertEqual(self.dset.nbytes, self.dset.dtype.itemsize) # not sure if 'f' is always alias for 'f4' + + def test_shape(self): + """ Verify shape """ + self.assertEqual(self.data.shape, (3, 2)) + self.assertEqual(self.dset.shape, tuple()) + + def test_ellipsis(self): + """ Ellipsis -> ndarray promoted to underlying shape """ + out = self.dset[...] + self.assertArrayEqual(out, self.data) + + def test_tuple(self): + """ () -> same as ellipsis """ + out = self.dset[...] + self.assertArrayEqual(out, self.data) + + def test_slice(self): + """ slice -> ValueError """ + with self.assertRaises(ValueError): + self.dset[0:4] + + def test_multi_block_slice(self): + """ MultiBlockSlice -> ValueError """ + with self.assertRaises(ValueError): + self.dset[h5py.MultiBlockSlice()] + + def test_index(self): + """ index -> ValueError """ + with self.assertRaises(ValueError): + self.dset[0] + + def test_indexlist(self): + """ index list -> ValueError """ + with self.assertRaises(ValueError): + self.dset[[]] + + def test_mask(self): + """ mask -> ValueError """ + mask = np.array(True, dtype='bool') + with self.assertRaises(ValueError): + self.dset[mask] + + def test_fieldnames(self): + """ field name -> ValueError (no fields) """ + with self.assertRaises(ValueError): + self.dset['field'] + + +class Test1DZeroFloat(TestCase): + + def setUp(self): + TestCase.setUp(self) + self.data = np.ones((0,), dtype='f') + self.dset = self.f.create_dataset('x', data=self.data) + + def test_ndim(self): + """ Verify number of dimensions """ + self.assertEqual(self.dset.ndim, 1) + + def test_shape(self): + """ Verify shape """ + self.assertEqual(self.dset.shape, (0,)) + + def test_ellipsis(self): + """ Ellipsis -> ndarray of matching shape """ + self.assertNumpyBehavior(self.dset, self.data, np.s_[...]) + + def test_tuple(self): + """ () -> same as ellipsis """ + self.assertNumpyBehavior(self.dset, self.data, np.s_[()]) + + def test_slice(self): + """ slice -> ndarray of shape (0,) """ + self.assertNumpyBehavior(self.dset, self.data, np.s_[0:4]) + + def test_slice_stop_less_than_start(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[7:5]) + + def test_index(self): + """ index -> out of range """ + with self.assertRaises(IndexError): + self.dset[0] + + def test_indexlist(self): + """ index list """ + self.assertNumpyBehavior(self.dset, self.data, np.s_[[]]) + + def test_mask(self): + """ mask -> ndarray of matching shape """ + mask = np.ones((0,), dtype='bool') + self.assertNumpyBehavior( + self.dset, + self.data, + np.s_[mask], + # Fast reader doesn't work with boolean masks + skip_fast_reader=True, + ) + + def test_fieldnames(self): + """ field name -> ValueError (no fields) """ + with self.assertRaises(ValueError): + self.dset['field'] + + +class Test1DFloat(TestCase): + + def setUp(self): + TestCase.setUp(self) + self.data = np.arange(13).astype('f') + self.dset = self.f.create_dataset('x', data=self.data) + + def test_ndim(self): + """ Verify number of dimensions """ + self.assertEqual(self.dset.ndim, 1) + + def test_shape(self): + """ Verify shape """ + self.assertEqual(self.dset.shape, (13,)) + + def test_ellipsis(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[...]) + + def test_tuple(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[()]) + + def test_slice_simple(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[0:4]) + + def test_slice_zerosize(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[4:4]) + + def test_slice_strides(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[1:7:3]) + + def test_slice_negindexes(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[-8:-2:3]) + + def test_slice_stop_less_than_start(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[7:5]) + + def test_slice_outofrange(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[100:400:3]) + + def test_slice_backwards(self): + """ we disallow negative steps """ + with self.assertRaises(ValueError): + self.dset[::-1] + + def test_slice_zerostride(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[::0]) + + def test_index_simple(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[3]) + + def test_index_neg(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[-4]) + + # FIXME: NumPy permits this... it adds a new axis in front + def test_index_none(self): + with self.assertRaises(TypeError): + self.dset[None] + + def test_index_illegal(self): + """ Illegal slicing argument """ + with self.assertRaises(TypeError): + self.dset[{}] + + def test_index_outofrange(self): + with self.assertRaises(IndexError): + self.dset[100] + + def test_indexlist_simple(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[[1,2,5]]) + + def test_indexlist_numpyarray(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[np.array([1, 2, 5])]) + + def test_indexlist_single_index_ellipsis(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[[0], ...]) + + def test_indexlist_numpyarray_single_index_ellipsis(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[np.array([0]), ...]) + + def test_indexlist_numpyarray_ellipsis(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[np.array([1, 2, 5]), ...]) + + def test_indexlist_empty(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[[]]) + + def test_indexlist_outofrange(self): + with self.assertRaises(IndexError): + self.dset[[100]] + + def test_indexlist_nonmonotonic(self): + """ we require index list values to be strictly increasing """ + with self.assertRaises(TypeError): + self.dset[[1,3,2]] + + def test_indexlist_monotonic_negative(self): + # This should work: indices are logically increasing + self.assertNumpyBehavior(self.dset, self.data, np.s_[[0, 2, -2]]) + + with self.assertRaises(TypeError): + self.dset[[-2, -3]] + + def test_indexlist_repeated(self): + """ we forbid repeated index values """ + with self.assertRaises(TypeError): + self.dset[[1,1,2]] + + def test_mask_true(self): + self.assertNumpyBehavior( + self.dset, + self.data, + np.s_[self.data > -100], + # Fast reader doesn't work with boolean masks + skip_fast_reader=True, + ) + + def test_mask_false(self): + self.assertNumpyBehavior( + self.dset, + self.data, + np.s_[self.data > 100], + # Fast reader doesn't work with boolean masks + skip_fast_reader=True, + ) + + def test_mask_partial(self): + self.assertNumpyBehavior( + self.dset, + self.data, + np.s_[self.data > 5], + # Fast reader doesn't work with boolean masks + skip_fast_reader=True, + ) + + def test_mask_wrongsize(self): + """ we require the boolean mask shape to match exactly """ + with self.assertRaises(TypeError): + self.dset[np.ones((2,), dtype='bool')] + + def test_fieldnames(self): + """ field name -> ValueError (no fields) """ + with self.assertRaises(ValueError): + self.dset['field'] + + +class Test2DZeroFloat(TestCase): + + def setUp(self): + TestCase.setUp(self) + self.data = np.ones((0,3), dtype='f') + self.dset = self.f.create_dataset('x', data=self.data) + + def test_ndim(self): + """ Verify number of dimensions """ + self.assertEqual(self.dset.ndim, 2) + + def test_shape(self): + """ Verify shape """ + self.assertEqual(self.dset.shape, (0, 3)) + + def test_indexlist(self): + """ see issue #473 """ + self.assertNumpyBehavior(self.dset, self.data, np.s_[:,[0,1,2]]) + + +class Test2DFloat(TestCase): + + def setUp(self): + TestCase.setUp(self) + self.data = np.ones((5,3), dtype='f') + self.dset = self.f.create_dataset('x', data=self.data) + + def test_ndim(self): + """ Verify number of dimensions """ + self.assertEqual(self.dset.ndim, 2) + + def test_size(self): + """ Verify size """ + self.assertEqual(self.dset.size, 15) + + def test_nbytes(self): + """ Verify nbytes """ + self.assertEqual(self.dset.nbytes, 15*self.data.dtype.itemsize) # not sure if 'f' is always alias for 'f4' + + def test_shape(self): + """ Verify shape """ + self.assertEqual(self.dset.shape, (5, 3)) + + def test_indexlist(self): + """ see issue #473 """ + self.assertNumpyBehavior(self.dset, self.data, np.s_[:,[0,1,2]]) + + def test_index_emptylist(self): + self.assertNumpyBehavior(self.dset, self.data, np.s_[:, []]) + self.assertNumpyBehavior(self.dset, self.data, np.s_[[]]) + + +class TestVeryLargeArray(TestCase): + + def setUp(self): + TestCase.setUp(self) + self.dset = self.f.create_dataset('x', shape=(2**15, 2**16)) + + @ut.skipIf(sys.maxsize < 2**31, 'Maximum integer size >= 2**31 required') + def test_size(self): + self.assertEqual(self.dset.size, 2**31) + + +def test_read_no_fill_value(writable_file): + # With FILL_TIME_NEVER, HDF5 doesn't write zeros in the output array for + # unallocated chunks. If we read into uninitialized memory, it can appear + # to read random values. https://github.com/h5py/h5py/issues/2069 + dcpl = h5py.h5p.create(h5py.h5p.DATASET_CREATE) + dcpl.set_chunk((1,)) + dcpl.set_fill_time(h5py.h5d.FILL_TIME_NEVER) + ds = h5py.Dataset(h5py.h5d.create( + writable_file.id, b'a', h5py.h5t.IEEE_F64LE, h5py.h5s.create_simple((5,)), dcpl + )) + np.testing.assert_array_equal(ds[:3], np.zeros(3, np.float64)) + + +class TestBoolIndex(TestCase): + """ + Tests for indexing with Boolean arrays + """ + def setUp(self): + super().setUp() + self.arr = np.arange(9).reshape(3,-1) + self.dset = self.f.create_dataset('x', data=self.arr) + + def test_select_first_axis(self): + sel = np.s_[[False, True, False],:] + self.assertNumpyBehavior(self.dset, self.arr, sel) + + def test_wrong_size(self): + sel = np.s_[[False, True, False, False],:] + with self.assertRaises(TypeError): + self.dset[sel] diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dataset_swmr.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dataset_swmr.py new file mode 100644 index 0000000000000000000000000000000000000000..8b880f7bd01c28aa24d8dcff616cee62d7c5b23a --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dataset_swmr.py @@ -0,0 +1,118 @@ +import numpy as np +import h5py + +from .common import TestCase + + +class TestDatasetSwmrRead(TestCase): + """ Testing SWMR functions when reading a dataset. + Skip this test if the HDF5 library does not have the SWMR features. + """ + + def setUp(self): + TestCase.setUp(self) + self.data = np.arange(13).astype('f') + self.dset = self.f.create_dataset('data', chunks=(13,), maxshape=(None,), data=self.data) + fname = self.f.filename + self.f.close() + + self.f = h5py.File(fname, 'r', swmr=True) + self.dset = self.f['data'] + + def test_initial_swmr_mode_on(self): + """ Verify that the file is initially in SWMR mode""" + self.assertTrue(self.f.swmr_mode) + + def test_read_data(self): + self.assertArrayEqual(self.dset, self.data) + + def test_refresh(self): + self.dset.refresh() + + def test_force_swmr_mode_on_raises(self): + """ Verify when reading a file cannot be forcibly switched to swmr mode. + When reading with SWMR the file must be opened with swmr=True.""" + with self.assertRaises(Exception): + self.f.swmr_mode = True + self.assertTrue(self.f.swmr_mode) + + def test_force_swmr_mode_off_raises(self): + """ Switching SWMR write mode off is only possible by closing the file. + Attempts to forcibly switch off the SWMR mode should raise a ValueError. + """ + with self.assertRaises(ValueError): + self.f.swmr_mode = False + self.assertTrue(self.f.swmr_mode) + +class TestDatasetSwmrWrite(TestCase): + """ Testing SWMR functions when reading a dataset. + Skip this test if the HDF5 library does not have the SWMR features. + """ + + def setUp(self): + """ First setup a file with a small chunked and empty dataset. + No data written yet. + """ + + # Note that when creating the file, the swmr=True is not required for + # write, but libver='latest' is required. + self.f = h5py.File(self.mktemp(), 'w', libver='latest') + + self.data = np.arange(4).astype('f') + self.dset = self.f.create_dataset('data', shape=(0,), dtype=self.data.dtype, chunks=(2,), maxshape=(None,)) + + + def test_initial_swmr_mode_off(self): + """ Verify that the file is not initially in SWMR mode""" + self.assertFalse(self.f.swmr_mode) + + def test_switch_swmr_mode_on(self): + """ Switch to SWMR mode and verify """ + self.f.swmr_mode = True + self.assertTrue(self.f.swmr_mode) + + def test_switch_swmr_mode_off_raises(self): + """ Switching SWMR write mode off is only possible by closing the file. + Attempts to forcibly switch off the SWMR mode should raise a ValueError. + """ + self.f.swmr_mode = True + self.assertTrue(self.f.swmr_mode) + with self.assertRaises(ValueError): + self.f.swmr_mode = False + self.assertTrue(self.f.swmr_mode) + + def test_extend_dset(self): + """ Extend and flush a SWMR dataset + """ + self.f.swmr_mode = True + self.assertTrue(self.f.swmr_mode) + + self.dset.resize( self.data.shape ) + self.dset[:] = self.data + self.dset.flush() + + # Refresh and read back data for assertion + self.dset.refresh() + self.assertArrayEqual(self.dset, self.data) + + def test_extend_dset_multiple(self): + + self.f.swmr_mode = True + self.assertTrue(self.f.swmr_mode) + + self.dset.resize( (4,) ) + self.dset[0:] = self.data + self.dset.flush() + + # Refresh and read back 1st data block for assertion + self.dset.refresh() + self.assertArrayEqual(self.dset, self.data) + + self.dset.resize( (8,) ) + self.dset[4:] = self.data + self.dset.flush() + + # Refresh and read back 1st data block for assertion + self.dset.refresh() + self.assertArrayEqual(self.dset[0:4], self.data) + self.assertArrayEqual(self.dset[4:8], self.data) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_datatype.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_datatype.py new file mode 100644 index 0000000000000000000000000000000000000000..0b5691b870e984067c67c01ca7771ebd5bd52649 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_datatype.py @@ -0,0 +1,40 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + File-resident datatype tests. + + Tests "committed" file-resident datatype objects. +""" + +import numpy as np + +from .common import TestCase + +from h5py import Datatype + +class TestCreation(TestCase): + + """ + Feature: repr() works sensibly on datatype objects + """ + + def test_repr(self): + """ repr() on datatype objects """ + self.f['foo'] = np.dtype('S10') + dt = self.f['foo'] + self.assertIsInstance(repr(dt), str) + self.f.close() + self.assertIsInstance(repr(dt), str) + + + def test_appropriate_low_level_id(self): + " Binding a group to a non-TypeID identifier fails with ValueError " + with self.assertRaises(ValueError): + Datatype(self.f['/'].id) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dimension_scales.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dimension_scales.py new file mode 100644 index 0000000000000000000000000000000000000000..8d1664202abf673211f8a58e2d9c710c986b85f3 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dimension_scales.py @@ -0,0 +1,216 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + + +import numpy as np + +from .common import TestCase +from h5py import File +import h5py + + +class BaseDataset(TestCase): + + """ + data is a 3-dimensional dataset with dimensions [z, y, x] + + The z dimension is labeled. It does not have any attached scales. + The y dimension is not labeled. It has one attached scale. + The x dimension is labeled. It has two attached scales. + + data2 is a 3-dimensional dataset with no associated dimension scales. + """ + + def setUp(self): + self.f = File(self.mktemp(), 'w') + self.f['data'] = np.ones((4, 3, 2), 'f') + self.f['data2'] = np.ones((4, 3, 2), 'f') + self.f['x1'] = np.ones((2), 'f') + h5py.h5ds.set_scale(self.f['x1'].id) + h5py.h5ds.attach_scale(self.f['data'].id, self.f['x1'].id, 2) + self.f['x2'] = np.ones((2), 'f') + h5py.h5ds.set_scale(self.f['x2'].id, b'x2 name') + h5py.h5ds.attach_scale(self.f['data'].id, self.f['x2'].id, 2) + self.f['y1'] = np.ones((3), 'f') + h5py.h5ds.set_scale(self.f['y1'].id, b'y1 name') + h5py.h5ds.attach_scale(self.f['data'].id, self.f['y1'].id, 1) + self.f['z1'] = np.ones((4), 'f') + + h5py.h5ds.set_label(self.f['data'].id, 0, b'z') + h5py.h5ds.set_label(self.f['data'].id, 2, b'x') + + def tearDown(self): + if self.f: + self.f.close() + + +class TestH5DSBindings(BaseDataset): + + """ + Feature: Datasets can be created from existing data + """ + + def test_create_dimensionscale(self): + """ Create a dimension scale from existing dataset """ + self.assertTrue(h5py.h5ds.is_scale(self.f['x1'].id)) + self.assertEqual(h5py.h5ds.get_scale_name(self.f['x1'].id), b'') + self.assertEqual(self.f['x1'].attrs['CLASS'], b"DIMENSION_SCALE") + self.assertEqual(h5py.h5ds.get_scale_name(self.f['x2'].id), b'x2 name') + + def test_attach_dimensionscale(self): + self.assertTrue( + h5py.h5ds.is_attached(self.f['data'].id, self.f['x1'].id, 2) + ) + self.assertFalse( + h5py.h5ds.is_attached(self.f['data'].id, self.f['x1'].id, 1)) + self.assertEqual(h5py.h5ds.get_num_scales(self.f['data'].id, 0), 0) + self.assertEqual(h5py.h5ds.get_num_scales(self.f['data'].id, 1), 1) + self.assertEqual(h5py.h5ds.get_num_scales(self.f['data'].id, 2), 2) + + def test_detach_dimensionscale(self): + self.assertTrue( + h5py.h5ds.is_attached(self.f['data'].id, self.f['x1'].id, 2) + ) + h5py.h5ds.detach_scale(self.f['data'].id, self.f['x1'].id, 2) + self.assertFalse( + h5py.h5ds.is_attached(self.f['data'].id, self.f['x1'].id, 2) + ) + self.assertEqual(h5py.h5ds.get_num_scales(self.f['data'].id, 2), 1) + + def test_label_dimensionscale(self): + self.assertEqual(h5py.h5ds.get_label(self.f['data'].id, 0), b'z') + self.assertEqual(h5py.h5ds.get_label(self.f['data'].id, 1), b'') + self.assertEqual(h5py.h5ds.get_label(self.f['data'].id, 2), b'x') + + def test_iter_dimensionscales(self): + def func(dsid): + res = h5py.h5ds.get_scale_name(dsid) + if res == b'x2 name': + return dsid + + res = h5py.h5ds.iterate(self.f['data'].id, 2, func, 0) + self.assertEqual(h5py.h5ds.get_scale_name(res), b'x2 name') + + +class TestDimensionManager(BaseDataset): + + def test_make_scale(self): + # test recreating or renaming an existing scale: + self.f['x1'].make_scale(b'foobar') + self.assertEqual(self.f['data'].dims[2]['foobar'], self.f['x1']) + # test creating entirely new scale: + self.f['data2'].make_scale(b'foobaz') + self.f['data'].dims[2].attach_scale(self.f['data2']) + self.assertEqual(self.f['data'].dims[2]['foobaz'], self.f['data2']) + + def test_get_dimension(self): + with self.assertRaises(IndexError): + self.f['data'].dims[3] + + def test_len(self): + self.assertEqual(len(self.f['data'].dims), 3) + self.assertEqual(len(self.f['data2'].dims), 3) + + def test_iter(self): + dims = self.f['data'].dims + self.assertEqual( + [d for d in dims], + [dims[0], dims[1], dims[2]] + ) + + def test_repr(self): + ds = self.f.create_dataset('x', (2,3)) + self.assertIsInstance(repr(ds.dims), str) + self.f.close() + self.assertIsInstance(repr(ds.dims), str) + + +class TestDimensionsHighLevel(BaseDataset): + + def test_len(self): + self.assertEqual(len(self.f['data'].dims[0]), 0) + self.assertEqual(len(self.f['data'].dims[1]), 1) + self.assertEqual(len(self.f['data'].dims[2]), 2) + self.assertEqual(len(self.f['data2'].dims[0]), 0) + self.assertEqual(len(self.f['data2'].dims[1]), 0) + self.assertEqual(len(self.f['data2'].dims[2]), 0) + + def test_get_label(self): + self.assertEqual(self.f['data'].dims[2].label, 'x') + self.assertEqual(self.f['data'].dims[1].label, '') + self.assertEqual(self.f['data'].dims[0].label, 'z') + self.assertEqual(self.f['data2'].dims[2].label, '') + self.assertEqual(self.f['data2'].dims[1].label, '') + self.assertEqual(self.f['data2'].dims[0].label, '') + + def test_set_label(self): + self.f['data'].dims[0].label = 'foo' + self.assertEqual(self.f['data'].dims[2].label, 'x') + self.assertEqual(self.f['data'].dims[1].label, '') + self.assertEqual(self.f['data'].dims[0].label, 'foo') + + def test_detach_scale(self): + self.f['data'].dims[2].detach_scale(self.f['x1']) + self.assertEqual(len(self.f['data'].dims[2]), 1) + self.assertEqual(self.f['data'].dims[2][0], self.f['x2']) + self.f['data'].dims[2].detach_scale(self.f['x2']) + self.assertEqual(len(self.f['data'].dims[2]), 0) + + def test_attach_scale(self): + self.f['x3'] = self.f['x2'][...] + self.f['data'].dims[2].attach_scale(self.f['x3']) + self.assertEqual(len(self.f['data'].dims[2]), 3) + self.assertEqual(self.f['data'].dims[2][2], self.f['x3']) + + def test_get_dimension_scale(self): + self.assertEqual(self.f['data'].dims[2][0], self.f['x1']) + with self.assertRaises(RuntimeError): + self.f['data2'].dims[2][0], self.f['x2'] + self.assertEqual(self.f['data'].dims[2][''], self.f['x1']) + self.assertEqual(self.f['data'].dims[2]['x2 name'], self.f['x2']) + + def test_get_items(self): + self.assertEqual( + self.f['data'].dims[2].items(), + [('', self.f['x1']), ('x2 name', self.f['x2'])] + ) + + def test_get_keys(self): + self.assertEqual(self.f['data'].dims[2].keys(), ['', 'x2 name']) + + def test_get_values(self): + self.assertEqual( + self.f['data'].dims[2].values(), + [self.f['x1'], self.f['x2']] + ) + + def test_iter(self): + self.assertEqual([i for i in self.f['data'].dims[2]], ['', 'x2 name']) + + def test_repr(self): + ds = self.f["data"] + self.assertEqual(repr(ds.dims[2])[1:16], '"x" dimension 2') + self.f.close() + self.assertIsInstance(repr(ds.dims), str) + + def test_attributes(self): + self.f["data2"].attrs["DIMENSION_LIST"] = self.f["data"].attrs[ + "DIMENSION_LIST"] + self.assertEqual(len(self.f['data2'].dims[0]), 0) + self.assertEqual(len(self.f['data2'].dims[1]), 1) + self.assertEqual(len(self.f['data2'].dims[2]), 2) + + def test_is_scale(self): + """Test Dataset.is_scale property""" + self.assertTrue(self.f['x1'].is_scale) + self.assertTrue(self.f['x2'].is_scale) + self.assertTrue(self.f['y1'].is_scale) + self.assertFalse(self.f['z1'].is_scale) + self.assertFalse(self.f['data'].is_scale) + self.assertFalse(self.f['data2'].is_scale) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dims_dimensionproxy.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dims_dimensionproxy.py new file mode 100644 index 0000000000000000000000000000000000000000..fe60e1de5a1b01c0de11ed3e82fa4e489b14e61a --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dims_dimensionproxy.py @@ -0,0 +1,22 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Tests the h5py.Dataset.dims.DimensionProxy class. +""" + + +from .common import TestCase + +class TestItems(TestCase): + + def test_empty(self): + """ no dimension scales -> empty list """ + dset = self.f.create_dataset('x', (10,)) + self.assertEqual(dset.dims[0].items(), []) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dtype.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dtype.py new file mode 100644 index 0000000000000000000000000000000000000000..87748c46d583cc2854ad3c1a43e46042ed0c738a --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_dtype.py @@ -0,0 +1,532 @@ +""" + Tests for converting between numpy dtypes and h5py data types +""" + +from itertools import count +import platform +import numpy as np +import h5py +try: + import tables +except ImportError: + tables = None + +from .common import ut, TestCase + +UNSUPPORTED_LONG_DOUBLE = ('i386', 'i486', 'i586', 'i686', 'ppc64le') +UNSUPPORTED_LONG_DOUBLE_TYPES = ('float96', 'float128', 'complex192', + 'complex256') + + +class TestVlen(TestCase): + + """ + Check that storage of vlen strings is carried out correctly. + """ + def assertVlenArrayEqual(self, dset, arr, message=None, precision=None): + assert dset.shape == arr.shape, \ + "Shape mismatch (%s vs %s)%s" % (dset.shape, arr.shape, message) + for (i, d, a) in zip(count(), dset, arr): + self.assertArrayEqual(d, a, message, precision) + + def test_compound(self): + + fields = [] + fields.append(('field_1', h5py.string_dtype())) + fields.append(('field_2', np.int32)) + dt = np.dtype(fields) + self.f['mytype'] = np.dtype(dt) + dt_out = self.f['mytype'].dtype.fields['field_1'][0] + string_inf = h5py.check_string_dtype(dt_out) + self.assertEqual(string_inf.encoding, 'utf-8') + + def test_compound_vlen_bool(self): + vidt = h5py.vlen_dtype(np.uint8) + def a(items): + return np.array(items, dtype=np.uint8) + + f = self.f + + dt_vb = np.dtype([ + ('foo', vidt), + ('logical', bool)]) + vb = f.create_dataset('dt_vb', shape=(4,), dtype=dt_vb) + data = np.array([(a([1, 2, 3]), True), + (a([1 ]), False), + (a([1, 5 ]), True), + (a([],), False), ], + dtype=dt_vb) + vb[:] = data + actual = f['dt_vb'][:] + self.assertVlenArrayEqual(data['foo'], actual['foo']) + self.assertArrayEqual(data['logical'], actual['logical']) + + dt_vv = np.dtype([ + ('foo', vidt), + ('bar', vidt)]) + f.create_dataset('dt_vv', shape=(4,), dtype=dt_vv) + + dt_vvb = np.dtype([ + ('foo', vidt), + ('bar', vidt), + ('logical', bool)]) + vvb = f.create_dataset('dt_vvb', shape=(2,), dtype=dt_vvb) + + dt_bvv = np.dtype([ + ('logical', bool), + ('foo', vidt), + ('bar', vidt)]) + bvv = f.create_dataset('dt_bvv', shape=(2,), dtype=dt_bvv) + data = np.array([(True, a([1, 2, 3]), a([1, 2])), + (False, a([]), a([2, 4, 6])), ], + dtype=bvv) + bvv[:] = data + actual = bvv[:] + self.assertVlenArrayEqual(data['foo'], actual['foo']) + self.assertVlenArrayEqual(data['bar'], actual['bar']) + self.assertArrayEqual(data['logical'], actual['logical']) + + def test_compound_vlen_enum(self): + eidt = h5py.enum_dtype({'OFF': 0, 'ON': 1}, basetype=np.uint8) + vidt = h5py.vlen_dtype(np.uint8) + def a(items): + return np.array(items, dtype=np.uint8) + + f = self.f + + dt_vve = np.dtype([ + ('foo', vidt), + ('bar', vidt), + ('switch', eidt)]) + vve = f.create_dataset('dt_vve', shape=(2,), dtype=dt_vve) + data = np.array([(a([1, 2, 3]), a([1, 2]), 1), + (a([]), a([2, 4, 6]), 0), ], + dtype=dt_vve) + vve[:] = data + actual = vve[:] + self.assertVlenArrayEqual(data['foo'], actual['foo']) + self.assertVlenArrayEqual(data['bar'], actual['bar']) + self.assertArrayEqual(data['switch'], actual['switch']) + + def test_vlen_enum(self): + fname = self.mktemp() + arr1 = [[1], [1, 2]] + dt1 = h5py.vlen_dtype(h5py.enum_dtype(dict(foo=1, bar=2), 'i')) + + with h5py.File(fname, 'w') as f: + df1 = f.create_dataset('test', (len(arr1),), dtype=dt1) + df1[:] = np.array(arr1, dtype=object) + + with h5py.File(fname, 'r') as f: + df2 = f['test'] + dt2 = df2.dtype + arr2 = [e.tolist() for e in df2[:]] + + self.assertEqual(arr1, arr2) + self.assertEqual(h5py.check_enum_dtype(h5py.check_vlen_dtype(dt1)), + h5py.check_enum_dtype(h5py.check_vlen_dtype(dt2))) + + +def test_write_empty_vlen(writable_file): + # vlen dtype with no entries + d = np.rec.fromarrays([[], []], names='a,b', formats='|V16,O') + dset = writable_file.create_dataset( + 'test', data=d, dtype=[('a', '|V16'), ('b', h5py.special_dtype(vlen=np.float64))] + ) + assert dset.size == 0 + + +def test_write_vlen_length0_compound(writable_file): + # one entry has variable length 0 (using the variable length) + # https://github.com/h5py/h5py/issues/2693 + compound_dtype = np.dtype([('id', 'i4'), ('value', 'f8'), ('name', 'S10')]) + vlen_compound_dtype = h5py.special_dtype(vlen=compound_dtype) + arr0 = np.array([(1, 3.14, b'test1'), (2, 2.71, b'test2')], dtype=compound_dtype) + arr1 = np.array([], dtype=compound_dtype) + + dset = writable_file.create_dataset( + 'vlen_compound_data', shape=(2,), dtype=vlen_compound_dtype + ) + dset[0] = arr0 + dset[1] = arr1 + + np.testing.assert_array_equal(dset[0], arr0) # With data + np.testing.assert_array_equal(dset[1], arr1) # Without data + + +class TestExplicitCast(TestCase): + def test_f2_casting(self): + fname = self.mktemp() + + np.random.seed(1) + A = np.random.rand(1500, 20) + + # Save to HDF5 file + with h5py.File(fname, "w") as Fid: + Fid.create_dataset("Data", data=A, dtype='f2') + + with h5py.File(fname, "r") as Fid: + B = Fid["Data"][:] + + # Compare + self.assertTrue(np.all(A.astype('f2') == B)) + + +class TestOffsets(TestCase): + """ + Check that compound members with aligned or manual offsets are handled + correctly. + """ + + def test_compound_vlen(self): + vidt = h5py.vlen_dtype(np.uint8) + eidt = h5py.enum_dtype({'OFF': 0, 'ON': 1}, basetype=np.uint8) + + for np_align in (False, True): + dt = np.dtype([ + ('a', eidt), + ('foo', vidt), + ('bar', vidt), + ('switch', eidt)], align=np_align) + np_offsets = [dt.fields[i][1] for i in dt.names] + + for logical in (False, True): + if logical and np_align: + # Vlen types have different size in the numpy struct + self.assertRaises(TypeError, h5py.h5t.py_create, dt, + logical=logical) + else: + ht = h5py.h5t.py_create(dt, logical=logical) + offsets = [ht.get_member_offset(i) + for i in range(ht.get_nmembers())] + if np_align: + self.assertEqual(np_offsets, offsets) + + def test_aligned_offsets(self): + dt = np.dtype('i4,i8,i2', align=True) + ht = h5py.h5t.py_create(dt) + self.assertEqual(dt.itemsize, ht.get_size()) + self.assertEqual( + [dt.fields[i][1] for i in dt.names], + [ht.get_member_offset(i) for i in range(ht.get_nmembers())] + ) + + def test_aligned_data(self): + dt = np.dtype('i4,f8,i2', align=True) + data = np.zeros(10, dtype=dt) + + data['f0'] = np.array(np.random.randint(-100, 100, size=data.size), + dtype='i4') + data['f1'] = np.random.rand(data.size) + data['f2'] = np.array(np.random.randint(-100, 100, size=data.size), + dtype='i2') + + fname = self.mktemp() + + with h5py.File(fname, 'w') as f: + f['data'] = data + + with h5py.File(fname, 'r') as f: + self.assertArrayEqual(f['data'], data) + + def test_compound_robustness(self): + # make an out of order compound type with gaps in it, and larger itemsize than minimum + # Idea is to be robust to type descriptions we *could* get out of HDF5 files, from custom descriptions + # of types in addition to numpy's flakey history on unaligned fields with non-standard or padded layouts. + fields = [ + ('f0', np.float64, 25), + ('f1', np.uint64, 9), + ('f2', np.uint32, 0), + ('f3', np.uint16, 5) + ] + lastfield = fields[np.argmax([ x[2] for x in fields ])] + itemsize = lastfield[2] + np.dtype(lastfield[1]).itemsize + 6 + extract_index = lambda index, sequence: [ x[index] for x in sequence ] + + dt = np.dtype({ + 'names' : extract_index(0, fields), + 'formats' : extract_index(1, fields), + 'offsets' : extract_index(2, fields), + # 'aligned': False, - already defaults to False + 'itemsize': itemsize + }) + + self.assertTrue(dt.itemsize == itemsize) + data = np.zeros(10, dtype=dt) + + # don't trust numpy struct handling, keep fields out of band in case content insertion is erroneous + # yes... this has also been known to happen. + f1 = np.array([1 + i * 4 for i in range(data.shape[0])], dtype=dt.fields['f1'][0]) + f2 = np.array([2 + i * 4 for i in range(data.shape[0])], dtype=dt.fields['f2'][0]) + f3 = np.array([3 + i * 4 for i in range(data.shape[0])], dtype=dt.fields['f3'][0]) + f0c = 3.14 + data['f0'] = f0c + data['f3'] = f3 + data['f1'] = f1 + data['f2'] = f2 + + # numpy consistency checks + self.assertTrue(np.all(data['f0'] == f0c)) + self.assertArrayEqual(data['f3'], f3) + self.assertArrayEqual(data['f1'], f1) + self.assertArrayEqual(data['f2'], f2) + + fname = self.mktemp() + + with h5py.File(fname, 'w') as fd: + fd.create_dataset('data', data=data) + + with h5py.File(fname, 'r') as fd: + readback = fd['data'] + self.assertTrue(readback.dtype == dt) + self.assertArrayEqual(readback, data) + self.assertTrue(np.all(readback['f0'] == f0c)) + self.assertArrayEqual(readback['f1'], f1) + self.assertArrayEqual(readback['f2'], f2) + self.assertArrayEqual(readback['f3'], f3) + + def test_out_of_order_offsets(self): + dt = np.dtype({ + 'names' : ['f1', 'f2', 'f3'], + 'formats' : ['']: + dt_descr = f'{dt_order}M8[{dt_unit}]' + dt = h5py.opaque_dtype(np.dtype(dt_descr)) + arr = np.array([0], dtype=np.int64).view(dtype=dt) + + with h5py.File(fname, 'w') as f: + dset = f.create_dataset("default", data=arr, dtype=dt) + self.assertArrayEqual(arr, dset) + self.assertEqual(arr.dtype, dset.dtype) + + def test_timedelta(self): + fname = self.mktemp() + + for dt_unit in self.datetime_units: + for dt_order in ['<', '>']: + dt_descr = f'{dt_order}m8[{dt_unit}]' + dt = h5py.opaque_dtype(np.dtype(dt_descr)) + arr = np.array([np.timedelta64(500, dt_unit)], dtype=dt) + + with h5py.File(fname, 'w') as f: + dset = f.create_dataset("default", data=arr, dtype=dt) + self.assertArrayEqual(arr, dset) + self.assertEqual(arr.dtype, dset.dtype) + +@ut.skipUnless(tables is not None, 'tables is required') +class TestBitfield(TestCase): + + """ + Test H5T_NATIVE_B8 reading + """ + + def test_b8_bool(self): + arr1 = np.array([False, True], dtype=bool) + self._test_b8( + arr1, + expected_default_cast_dtype=np.uint8 + ) + self._test_b8( + arr1, + expected_default_cast_dtype=np.uint8, + cast_dtype=np.uint8 + ) + + def test_b8_bool_compound(self): + arr1 = np.array([(False,), (True,)], dtype=np.dtype([('x', '?')])) + self._test_b8( + arr1, + expected_default_cast_dtype=np.dtype([('x', 'u1')]) + ) + self._test_b8( + arr1, + expected_default_cast_dtype=np.dtype([('x', 'u1')]), + cast_dtype=np.dtype([('x', 'u1')]) + ) + + def test_b8_bool_compound_nested(self): + arr1 = np.array( + [(True, (True, False)), (True, (False, True))], + dtype=np.dtype([('x', '?'), ('y', [('a', '?'), ('b', '?')])]), + ) + self._test_b8( + arr1, + expected_default_cast_dtype=np.dtype( + [('x', 'u1'), ('y', [('a', 'u1'), ('b', 'u1')])] + ) + ) + self._test_b8( + arr1, + expected_default_cast_dtype=np.dtype( + [('x', 'u1'), ('y', [('a', 'u1'), ('b', 'u1')])] + ), + cast_dtype=np.dtype([('x', 'u1'), ('y', [('a', 'u1'), ('b', 'u1')])]), + ) + + def test_b8_bool_compound_mixed_types(self): + arr1 = np.array( + [(True, 0.5), (False, 0.2)], dtype=np.dtype([('x','?'), ('y', ' (1, 14, 3), + reason='Requires HDF5 <= 1.14.3') + def test_too_small_pbs(self): + """Page buffer size must be greater than file space page size.""" + fname = self.mktemp() + fsp = 16 * 1024 + with File(fname, mode='w', fs_strategy='page', fs_page_size=fsp): + pass + with self.assertRaises(OSError): + File(fname, mode="r", page_buf_size=fsp-1) + + @pytest.mark.skipif(h5py.version.hdf5_version_tuple < (1, 14, 4), + reason='Requires HDF5 >= 1.14.4') + def test_open_nonpage_pbs(self): + """Open non-PAGE file with page buffer set.""" + fname = self.mktemp() + fsp = 16 * 1024 + with File(fname, mode='w'): + pass + with File(fname, mode='r', page_buf_size=fsp) as f: + fapl = f.id.get_access_plist() + assert fapl.get_page_buffer_size()[0] == 0 + + @pytest.mark.skipif(h5py.version.hdf5_version_tuple < (1, 14, 4), + reason='Requires HDF5 >= 1.14.4') + def test_smaller_pbs(self): + """Adjust page buffer size automatically when smaller than file page.""" + fname = self.mktemp() + fsp = 16 * 1024 + with File(fname, mode='w', fs_strategy='page', fs_page_size=fsp): + pass + with File(fname, mode='r', page_buf_size=fsp-100) as f: + fapl = f.id.get_access_plist() + assert fapl.get_page_buffer_size()[0] == fsp + + def test_actual_pbs(self): + """Verify actual page buffer size.""" + fname = self.mktemp() + fsp = 16 * 1024 + pbs = 2 * fsp + with File(fname, mode='w', fs_strategy='page', fs_page_size=fsp): + pass + with File(fname, mode='r', page_buf_size=pbs-1) as f: + fapl = f.id.get_access_plist() + self.assertEqual(fapl.get_page_buffer_size()[0], fsp) + + +class TestModes(TestCase): + + """ + Feature: File mode can be retrieved via file.mode + """ + + def test_mode_attr(self): + """ Mode equivalent can be retrieved via property """ + fname = self.mktemp() + with File(fname, 'w') as f: + self.assertEqual(f.mode, 'r+') + with File(fname, 'r') as f: + self.assertEqual(f.mode, 'r') + + def test_mode_external(self): + """ Mode property works for files opened via external links + + Issue 190. + """ + fname1 = self.mktemp() + fname2 = self.mktemp() + + f1 = File(fname1, 'w') + f1.close() + + f2 = File(fname2, 'w') + try: + f2['External'] = h5py.ExternalLink(fname1, '/') + f3 = f2['External'].file + self.assertEqual(f3.mode, 'r+') + finally: + f2.close() + f3.close() + + f2 = File(fname2, 'r') + try: + f3 = f2['External'].file + self.assertEqual(f3.mode, 'r') + finally: + f2.close() + f3.close() + + +class TestDrivers(TestCase): + + """ + Feature: Files can be opened with low-level HDF5 drivers. Does not + include MPI drivers (see bottom). + """ + + @ut.skipUnless(os.name == 'posix', "Stdio driver is supported on posix") + def test_stdio(self): + """ Stdio driver is supported on posix """ + fid = File(self.mktemp(), 'w', driver='stdio') + self.assertTrue(fid) + self.assertEqual(fid.driver, 'stdio') + fid.close() + + # Testing creation with append flag + fid = File(self.mktemp(), 'a', driver='stdio') + self.assertTrue(fid) + self.assertEqual(fid.driver, 'stdio') + fid.close() + + @ut.skipUnless(direct_vfd, + "DIRECT driver is supported on Linux if hdf5 is " + "built with the appriorate flags.") + def test_direct(self): + """ DIRECT driver is supported on Linux""" + fid = File(self.mktemp(), 'w', driver='direct') + self.assertTrue(fid) + self.assertEqual(fid.driver, 'direct') + default_fapl = fid.id.get_access_plist().get_fapl_direct() + fid.close() + + # Testing creation with append flag + fid = File(self.mktemp(), 'a', driver='direct') + self.assertTrue(fid) + self.assertEqual(fid.driver, 'direct') + fid.close() + + # 2022/02/26: hnmaarrfk + # I'm actually not too sure of the restriction on the + # different valid block_sizes and cbuf_sizes on different hardware + # platforms. + # + # I've learned a few things: + # * cbuf_size: Copy buffer size must be a multiple of block size + # The alignment (on my platform x86-64bit with an NVMe SSD + # could be an integer multiple of 512 + # + # To allow HDF5 to do the heavy lifting for different platform, + # We didn't provide any arguments to the first call + # and obtained HDF5's default values there. + + # Testing creation with a few different property lists + for alignment, block_size, cbuf_size in [ + default_fapl, + (default_fapl[0], default_fapl[1], 3 * default_fapl[1]), + (default_fapl[0] * 2, default_fapl[1], 3 * default_fapl[1]), + (default_fapl[0], 2 * default_fapl[1], 6 * default_fapl[1]), + ]: + with File(self.mktemp(), 'w', driver='direct', + alignment=alignment, + block_size=block_size, + cbuf_size=cbuf_size) as fid: + actual_fapl = fid.id.get_access_plist().get_fapl_direct() + actual_alignment = actual_fapl[0] + actual_block_size = actual_fapl[1] + actual_cbuf_size = actual_fapl[2] + assert actual_alignment == alignment + assert actual_block_size == block_size + assert actual_cbuf_size == actual_cbuf_size + + @ut.skipUnless(os.name == 'posix', "Sec2 driver is supported on posix") + def test_sec2(self): + """ Sec2 driver is supported on posix """ + fid = File(self.mktemp(), 'w', driver='sec2') + self.assertTrue(fid) + self.assertEqual(fid.driver, 'sec2') + fid.close() + + # Testing creation with append flag + fid = File(self.mktemp(), 'a', driver='sec2') + self.assertTrue(fid) + self.assertEqual(fid.driver, 'sec2') + fid.close() + + def test_core(self): + """ Core driver is supported (no backing store) """ + fname = self.mktemp() + fid = File(fname, 'w', driver='core', backing_store=False) + self.assertTrue(fid) + self.assertEqual(fid.driver, 'core') + fid.close() + self.assertFalse(os.path.exists(fname)) + + # Testing creation with append flag + fid = File(self.mktemp(), 'a', driver='core') + self.assertTrue(fid) + self.assertEqual(fid.driver, 'core') + fid.close() + + def test_backing(self): + """ Core driver saves to file when backing store used """ + fname = self.mktemp() + fid = File(fname, 'w', driver='core', backing_store=True) + fid.create_group('foo') + fid.close() + fid = File(fname, 'r') + assert 'foo' in fid + fid.close() + # keywords for other drivers are invalid when using the default driver + with self.assertRaises(TypeError): + File(fname, 'w', backing_store=True) + + def test_readonly(self): + """ Core driver can be used to open existing files """ + fname = self.mktemp() + fid = File(fname, 'w') + fid.create_group('foo') + fid.close() + fid = File(fname, 'r', driver='core') + self.assertTrue(fid) + assert 'foo' in fid + with self.assertRaises(ValueError): + fid.create_group('bar') + fid.close() + + def test_blocksize(self): + """ Core driver supports variable block size """ + fname = self.mktemp() + fid = File(fname, 'w', driver='core', block_size=1024, + backing_store=False) + self.assertTrue(fid) + fid.close() + + def test_split(self): + """ Split stores metadata in a separate file """ + fname = self.mktemp() + fid = File(fname, 'w', driver='split') + fid.close() + self.assertTrue(os.path.exists(fname + '-m.h5')) + fid = File(fname, 'r', driver='split') + self.assertTrue(fid) + fid.close() + + def test_fileobj(self): + """ Python file object driver is supported """ + tf = tempfile.TemporaryFile() + fid = File(tf, 'w', driver='fileobj') + self.assertTrue(fid) + self.assertEqual(fid.driver, 'fileobj') + fid.close() + # Driver must be 'fileobj' for file-like object if specified + with self.assertRaises(ValueError): + File(tf, 'w', driver='core') + tf.close() + + # TODO: family driver tests + + +@pytest.mark.skipif( + h5py.version.hdf5_version_tuple[1] % 2 != 0 , + reason='Not HDF5 release version' +) +class TestNewLibver(TestCase): + + """ + Feature: File format compatibility bounds can be specified when + opening a file. + """ + + @classmethod + def setUpClass(cls): + super().setUpClass() + + # Current latest library bound label + if h5py.version.hdf5_version_tuple < (1, 11, 4): + cls.latest = 'v110' + elif h5py.version.hdf5_version_tuple < (1, 13, 0): + cls.latest = 'v112' + elif h5py.version.hdf5_version_tuple < (2, 0, 0): + cls.latest = 'v114' + else: + cls.latest = 'v200' + + def test_default(self): + """ Opening with no libver arg """ + f = File(self.mktemp(), 'w') + self.assertEqual(f.libver, ('earliest', self.latest)) + f.close() + + def test_single(self): + """ Opening with single libver arg """ + f = File(self.mktemp(), 'w', libver='latest') + self.assertEqual(f.libver, (self.latest, self.latest)) + f.close() + + def test_single_v108(self): + """ Opening with "v108" libver arg """ + f = File(self.mktemp(), 'w', libver='v108') + self.assertEqual(f.libver, ('v108', self.latest)) + f.close() + + def test_single_v110(self): + """ Opening with "v110" libver arg """ + f = File(self.mktemp(), 'w', libver='v110') + self.assertEqual(f.libver, ('v110', self.latest)) + f.close() + + @ut.skipIf(h5py.version.hdf5_version_tuple < (1, 11, 4), + 'Requires HDF5 1.11.4 or later') + def test_single_v112(self): + """ Opening with "v112" libver arg """ + f = File(self.mktemp(), 'w', libver='v112') + self.assertEqual(f.libver, ('v112', self.latest)) + f.close() + + @ut.skipIf(h5py.version.hdf5_version_tuple < (1, 14, 0), + 'Requires HDF5 1.14 or later') + def test_single_v114(self): + """ Opening with "v114" libver arg """ + f = File(self.mktemp(), 'w', libver='v114') + self.assertEqual(f.libver, ('v114', self.latest)) + f.close() + + @ut.skipIf(h5py.version.hdf5_version_tuple < (2, 0, 0), + 'Requires HDF5 2.0 or later') + def test_single_v200(self): + """ Opening with "v200" libver arg """ + f = File(self.mktemp(), 'w', libver='v200') + self.assertEqual(f.libver, ('v200', self.latest)) + f.close() + + def test_multiple(self): + """ Opening with two libver args """ + f = File(self.mktemp(), 'w', libver=('earliest', 'v108')) + self.assertEqual(f.libver, ('earliest', 'v108')) + f.close() + + def test_none(self): + """ Omitting libver arg results in maximum compatibility """ + f = File(self.mktemp(), 'w') + self.assertEqual(f.libver, ('earliest', self.latest)) + f.close() + + +class TestUserblock(TestCase): + + """ + Feature: Files can be create with user blocks + """ + + def test_create_blocksize(self): + """ User blocks created with w, w-, x and properties work correctly """ + f = File(self.mktemp(), 'w-', userblock_size=512) + try: + self.assertEqual(f.userblock_size, 512) + finally: + f.close() + + f = File(self.mktemp(), 'x', userblock_size=512) + try: + self.assertEqual(f.userblock_size, 512) + finally: + f.close() + + f = File(self.mktemp(), 'w', userblock_size=512) + try: + self.assertEqual(f.userblock_size, 512) + finally: + f.close() + # User block size must be an integer + with self.assertRaises(ValueError): + File(self.mktemp(), 'w', userblock_size='non') + + def test_write_only(self): + """ User block only allowed for write """ + name = self.mktemp() + f = File(name, 'w') + f.close() + + with self.assertRaises(ValueError): + f = h5py.File(name, 'r', userblock_size=512) + + with self.assertRaises(ValueError): + f = h5py.File(name, 'r+', userblock_size=512) + + def test_match_existing(self): + """ User block size must match that of file when opening for append """ + name = self.mktemp() + f = File(name, 'w', userblock_size=512) + f.close() + + with self.assertRaises(ValueError): + f = File(name, 'a', userblock_size=1024) + + f = File(name, 'a', userblock_size=512) + try: + self.assertEqual(f.userblock_size, 512) + finally: + f.close() + + def test_power_of_two(self): + """ User block size must be a power of 2 and at least 512 """ + name = self.mktemp() + + with self.assertRaises(ValueError): + f = File(name, 'w', userblock_size=128) + + with self.assertRaises(ValueError): + f = File(name, 'w', userblock_size=513) + + with self.assertRaises(ValueError): + f = File(name, 'w', userblock_size=1023) + + def test_write_block(self): + """ Test that writing to a user block does not destroy the file """ + name = self.mktemp() + + f = File(name, 'w', userblock_size=512) + f.create_group("Foobar") + f.close() + + pyfile = open(name, 'r+b') + try: + pyfile.write(b'X' * 512) + finally: + pyfile.close() + + f = h5py.File(name, 'r') + try: + assert "Foobar" in f + finally: + f.close() + + pyfile = open(name, 'rb') + try: + self.assertEqual(pyfile.read(512), b'X' * 512) + finally: + pyfile.close() + + +class TestContextManager(TestCase): + + """ + Feature: File objects can be used as context managers + """ + + def test_context_manager(self): + """ File objects can be used in with statements """ + with File(self.mktemp(), 'w') as fid: + self.assertTrue(fid) + self.assertTrue(not fid) + + +@ut.skipIf(not UNICODE_FILENAMES, "Filesystem unicode support required") +class TestUnicode(TestCase): + + """ + Feature: Unicode filenames are supported + """ + + def test_unicode(self): + """ Unicode filenames can be used, and retrieved properly via .filename + """ + fname = self.mktemp(prefix=chr(0x201a)) + fid = File(fname, 'w') + try: + self.assertEqual(fid.filename, fname) + self.assertIsInstance(fid.filename, str) + finally: + fid.close() + + def test_unicode_hdf5_python_consistent(self): + """ Unicode filenames can be used, and seen correctly from python + """ + fname = self.mktemp(prefix=chr(0x201a)) + print(h5py.version.info) + from h5py._hl.compat import WINDOWS_ENCODING + print("Windows file encoding in use", WINDOWS_ENCODING) + print(f"Creating {fname!r}") + with File(fname, 'w') as f: + print(os.listdir(self.tempdir)) + assert os.path.exists(fname) + + def test_nonexistent_file_unicode(self): + """ + Modes 'r' and 'r+' do not create files even when given unicode names + """ + fname = self.mktemp(prefix=chr(0x201a)) + with self.assertRaises(OSError): + File(fname, 'r') + with self.assertRaises(OSError): + File(fname, 'r+') + + +class TestFileProperty(TestCase): + + """ + Feature: A File object can be retrieved from any child object, + via the .file property + """ + + def test_property(self): + """ File object can be retrieved from subgroup """ + fname = self.mktemp() + hfile = File(fname, 'w') + try: + hfile2 = hfile['/'].file + self.assertEqual(hfile, hfile2) + finally: + hfile.close() + + def test_close(self): + """ All retrieved File objects are closed at the same time """ + fname = self.mktemp() + hfile = File(fname, 'w') + grp = hfile.create_group('foo') + hfile2 = grp.file + hfile3 = hfile['/'].file + hfile2.close() + self.assertFalse(hfile) + self.assertFalse(hfile2) + self.assertFalse(hfile3) + + def test_mode(self): + """ Retrieved File objects have a meaningful mode attribute """ + hfile = File(self.mktemp(), 'w') + try: + grp = hfile.create_group('foo') + self.assertEqual(grp.file.mode, hfile.mode) + finally: + hfile.close() + + +class TestClose(TestCase): + + """ + Feature: Files can be closed + """ + + def test_close(self): + """ Close file via .close method """ + fid = File(self.mktemp(), 'w') + self.assertTrue(fid) + fid.close() + self.assertFalse(fid) + + def test_closed_file(self): + """ Trying to modify closed file raises ValueError """ + fid = File(self.mktemp(), 'w') + fid.close() + with self.assertRaises(ValueError): + fid.create_group('foo') + + def test_close_multiple_default_driver(self): + fname = self.mktemp() + f = h5py.File(fname, 'w') + f.create_group("test") + f.close() + f.close() + + +class TestFlush(TestCase): + + """ + Feature: Files can be flushed + """ + + def test_flush(self): + """ Flush via .flush method """ + fid = File(self.mktemp(), 'w') + fid.flush() + fid.close() + + +class TestRepr(TestCase): + + """ + Feature: File objects provide a helpful __repr__ string + """ + + def test_repr(self): + """ __repr__ behaves itself when files are open and closed """ + fid = File(self.mktemp(), 'w') + self.assertIsInstance(repr(fid), str) + fid.close() + self.assertIsInstance(repr(fid), str) + + +class TestFilename(TestCase): + + """ + Feature: The name of a File object can be retrieved via .filename + """ + + def test_filename(self): + """ .filename behaves properly for string data """ + fname = self.mktemp() + fid = File(fname, 'w') + try: + self.assertEqual(fid.filename, fname) + self.assertIsInstance(fid.filename, str) + finally: + fid.close() + + +class TestCloseInvalidatesOpenObjectIDs(TestCase): + + """ + Ensure that closing a file invalidates object IDs, as appropriate + """ + + def test_close(self): + """ Closing a file invalidates any of the file's open objects """ + with File(self.mktemp(), 'w') as f1: + g1 = f1.create_group('foo') + self.assertTrue(bool(f1.id)) + self.assertTrue(bool(g1.id)) + f1.close() + self.assertFalse(bool(f1.id)) + self.assertFalse(bool(g1.id)) + with File(self.mktemp(), 'w') as f2: + g2 = f2.create_group('foo') + self.assertTrue(bool(f2.id)) + self.assertTrue(bool(g2.id)) + self.assertFalse(bool(f1.id)) + self.assertFalse(bool(g1.id)) + + def test_close_one_handle(self): + fname = self.mktemp() + with File(fname, 'w') as f: + f.create_group('foo') + + f1 = File(fname) + f2 = File(fname) + g1 = f1['foo'] + g2 = f2['foo'] + assert g1.id.valid + assert g2.id.valid + f1.close() + assert not g1.id.valid + # Closing f1 shouldn't close f2 or objects belonging to it + assert f2.id.valid + assert g2.id.valid + + f2.close() + assert not f2.id.valid + assert not g2.id.valid + + +class TestPathlibSupport(TestCase): + + """ + Check that h5py doesn't break on pathlib + """ + def test_pathlib_accepted_file(self): + """ Check that pathlib is accepted by h5py.File """ + with closed_tempfile() as f: + path = pathlib.Path(f) + with File(path, 'w') as f2: + self.assertTrue(True) + + def test_pathlib_name_match(self): + """ Check that using pathlib does not affect naming """ + with closed_tempfile() as f: + path = pathlib.Path(f) + with File(path, 'w') as h5f1: + pathlib_name = h5f1.filename + with File(f, 'w') as h5f2: + normal_name = h5f2.filename + self.assertEqual(pathlib_name, normal_name) + + +class TestPickle(TestCase): + """Check that h5py.File can't be pickled""" + def test_dump_error(self): + with File(self.mktemp(), 'w') as f1: + with self.assertRaises(TypeError): + pickle.dumps(f1) + + +# unittest doesn't work with pytest fixtures (and possibly other features), +# hence no subclassing TestCase +@pytest.mark.mpi +class TestMPI: + def test_mpio(self, mpi_file_name): + """ MPIO driver and options """ + from mpi4py import MPI + + with File(mpi_file_name, 'w', driver='mpio', comm=MPI.COMM_WORLD) as f: + assert f + assert f.driver == 'mpio' + + def test_mpio_append(self, mpi_file_name): + """ Testing creation of file with append """ + from mpi4py import MPI + + with File(mpi_file_name, 'a', driver='mpio', comm=MPI.COMM_WORLD) as f: + assert f + assert f.driver == 'mpio' + + def test_mpi_atomic(self, mpi_file_name): + """ Enable atomic mode for MPIO driver """ + from mpi4py import MPI + + with File(mpi_file_name, 'w', driver='mpio', comm=MPI.COMM_WORLD) as f: + assert not f.atomic + f.atomic = True + assert f.atomic + + def test_close_multiple_mpio_driver(self, mpi_file_name): + """ MPIO driver and options """ + from mpi4py import MPI + + f = File(mpi_file_name, 'w', driver='mpio', comm=MPI.COMM_WORLD) + f.create_group("test") + f.close() + f.close() + + +class TestSWMRMode(TestCase): + + """ + Feature: Create file that switches on SWMR mode + """ + + def test_file_mode_generalizes(self): + fname = self.mktemp() + fid = File(fname, 'w', libver='latest') + g = fid.create_group('foo') + # fid and group member file attribute should have the same mode + assert fid.mode == g.file.mode == 'r+' + fid.swmr_mode = True + # fid and group member file attribute should still be 'r+' + # even though file intent has changed + assert fid.mode == g.file.mode == 'r+' + fid.close() + + def test_swmr_mode_consistency(self): + fname = self.mktemp() + fid = File(fname, 'w', libver='latest') + g = fid.create_group('foo') + assert fid.swmr_mode == g.file.swmr_mode == False + fid.swmr_mode = True + # This setter should affect both fid and group member file attribute + assert fid.swmr_mode == g.file.swmr_mode == True + fid.close() + + +@pytest.mark.skipif("HDF5_USE_FILE_LOCKING" in os.environ, + reason="HDF5_USE_FILE_LOCKING env. var. is set") +class TestFileLocking: + """Test h5py.File file locking option""" + + def test_reopen(self, tmp_path): + """Test file locking when opening twice the same file""" + fname = tmp_path / "test.h5" + + with h5py.File(fname, mode="w", locking=True) as f: + f.flush() + + # Opening same file in same process without locking is expected to fail + with pytest.raises(OSError): + with h5py.File(fname, mode="r", locking=False) as h5f_read: + pass + + with h5py.File(fname, mode="r", locking=True) as h5f_read: + pass + + if h5py.version.hdf5_version_tuple < (1, 14, 4): + with h5py.File(fname, mode="r", locking='best-effort') as h5f_read: + pass + else: + with pytest.raises(OSError): + with h5py.File(fname, mode="r", locking='best-effort') as h5f_read: + pass + + + def test_unsupported_locking(self, tmp_path): + """Test with erroneous file locking value""" + fname = tmp_path / "test.h5" + with pytest.raises(ValueError): + with h5py.File(fname, mode="r", locking='unsupported-value') as h5f_read: + pass + + def test_multiprocess(self, tmp_path): + """Test file locking option from different concurrent processes""" + fname = tmp_path / "test.h5" + + def open_in_subprocess(filename, mode, locking): + """Open HDF5 file in a subprocess and return True on success""" + h5py_import_dir = str(pathlib.Path(h5py.__file__).parent.parent) + + process = subprocess.run( + [ + sys.executable, + "-c", + f""" +import sys +sys.path.insert(0, {h5py_import_dir!r}) +import h5py +f = h5py.File({str(filename)!r}, mode={mode!r}, locking={locking}) + """, + ], + capture_output=True) + return process.returncode == 0 and not process.stderr + + # Create test file + with h5py.File(fname, mode="w", locking=True) as f: + f["data"] = 1 + + with h5py.File(fname, mode="r", locking=False) as f: + # Opening in write mode with locking is expected to work + assert open_in_subprocess(fname, mode="w", locking=True) + + +@pytest.mark.skipif( + h5py.version.hdf5_version_tuple < (1, 14, 4), + reason="Requires HDF5 >= 1.14.4", +) +@pytest.mark.skipif( + "HDF5_USE_FILE_LOCKING" in os.environ, + reason="HDF5_USE_FILE_LOCKING env. var. is set", +) +@pytest.mark.parametrize( + 'locking_arg,file_locking_props', + [ + (False, (0, 0)), + (True, (1, 0)), + ('best-effort', (1, 1)), + ] +) +def test_file_locking_external_link(tmp_path, locking_arg, file_locking_props): + """Test that same file locking is used for external link""" + fname_main = tmp_path / "test_main.h5" + fname_elink = tmp_path / "test_linked.h5" + + # Create test files + with h5py.File(fname_elink, "w") as f: + f["data"] = 1 + with h5py.File(fname_main, "w") as f: + f["link"] = h5py.ExternalLink(fname_elink, "/data") + + with h5py.File(fname_main, "r", locking=locking_arg) as f: + locking_info = f.id.get_access_plist().get_file_locking() + assert locking_info == file_locking_props + + # Test that external link file is also opened without file locking + elink_dataset = f["link"] + elink_locking_info = elink_dataset.file.id.get_access_plist().get_file_locking() + assert elink_locking_info == file_locking_props + + +def test_close_gc(writable_file): + # https://github.com/h5py/h5py/issues/1852 + for i in range(100): + writable_file[str(i)] = [] + + filename = writable_file.filename + writable_file.close() + + # Ensure that Python's garbage collection doesn't interfere with closing + # a file. Try a few times - the problem is not 100% consistent, but + # normally showed up on the 1st or 2nd iteration for me. -TAK, 2021 + for i in range(10): + with h5py.File(filename, 'r') as f: + refs = [d.id for d in f.values()] + refs.append(refs) # Make a reference cycle so GC is involved + del refs # GC is likely to fire while closing the file + + +@pytest.mark.slow +def test_reproducible_file(tmp_path): + def write(path): + with File(path, 'w', track_order=True) as hf: + g = hf.create_group("group", track_order=True) + g.create_dataset("dset", shape=10, dtype='f4') + + f1 = tmp_path / "f1.h5" + write(f1) + time.sleep(1.1) # Ensure any timestamps are different + f2 = tmp_path / "f2.h5" + write(f2) + + assert sha256(f1.read_bytes()).hexdigest() == sha256(f2.read_bytes()).hexdigest() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_file2.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_file2.py new file mode 100644 index 0000000000000000000000000000000000000000..1c4517fe797d794960bccc20795d40bce088af13 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_file2.py @@ -0,0 +1,333 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Tests the h5py.File object. +""" + +import h5py +from h5py._hl.files import _drivers +from h5py import File + +from .common import ut, TestCase + +import pytest +import io +import tempfile +import os + + +def nfiles(): + return h5py.h5f.get_obj_count(h5py.h5f.OBJ_ALL, h5py.h5f.OBJ_FILE) + +def ngroups(): + return h5py.h5f.get_obj_count(h5py.h5f.OBJ_ALL, h5py.h5f.OBJ_GROUP) + + +class TestDealloc(TestCase): + + """ + Behavior on object deallocation. Note most of this behavior is + delegated to FileID. + """ + + def test_autoclose(self): + """ File objects close automatically when out of scope, but + other objects remain open. """ + + start_nfiles = nfiles() + start_ngroups = ngroups() + + fname = self.mktemp() + f = h5py.File(fname, 'w') + g = f['/'] + + self.assertEqual(nfiles(), start_nfiles+1) + self.assertEqual(ngroups(), start_ngroups+1) + + del f + + self.assertTrue(g) + self.assertEqual(nfiles(), start_nfiles) + self.assertEqual(ngroups(), start_ngroups+1) + + f = g.file + + self.assertTrue(f) + self.assertEqual(nfiles(), start_nfiles+1) + self.assertEqual(ngroups(), start_ngroups+1) + + del g + + self.assertEqual(nfiles(), start_nfiles+1) + self.assertEqual(ngroups(), start_ngroups) + + del f + + self.assertEqual(nfiles(), start_nfiles) + self.assertEqual(ngroups(), start_ngroups) + + +class TestDriverRegistration(TestCase): + def test_register_driver(self): + called_with = [None] + + def set_fapl(plist, *args, **kwargs): + called_with[0] = args, kwargs + return _drivers['sec2'](plist) + + h5py.register_driver('new-driver', set_fapl) + self.assertIn('new-driver', h5py.registered_drivers()) + + fname = self.mktemp() + h5py.File(fname, driver='new-driver', driver_arg_0=0, driver_arg_1=1, + mode='w') + + self.assertEqual( + called_with, + [((), {'driver_arg_0': 0, 'driver_arg_1': 1})], + ) + + def test_unregister_driver(self): + h5py.register_driver('new-driver', lambda plist: None) + self.assertIn('new-driver', h5py.registered_drivers()) + + h5py.unregister_driver('new-driver') + self.assertNotIn('new-driver', h5py.registered_drivers()) + + with self.assertRaises(ValueError) as e: + fname = self.mktemp() + h5py.File(fname, driver='new-driver', mode='w') + + self.assertEqual(str(e.exception), "Unknown driver type 'new-driver'") + + +class TestCache(TestCase): + def setUp(self): + MiB = 1024 * 1024 + if h5py.version.hdf5_version_tuple < (2, 0, 0): + self.dflt_chunk_cache = MiB + else: + self.dflt_chunk_cache = 8 * MiB + + def test_defaults(self): + fname = self.mktemp() + f = h5py.File(fname, 'w') + self.assertEqual(list(f.id.get_access_plist().get_cache()), + [0, 521, self.dflt_chunk_cache, 0.75]) + + def test_nbytes(self): + fname = self.mktemp() + f = h5py.File(fname, 'w', rdcc_nbytes=1024) + self.assertEqual(list(f.id.get_access_plist().get_cache()), + [0, 521, 1024, 0.75]) + + def test_nslots(self): + fname = self.mktemp() + f = h5py.File(fname, 'w', rdcc_nslots=125) + self.assertEqual(list(f.id.get_access_plist().get_cache()), + [0, 125, self.dflt_chunk_cache, 0.75]) + + def test_w0(self): + fname = self.mktemp() + f = h5py.File(fname, 'w', rdcc_w0=0.25) + self.assertEqual(list(f.id.get_access_plist().get_cache()), + [0, 521, self.dflt_chunk_cache, 0.25]) + + +class TestFileObj(TestCase): + + def check_write(self, fileobj): + f = h5py.File(fileobj, 'w') + self.assertEqual(f.driver, 'fileobj') + self.assertEqual(f.filename, repr(fileobj)) + f.create_dataset('test', data=list(range(12))) + self.assertEqual(list(f), ['test']) + self.assertEqual(list(f['test'][:]), list(range(12))) + f.close() + + def check_read(self, fileobj): + f = h5py.File(fileobj, 'r') + self.assertEqual(list(f), ['test']) + self.assertEqual(list(f['test'][:]), list(range(12))) + self.assertRaises(Exception, f.create_dataset, 'another.test', data=list(range(3))) + f.close() + + def test_BytesIO(self): + with io.BytesIO() as fileobj: + self.assertEqual(len(fileobj.getvalue()), 0) + self.check_write(fileobj) + self.assertGreater(len(fileobj.getvalue()), 0) + self.check_read(fileobj) + + def test_file(self): + fname = self.mktemp() + try: + with open(fname, 'wb+') as fileobj: + self.assertEqual(os.path.getsize(fname), 0) + self.check_write(fileobj) + self.assertGreater(os.path.getsize(fname), 0) + self.check_read(fileobj) + with open(fname, 'rb') as fileobj: + self.check_read(fileobj) + finally: + os.remove(fname) + + @pytest.mark.filterwarnings( + # at least on Windows and MacOS, a resource warning may be emitted + # when this test returns + "ignore::ResourceWarning" + ) + def test_TemporaryFile(self): + # in this test, we check explicitly that temp file gets + # automatically deleted upon h5py.File.close()... + fileobj = tempfile.NamedTemporaryFile() + fname = fileobj.name + f = h5py.File(fileobj, 'w') + del fileobj + # ... but in your code feel free to simply + # f = h5py.File(tempfile.TemporaryFile()) + + f.create_dataset('test', data=list(range(12))) + self.assertEqual(list(f), ['test']) + self.assertEqual(list(f['test'][:]), list(range(12))) + self.assertTrue(os.path.isfile(fname)) + f.close() + self.assertFalse(os.path.isfile(fname)) + + def test_exception_open(self): + self.assertRaises(Exception, h5py.File, None, + driver='fileobj', mode='x') + self.assertRaises(Exception, h5py.File, 'rogue', + driver='fileobj', mode='x') + self.assertRaises(Exception, h5py.File, self, + driver='fileobj', mode='x') + + def test_exception_read(self): + + class BrokenBytesIO(io.BytesIO): + def readinto(self, b): + raise Exception('I am broken') + + f = h5py.File(BrokenBytesIO(), 'w') + f.create_dataset('test', data=list(range(12))) + self.assertRaises(Exception, list, f['test']) + + def test_exception_write(self): + + class BrokenBytesIO(io.BytesIO): + allow_write = False + def write(self, b): + if self.allow_write: + return super().write(b) + else: + raise Exception('I am broken') + + bio = BrokenBytesIO() + f = h5py.File(bio, 'w') + try: + self.assertRaises(Exception, f.create_dataset, 'test', + data=list(range(12))) + finally: + # Un-break writing so we can close: errors while closing get messy. + bio.allow_write = True + f.close() + + @ut.skip("Incompletely closed files can cause segfaults") + def test_exception_close(self): + fileobj = io.BytesIO() + f = h5py.File(fileobj, 'w') + fileobj.close() + self.assertRaises(Exception, f.close) + + def test_exception_writeonly(self): + # HDF5 expects read & write access to a file it's writing; + # check that we get the correct exception on a write-only file object. + fileobj = open(os.path.join(self.tempdir, 'a.h5'), 'wb') + f = h5py.File(fileobj, 'w') + group = f.create_group("group") + with self.assertRaises(io.UnsupportedOperation): + group.create_dataset("data", data='foo', dtype=h5py.string_dtype()) + f.close() + fileobj.close() + + + def test_method_vanish(self): + fileobj = io.BytesIO() + f = h5py.File(fileobj, 'w') + f.create_dataset('test', data=list(range(12))) + self.assertEqual(list(f['test'][:]), list(range(12))) + fileobj.readinto = None + self.assertRaises(Exception, list, f['test']) + + +class TestTrackOrder(TestCase): + def populate(self, f): + for i in range(100): + # Mix group and dataset creation. + if i % 10 == 0: + f.create_group(str(i)) + else: + f[str(i)] = [i] + + def test_track_order(self): + fname = self.mktemp() + f = h5py.File(fname, 'w', track_order=True) # creation order + self.populate(f) + self.assertEqual(list(f), [str(i) for i in range(100)]) + f.close() + + # Check order tracking after reopening the file + f2 = h5py.File(fname) + self.assertEqual(list(f2), [str(i) for i in range(100)]) + + def test_no_track_order(self): + fname = self.mktemp() + f = h5py.File(fname, 'w', track_order=False) # name alphanumeric + self.populate(f) + self.assertEqual(list(f), + sorted([str(i) for i in range(100)])) + + +class TestFileMetaBlockSize(TestCase): + + """ + Feature: The meta block size can be manipulated, changing how metadata + is aggregated and the offset of the first dataset. + """ + + def test_file_create_with_meta_block_size_4096(self): + # Test a large meta block size of 4 kibibytes + meta_block_size = 4096 + with File( + self.mktemp(), 'w', + meta_block_size=meta_block_size, + libver="latest" + ) as f: + f["test"] = 5 + self.assertEqual(f.meta_block_size, meta_block_size) + # Equality is expected for HDF5 1.10 + self.assertGreaterEqual(f["test"].id.get_offset(), meta_block_size) + + def test_file_create_with_meta_block_size_512(self): + # Test a small meta block size of 512 bytes + # The smallest verifiable meta_block_size is 463 + meta_block_size = 512 + libver = "latest" + with File( + self.mktemp(), 'w', + meta_block_size=meta_block_size, + libver=libver + ) as f: + f["test"] = 3 + self.assertEqual(f.meta_block_size, meta_block_size) + # Equality is expected for HDF5 1.10 + self.assertGreaterEqual(f["test"].id.get_offset(), meta_block_size) + # Default meta_block_size is 2048. This should fail if meta_block_size is not set. + self.assertLess(f["test"].id.get_offset(), meta_block_size*2) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_file_alignment.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_file_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..da13ee04e43af42bf30c3ceaf758774c408053b7 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_file_alignment.py @@ -0,0 +1,103 @@ +import h5py +from .common import TestCase + + +def is_aligned(dataset, offset=4096): + # Here we check if the dataset is aligned + return dataset.id.get_offset() % offset == 0 + + +def dataset_name(i): + return f"data{i:03}" + + +class TestFileAlignment(TestCase): + """ + Ensure that setting the file alignment has the desired effect + in the internal structure. + """ + def test_no_alignment_set(self): + fname = self.mktemp() + # 881 is a prime number, so hopefully this help randomize the alignment + # enough + # A nice even number might give a pathological case where + # While we don't want the data to be aligned, it ends up aligned... + shape = (881,) + + with h5py.File(fname, 'w') as h5file: + # Create up to 1000 datasets + # At least one of them should be misaligned. + # While this isn't perfect, it seems that there + # The case where 1000 datasets get created is one where the data + # is aligned. Therefore, during correct operation, this test is + # expected to finish quickly + for i in range(1000): + dataset = h5file.create_dataset( + dataset_name(i), shape, dtype='uint8') + # Assign data so that the dataset is instantiated in + # the file + dataset[...] = i + if not is_aligned(dataset): + # Break early asserting that the file is not aligned + break + else: + raise RuntimeError("Data was all found to be aligned to 4096") + + def test_alignment_set_above_threshold(self): + # 2022/01/19 hmaarrfk + # UnitTest (TestCase) doesn't play well with pytest parametrization. + alignment_threshold = 1000 + alignment_interval = 4096 + + for shape in [ + (1033,), # A prime number above the threshold + (1000,), # Exactly equal to the threshold + (1001,), # one above the threshold + ]: + fname = self.mktemp() + with h5py.File(fname, 'w', + alignment_threshold=alignment_threshold, + alignment_interval=alignment_interval) as h5file: + # Create up to 1000 datasets + # They are all expected to be aligned + for i in range(1000): + dataset = h5file.create_dataset( + dataset_name(i), shape, dtype='uint8') + # Assign data so that the dataset is instantiated in + # the file + dataset[...] = (i % 256) # Truncate to uint8 + assert is_aligned(dataset, offset=alignment_interval) + + def test_alignment_set_below_threshold(self): + # 2022/01/19 hmaarrfk + # UnitTest (TestCase) doesn't play well with pytest parametrization. + alignment_threshold = 1000 + alignment_interval = 1024 + + for shape in [ + (881,), # A prime number below the threshold + (999,), # Exactly one below the threshold + ]: + fname = self.mktemp() + with h5py.File(fname, 'w', + alignment_threshold=alignment_threshold, + alignment_interval=alignment_interval) as h5file: + # Create up to 1000 datasets + # At least one of them should be misaligned. + # While this isn't perfect, it seems that there + # The case where 1000 datasets get created is one where the + # data is aligned. Therefore, during correct operation, this + # test is expected to finish quickly + for i in range(1000): + dataset = h5file.create_dataset( + dataset_name(i), shape, dtype='uint8') + # Assign data so that the dataset is instantiated in + # the file + dataset[...] = i + if not is_aligned(dataset, offset=alignment_interval): + # Break early asserting that the file is not aligned + break + else: + raise RuntimeError( + "Data was all found to be aligned to " + f"{alignment_interval}. This is highly unlikely.") diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_file_image.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_file_image.py new file mode 100644 index 0000000000000000000000000000000000000000..3e45b55a3bfcb99ad3bb7c5ee08486c74a9152ad --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_file_image.py @@ -0,0 +1,54 @@ +import numpy as np + +import h5py +from h5py import h5f, h5p + +from .common import TestCase + +class TestFileImage(TestCase): + def test_load_from_image(self): + from binascii import a2b_base64 + from zlib import decompress + + compressed_image = 'eJzr9HBx4+WS4mIAAQ4OBhYGAQZk8B8KKjhQ+TD5BCjNCKU7oPQKJpg4I1hOAiouCDUfXV1IkKsrSPV/NACzx4AFQnMwjIKRCDxcHQNAdASUD0ulJ5hQ1ZWkFpeAaFh69KDQXkYGNohZjDA+JCUzMkIEmKHqELQAWKkAByytOoBJViAPJM7ExATWyAE0B8RgZkyAJmlYDoEAIahukJoNU6+HMTA0UOgT6oBgP38XUI6G5UMFZrzKR8EoGAUjGMDKYVgxDSsuAHcfMK8=' + + image = decompress(a2b_base64(compressed_image)) + + fapl = h5p.create(h5py.h5p.FILE_ACCESS) + fapl.set_fapl_core() + fapl.set_file_image(image) + + fid = h5f.open(self.mktemp().encode(), h5py.h5f.ACC_RDONLY, fapl=fapl) + f = h5py.File(fid) + + self.assertTrue('test' in f) + + def test_open_from_image(self): + from binascii import a2b_base64 + from zlib import decompress + + compressed_image = 'eJzr9HBx4+WS4mIAAQ4OBhYGAQZk8B8KKjhQ+TD5BCjNCKU7oPQKJpg4I1hOAiouCDUfXV1IkKsrSPV/NACzx4AFQnMwjIKRCDxcHQNAdASUD0ulJ5hQ1ZWkFpeAaFh69KDQXkYGNohZjDA+JCUzMkIEmKHqELQAWKkAByytOoBJViAPJM7ExATWyAE0B8RgZkyAJmlYDoEAIahukJoNU6+HMTA0UOgT6oBgP38XUI6G5UMFZrzKR8EoGAUjGMDKYVgxDSsuAHcfMK8=' + + image = decompress(a2b_base64(compressed_image)) + + fid = h5f.open_file_image(image) + f = h5py.File(fid) + + self.assertTrue('test' in f) + + +def test_in_memory(): + arr = np.arange(10) + # Passing one fcpl & one fapl parameter to exercise the code splitting them: + with h5py.File.in_memory(track_order=True, rdcc_nbytes=2_000_000) as f1: + f1['a'] = arr + f1.flush() + img = f1.id.get_file_image() + + # Open while f1 is still open + with h5py.File.in_memory(img) as f2: + np.testing.assert_array_equal(f2['a'][:], arr) + + # Reuse image now that previous files are closed + with h5py.File.in_memory(img) as f3: + np.testing.assert_array_equal(f3['a'][:], arr) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_filters.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..e68b93807a759d595e1b0db9c9ddc0fb12e06610 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_filters.py @@ -0,0 +1,93 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Tests the h5py._hl.filters module. + +""" +import os +import numpy as np +import h5py + +from .common import ut, TestCase + + +class TestFilters(TestCase): + + def setUp(self): + """ like TestCase.setUp but also store the file path """ + self.path = self.mktemp() + self.f = h5py.File(self.path, 'w') + + @ut.skipUnless(h5py.h5z.filter_avail(h5py.h5z.FILTER_SZIP), 'szip filter required') + def test_wr_szip_fletcher32_64bit(self): + """ test combination of szip, fletcher32, and 64bit arrays + + The fletcher32 checksum must be computed after the szip + compression is applied. + + References: + - GitHub issue #953 + - https://forum.hdfgroup.org/t/fletcher32-checksum-error-with-szip-compression-and-64bit-data/4141 + """ + self.f.create_dataset("test_data", + data=np.zeros(10000, dtype=np.float64), + fletcher32=True, + compression="szip", + ) + self.f.close() + + with h5py.File(self.path, "r") as h5: + # Access the data which will compute the fletcher32 + # checksum and raise an OSError if something is wrong. + h5["test_data"][0] + + def test_wr_scaleoffset_fletcher32(self): + """ make sure that scaleoffset + fletcher32 is prevented + """ + data = np.linspace(0, 1, 100) + with self.assertRaises(ValueError): + self.f.create_dataset("test_data", + data=data, + fletcher32=True, + # retain 3 digits after the decimal point + scaleoffset=3, + ) + + +@ut.skipIf('gzip' not in h5py.filters.encode, "DEFLATE is not installed") +def test_filter_ref_obj(writable_file): + gzip8 = h5py.filters.Gzip(level=8) + # **kwargs unpacking (compatible with earlier h5py versions) + assert dict(**gzip8) == { + 'compression': h5py.h5z.FILTER_DEFLATE, + 'compression_opts': (8,) + } + + # Pass object as compression argument (new in h5py 3.0) + ds = writable_file.create_dataset( + 'x', shape=(100,), dtype=np.uint32, compression=gzip8 + ) + assert ds.compression == 'gzip' + assert ds.compression_opts == 8 + + +def test_filter_ref_obj_eq(): + gzip8 = h5py.filters.Gzip(level=8) + + assert gzip8 == h5py.filters.Gzip(level=8) + assert gzip8 != h5py.filters.Gzip(level=7) + + +@ut.skipIf(not os.getenv('H5PY_TEST_CHECK_FILTERS'), "H5PY_TEST_CHECK_FILTERS not set") +def test_filters_available(): + assert 'gzip' in h5py.filters.decode + assert 'gzip' in h5py.filters.encode + assert 'lzf' in h5py.filters.decode + assert 'lzf' in h5py.filters.encode diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_group.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_group.py new file mode 100644 index 0000000000000000000000000000000000000000..a90f59d80d78c0b7eff729eb68ef2f861f65295d --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_group.py @@ -0,0 +1,1226 @@ +# -*- coding: utf-8 -*- +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Group test module. + + Tests all methods and properties of Group objects, with the following + exceptions: + + 1. Method create_dataset is tested in module test_dataset +""" + +import numpy as np +import os +import os.path +from tempfile import mkdtemp + +from collections.abc import MutableMapping + +from .common import ut, TestCase +import h5py +from h5py import File, Group, SoftLink, HardLink, ExternalLink +from h5py import Dataset, Datatype +from h5py import h5t +from h5py._hl.compat import filename_encode + +# If we can't encode unicode filenames, there's not much point failing tests +# which must fail +try: + filename_encode(u"α") +except UnicodeEncodeError: + NO_FS_UNICODE = True +else: + NO_FS_UNICODE = False + + +class BaseGroup(TestCase): + + def setUp(self): + self.f = File(self.mktemp(), 'w') + + def tearDown(self): + if self.f: + self.f.close() + +class TestCreate(BaseGroup): + + """ + Feature: New groups can be created via .create_group method + """ + + def test_create(self): + """ Simple .create_group call """ + grp = self.f.create_group('foo') + self.assertIsInstance(grp, Group) + + grp2 = self.f.create_group(b'bar') + self.assertIsInstance(grp, Group) + + def test_create_intermediate(self): + """ Intermediate groups can be created automatically """ + grp = self.f.create_group('foo/bar/baz') + self.assertEqual(grp.name, '/foo/bar/baz') + + grp2 = self.f.create_group(b'boo/bar/baz') + self.assertEqual(grp2.name, '/boo/bar/baz') + + def test_create_exception(self): + """ Name conflict causes group creation to fail with ValueError """ + self.f.create_group('foo') + with self.assertRaises(ValueError): + self.f.create_group('foo') + + def test_unicode(self): + """ Unicode names are correctly stored """ + name = u"/Name" + chr(0x4500) + group = self.f.create_group(name) + self.assertEqual(group.name, name) + self.assertEqual(group.id.links.get_info(name.encode('utf8')).cset, h5t.CSET_UTF8) + + def test_unicode_default(self): + """ Unicode names convertible to ASCII are stored as ASCII (issue 239) + """ + name = u"/Hello, this is a name" + group = self.f.create_group(name) + self.assertEqual(group.name, name) + self.assertEqual(group.id.links.get_info(name.encode('utf8')).cset, h5t.CSET_ASCII) + + def test_type(self): + """ Names should be strings or bytes """ + with self.assertRaises(TypeError): + self.f.create_group(1.) + + def test_appropriate_low_level_id(self): + " Binding a group to a non-group identifier fails with ValueError " + dset = self.f.create_dataset('foo', [1]) + with self.assertRaises(ValueError): + Group(dset.id) + +class TestDatasetAssignment(BaseGroup): + + """ + Feature: Datasets can be created by direct assignment of data + """ + + def test_ndarray(self): + """ Dataset auto-creation by direct assignment """ + data = np.ones((4,4),dtype='f') + self.f['a'] = data + self.assertIsInstance(self.f['a'], Dataset) + self.assertArrayEqual(self.f['a'][...], data) + + def test_name_bytes(self): + data = np.ones((4, 4), dtype='f') + self.f[b'b'] = data + self.assertIsInstance(self.f[b'b'], Dataset) + +class TestDtypeAssignment(BaseGroup): + + """ + Feature: Named types can be created by direct assignment of dtypes + """ + + def test_dtype(self): + """ Named type creation """ + dtype = np.dtype('|S10') + self.f['a'] = dtype + self.assertIsInstance(self.f['a'], Datatype) + self.assertEqual(self.f['a'].dtype, dtype) + + def test_name_bytes(self): + """ Named type creation """ + dtype = np.dtype('|S10') + self.f[b'b'] = dtype + self.assertIsInstance(self.f[b'b'], Datatype) + + +class TestRequire(BaseGroup): + + """ + Feature: Groups can be auto-created, or opened via .require_group + """ + + def test_open_existing(self): + """ Existing group is opened and returned """ + grp = self.f.create_group('foo') + grp2 = self.f.require_group('foo') + self.assertEqual(grp2, grp) + + grp3 = self.f.require_group(b'foo') + self.assertEqual(grp3, grp) + + def test_create(self): + """ Group is created if it doesn't exist """ + grp = self.f.require_group('foo') + self.assertIsInstance(grp, Group) + self.assertEqual(grp.name, '/foo') + + def test_require_exception(self): + """ Opening conflicting object results in TypeError """ + self.f.create_dataset('foo', (1,), 'f') + with self.assertRaises(TypeError): + self.f.require_group('foo') + + def test_intermediate_create_dataset(self): + """ Intermediate is created if it doesn't exist """ + dt = h5py.string_dtype() + self.f.require_dataset("foo/bar/baz", (1,), dtype=dt) + group = self.f.get('foo') + assert isinstance(group, Group) + group = self.f.get('foo/bar') + assert isinstance(group, Group) + + def test_intermediate_create_group(self): + dt = h5py.string_dtype() + self.f.require_group("foo/bar/baz") + group = self.f.get('foo') + assert isinstance(group, Group) + group = self.f.get('foo/bar') + assert isinstance(group, Group) + group = self.f.get('foo/bar/baz') + assert isinstance(group, Group) + + def test_require_shape(self): + ds = self.f.require_dataset("foo/resizable", shape=(0, 3), maxshape=(None, 3), dtype=int) + ds.resize(20, axis=0) + self.f.require_dataset("foo/resizable", shape=(0, 3), maxshape=(None, 3), dtype=int) + self.f.require_dataset("foo/resizable", shape=(20, 3), dtype=int) + with self.assertRaises(TypeError): + self.f.require_dataset("foo/resizable", shape=(0, 0), maxshape=(3, None), dtype=int) + with self.assertRaises(TypeError): + self.f.require_dataset("foo/resizable", shape=(0, 0), maxshape=(None, 5), dtype=int) + with self.assertRaises(TypeError): + self.f.require_dataset("foo/resizable", shape=(0, 0), maxshape=(None, 5, 2), dtype=int) + with self.assertRaises(TypeError): + self.f.require_dataset("foo/resizable", shape=(10, 3), dtype=int) + + +class TestDelete(BaseGroup): + + """ + Feature: Objects can be unlinked via "del" operator + """ + + def test_delete(self): + """ Object deletion via "del" """ + self.f.create_group('foo') + self.assertIn('foo', self.f) + del self.f['foo'] + self.assertNotIn('foo', self.f) + + def test_nonexisting(self): + """ Deleting non-existent object raises KeyError """ + with self.assertRaises(KeyError): + del self.f['foo'] + + def test_readonly_delete_exception(self): + """ Deleting object in readonly file raises KeyError """ + # Note: it is impossible to restore the old behavior (ValueError) + # without breaking the above test (non-existing objects) + fname = self.mktemp() + hfile = File(fname, 'w') + try: + hfile.create_group('foo') + finally: + hfile.close() + + hfile = File(fname, 'r') + try: + with self.assertRaises(KeyError): + del hfile['foo'] + finally: + hfile.close() + +class TestOpen(BaseGroup): + + """ + Feature: Objects can be opened via indexing syntax obj[name] + """ + + def test_open(self): + """ Simple obj[name] opening """ + grp = self.f.create_group('foo') + grp2 = self.f['foo'] + grp3 = self.f['/foo'] + self.assertEqual(grp, grp2) + self.assertEqual(grp, grp3) + + def test_nonexistent(self): + """ Opening missing objects raises KeyError """ + with self.assertRaises(KeyError): + self.f['foo'] + + def test_reference(self): + """ Objects can be opened by HDF5 object reference """ + grp = self.f.create_group('foo') + grp2 = self.f[grp.ref] + self.assertEqual(grp2, grp) + + def test_reference_numpyobj(self): + """ Object can be opened by numpy.object_ containing object ref + + Test for issue 181, issue 202. + """ + g = self.f.create_group('test') + + dt = np.dtype([('a', 'i'),('b', h5py.ref_dtype)]) + dset = self.f.create_dataset('test_dset', (1,), dt) + + dset[0] =(42,g.ref) + data = dset[0] + self.assertEqual(self.f[data[1]], g) + + def test_invalid_ref(self): + """ Invalid region references should raise an exception """ + + ref = h5py.h5r.Reference() + + with self.assertRaises(ValueError): + self.f[ref] + + self.f.create_group('x') + ref = self.f['x'].ref + del self.f['x'] + + with self.assertRaises(Exception): + self.f[ref] + + def test_path_type_validation(self): + """ Access with non bytes or str types should raise an exception """ + self.f.create_group('group') + + with self.assertRaises(TypeError): + self.f[0] + + with self.assertRaises(TypeError): + self.f[...] + + # TODO: check that regionrefs also work with __getitem__ + +class TestRepr(BaseGroup): + """Opened and closed groups provide a useful __repr__ string""" + + def test_repr(self): + """ Opened and closed groups provide a useful __repr__ string """ + g = self.f.create_group('foo') + self.assertIsInstance(repr(g), str) + g.id._close() + self.assertIsInstance(repr(g), str) + g = self.f['foo'] + # Closing the file shouldn't break it + self.f.close() + self.assertIsInstance(repr(g), str) + +class BaseMapping(BaseGroup): + + """ + Base class for mapping tests + """ + def setUp(self): + self.f = File(self.mktemp(), 'w') + self.groups = ('a', 'b', 'c', 'd') + for x in self.groups: + self.f.create_group(x) + self.f['x'] = h5py.SoftLink('/mongoose') + self.groups = self.groups + ('x',) + + def tearDown(self): + if self.f: + self.f.close() + +class TestLen(BaseMapping): + + """ + Feature: The Python len() function returns the number of groups + """ + + def test_len(self): + """ len() returns number of group members """ + self.assertEqual(len(self.f), len(self.groups)) + self.f.create_group('e') + self.assertEqual(len(self.f), len(self.groups)+1) + + +class TestContains(BaseGroup): + + """ + Feature: The Python "in" builtin tests for membership + """ + + def test_contains(self): + """ "in" builtin works for membership (byte and Unicode) """ + self.f.create_group('a') + self.assertIn(b'a', self.f) + self.assertIn('a', self.f) + self.assertIn(b'/a', self.f) + self.assertIn('/a', self.f) + self.assertNotIn(b'mongoose', self.f) + self.assertNotIn('mongoose', self.f) + + def test_exc(self): + """ "in" on closed group returns False (see also issue 174) """ + self.f.create_group('a') + self.f.close() + self.assertFalse(b'a' in self.f) + self.assertFalse('a' in self.f) + + def test_empty(self): + """ Empty strings work properly and aren't contained """ + self.assertNotIn('', self.f) + self.assertNotIn(b'', self.f) + + def test_dot(self): + """ Current group "." is always contained """ + self.assertIn(b'.', self.f) + self.assertIn('.', self.f) + + def test_root(self): + """ Root group (by itself) is contained """ + self.assertIn(b'/', self.f) + self.assertIn('/', self.f) + + def test_trailing_slash(self): + """ Trailing slashes are unconditionally ignored """ + self.f.create_group('group') + self.f['dataset'] = 42 + self.assertIn('/group/', self.f) + self.assertIn('group/', self.f) + self.assertIn('/dataset/', self.f) + self.assertIn('dataset/', self.f) + + def test_softlinks(self): + """ Broken softlinks are contained, but their members are not """ + self.f.create_group('grp') + self.f['/grp/soft'] = h5py.SoftLink('/mongoose') + self.f['/grp/external'] = h5py.ExternalLink('mongoose.hdf5', '/mongoose') + self.assertIn('/grp/soft', self.f) + self.assertNotIn('/grp/soft/something', self.f) + self.assertIn('/grp/external', self.f) + self.assertNotIn('/grp/external/something', self.f) + + def test_oddball_paths(self): + """ Technically legitimate (but odd-looking) paths """ + self.f.create_group('x/y/z') + self.f['dset'] = 42 + self.assertIn('/', self.f) + self.assertIn('//', self.f) + self.assertIn('///', self.f) + self.assertIn('.///', self.f) + self.assertIn('././/', self.f) + grp = self.f['x'] + self.assertIn('.//x/y/z', self.f) + self.assertNotIn('.//x/y/z', grp) + self.assertIn('x///', self.f) + self.assertIn('./x///', self.f) + self.assertIn('dset///', self.f) + self.assertIn('/dset//', self.f) + +class TestIter(BaseMapping): + + """ + Feature: You can iterate over group members via "for x in y", etc. + """ + + def test_iter(self): + """ "for x in y" iteration """ + lst = [x for x in self.f] + self.assertSameElements(lst, self.groups) + + def test_iter_zero(self): + """ Iteration works properly for the case with no group members """ + hfile = File(self.mktemp(), 'w') + try: + lst = [x for x in hfile] + self.assertEqual(lst, []) + finally: + hfile.close() + +class TestTrackOrder(BaseGroup): + def populate(self, g): + for i in range(100): + # Mix group and dataset creation. + if i % 10 == 0: + g.create_group(str(i)) + else: + g[str(i)] = [i] + + def test_track_order(self): + g = self.f.create_group('order', track_order=True) # creation order + self.populate(g) + + ref = [str(i) for i in range(100)] + self.assertEqual(list(g), ref) + self.assertEqual(list(reversed(g)), list(reversed(ref))) + + def test_no_track_order(self): + g = self.f.create_group('order', track_order=False) # name alphanumeric + self.populate(g) + + ref = sorted([str(i) for i in range(100)]) + self.assertEqual(list(g), ref) + self.assertEqual(list(reversed(g)), list(reversed(ref))) + +class TestPy3Dict(BaseMapping): + + def test_keys(self): + """ .keys provides a key view """ + kv = getattr(self.f, 'keys')() + ref = self.groups + self.assertSameElements(list(kv), ref) + self.assertSameElements(list(reversed(kv)), list(reversed(ref))) + + for x in self.groups: + self.assertIn(x, kv) + self.assertEqual(len(kv), len(self.groups)) + + def test_values(self): + """ .values provides a value view """ + vv = getattr(self.f, 'values')() + ref = [self.f.get(x) for x in self.groups] + self.assertSameElements(list(vv), ref) + self.assertSameElements(list(reversed(vv)), list(reversed(ref))) + + self.assertEqual(len(vv), len(self.groups)) + for x in self.groups: + self.assertIn(self.f.get(x), vv) + + def test_items(self): + """ .items provides an item view """ + iv = getattr(self.f, 'items')() + ref = [(x,self.f.get(x)) for x in self.groups] + self.assertSameElements(list(iv), ref) + self.assertSameElements(list(reversed(iv)), list(reversed(ref))) + + self.assertEqual(len(iv), len(self.groups)) + for x in self.groups: + self.assertIn((x, self.f.get(x)), iv) + +class TestAdditionalMappingFuncs(BaseMapping): + """ + Feature: Other dict methods (pop, pop_item, clear, update, setdefault) are + available. + """ + def setUp(self): + self.f = File(self.mktemp(), 'w') + for x in ('/test/a', '/test/b', '/test/c', '/test/d'): + self.f.create_group(x) + self.group = self.f['test'] + + def tearDown(self): + if self.f: + self.f.close() + + def test_pop_item(self): + """.pop_item exists and removes item""" + key, val = self.group.popitem() + self.assertNotIn(key, self.group) + + def test_pop(self): + """.pop exists and removes specified item""" + self.group.pop('a') + self.assertNotIn('a', self.group) + + def test_pop_default(self): + """.pop falls back to default""" + # e shouldn't exist as a group + value = self.group.pop('e', None) + self.assertEqual(value, None) + + def test_pop_raises(self): + """.pop raises KeyError for non-existence""" + # e shouldn't exist as a group + with self.assertRaises(KeyError): + key = self.group.pop('e') + + def test_clear(self): + """.clear removes groups""" + self.group.clear() + self.assertEqual(len(self.group), 0) + + def test_update_dict(self): + """.update works with dict""" + new_items = {'e': np.array([42])} + self.group.update(new_items) + self.assertIn('e', self.group) + + def test_update_iter(self): + """.update works with list""" + new_items = [ + ('e', np.array([42])), + ('f', np.array([42])) + ] + self.group.update(new_items) + self.assertIn('e', self.group) + + def test_update_kwargs(self): + """.update works with kwargs""" + new_items = {'e': np.array([42])} + self.group.update(**new_items) + self.assertIn('e', self.group) + + def test_setdefault(self): + """.setdefault gets group if it exists""" + value = self.group.setdefault('a') + self.assertEqual(value, self.group.get('a')) + + def test_setdefault_with_default(self): + """.setdefault gets default if group doesn't exist""" + # e shouldn't exist as a group + # 42 used as groups should be strings + value = self.group.setdefault('e', np.array([42])) + self.assertEqual(value, 42) + + def test_setdefault_no_default(self): + """ + .setdefault gets None if group doesn't exist, but as None isn't defined + as data for a dataset, this should raise a TypeError. + """ + # e shouldn't exist as a group + with self.assertRaises(TypeError): + self.group.setdefault('e') + + +class TestGet(BaseGroup): + + """ + Feature: The .get method allows access to objects and metadata + """ + + def test_get_default(self): + """ Object is returned, or default if it doesn't exist """ + default = object() + out = self.f.get('mongoose', default) + self.assertIs(out, default) + + grp = self.f.create_group('a') + out = self.f.get(b'a') + self.assertEqual(out, grp) + + def test_get_class(self): + """ Object class is returned with getclass option """ + self.f.create_group('foo') + out = self.f.get('foo', getclass=True) + self.assertEqual(out, Group) + + self.f.create_dataset('bar', (4,)) + out = self.f.get('bar', getclass=True) + self.assertEqual(out, Dataset) + + self.f['baz'] = np.dtype('|S10') + out = self.f.get('baz', getclass=True) + self.assertEqual(out, Datatype) + + def test_get_link_class(self): + """ Get link classes """ + default = object() + + sl = SoftLink('/mongoose') + el = ExternalLink('somewhere.hdf5', 'mongoose') + + self.f.create_group('hard') + self.f['soft'] = sl + self.f['external'] = el + + out_hl = self.f.get('hard', default, getlink=True, getclass=True) + out_sl = self.f.get('soft', default, getlink=True, getclass=True) + out_el = self.f.get('external', default, getlink=True, getclass=True) + + self.assertEqual(out_hl, HardLink) + self.assertEqual(out_sl, SoftLink) + self.assertEqual(out_el, ExternalLink) + + def test_get_link(self): + """ Get link values """ + sl = SoftLink('/mongoose') + el = ExternalLink('somewhere.hdf5', 'mongoose') + + self.f.create_group('hard') + self.f['soft'] = sl + self.f['external'] = el + + out_hl = self.f.get('hard', getlink=True) + out_sl = self.f.get('soft', getlink=True) + out_el = self.f.get('external', getlink=True) + + #TODO: redo with SoftLink/ExternalLink built-in equality + self.assertIsInstance(out_hl, HardLink) + self.assertIsInstance(out_sl, SoftLink) + self.assertEqual(out_sl._path, sl._path) + self.assertIsInstance(out_el, ExternalLink) + self.assertEqual(out_el._path, el._path) + self.assertEqual(out_el._filename, el._filename) + +class TestVisit(TestCase): + + """ + Feature: The .visit and .visititems methods allow iterative access to + group and subgroup members + """ + + def setUp(self): + self.f = File(self.mktemp(), 'w') + self.groups = [ + 'grp1', 'grp1/sg1', 'grp1/sg2', 'grp2', 'grp2/sg1', 'grp2/sg1/ssg1' + ] + for x in self.groups: + self.f.create_group(x) + + def tearDown(self): + self.f.close() + + def test_visit(self): + """ All subgroups are visited """ + l = [] + self.f.visit(l.append) + self.assertSameElements(l, self.groups) + + def test_visititems(self): + """ All subgroups and contents are visited """ + l = [] + comp = [(x, self.f[x]) for x in self.groups] + self.f.visititems(lambda x, y: l.append((x,y))) + self.assertSameElements(comp, l) + + def test_bailout(self): + """ Returning a non-None value immediately aborts iteration """ + # do not make assumption on iteration order + l = [] + x = self.f.visit(lambda x: l.append(x) or -1) + assert x == -1 and len(l) == 1 and l[0] in self.groups + + l = [] + comp = [(x, self.f[x]) for x in self.groups] + x = self.f.visititems(lambda x, y: l.append((x,y)) or -1) + assert x == -1 and len(l) == 1 and l[0] in comp + +class TestVisitLinks(TestCase): + """ + Feature: The .visit_links and .visititems_links methods allow iterative access to + links contained in the group and its subgroups. + """ + + def setUp(self): + self.f = File(self.mktemp(), 'w') + self.groups = [ + 'grp1', 'grp1/grp11', 'grp1/grp12', 'grp2', 'grp2/grp21', 'grp2/grp21/grp211' + ] + self.links = [ + 'linkto_grp1', 'grp1/linkto_grp11', 'grp1/linkto_grp12', 'linkto_grp2', 'grp2/linkto_grp21', 'grp2/grp21/linkto_grp211' + ] + for g, l in zip(self.groups, self.links, strict=True): + self.f.create_group(g) + self.f[l] = SoftLink(f'/{g}') + + def tearDown(self): + self.f.close() + + def test_visit_links(self): + """ All subgroups and links are visited """ + l = [] + self.f.visit_links(l.append) + self.assertSameElements(l, self.groups + self.links) + + def test_visititems(self): + """ All links are visited """ + l = [] + comp = [(x, type(self.f.get(x, getlink=True))) for x in self.groups + self.links] + self.f.visititems_links(lambda x, y: l.append((x, type(y)))) + self.assertSameElements(comp, l) + + def test_bailout(self): + """ Returning a non-None value immediately aborts iteration """ + # do not make assumption on iteration order + l = [] + x = self.f.visit_links(lambda x: l.append(x) or -1) + assert x == -1 and len(l) == 1 + + l = [] + x = self.f.visititems_links(lambda x, y: l.append((x,y)) or -1) + assert x == -1 and len(l) == 1 + +class Visitor: + """ Class for exercise 'visit' and 'visititems' methods """ + + def __init__(self): + self._names = [] + + def __call__(self, name, obj=None): + self._names.append(name) + + @property + def names(self): + return self._names + +class TestLexicographic(TestCase): + """ Test ascending lexicographic order traversal of the 'visit*' methods. + + This semantics is set by the following default args in + h5py.h5o.visit(..., idx_type=H5_INDEX_NAME, order=H5_ITER_INC, ...) + h5py.h5l.visit(..., idx_type=H5_INDEX_NAME, order=H5_ITER_INC, ...) + """ + + import operator + split_parts = operator.methodcaller('split', '/') + + def setUp(self): + """ Populate example hdf5 file, with track_order=True """ + + self.f = File(self.mktemp(), 'w-', track_order=True) + self.f.create_dataset('b', (10,)) + + grp = self.f.create_group('B', track_order=True) + grp.create_dataset('b', (10,)) + grp.create_dataset('a', (10,)) + + grp = self.f.create_group('z', track_order=True) + grp.create_dataset('b', (10,)) + grp.create_dataset('a', (10,)) + + self.f.create_dataset('a', (10,)) + # note that 'z-' < 'z/...' but traversal order is ['z', 'z/...', 'z-'] + self.f.create_dataset('z-', (10,)) + + # create some links + self.f['A/x'] = self.f['B/b'] + self.f['y'] = self.f['z/a'] + self.f['A$'] = self.f['y'] + self.f['A/B/C'] = self.f['A'] + self.f['A/a'] = self.f['A'] + + # create vistor + self.v = Visitor() + + def test_nontrivial_sort_visit(self): + """check that test example is not trivially sorted""" + self.f.visit(self.v) + assert self.v.names != sorted(self.v.names) + + def test_visit(self): + """check that File.visit iterates in lexicographic order""" + self.f.visit(self.v) + assert self.v.names == sorted(self.v.names, key=self.split_parts) + + def test_visit_links(self): + """check that File.visit_links iterates in lexicographic order""" + self.f.visit_links(self.v) + assert self.v.names == sorted(self.v.names, key=self.split_parts) + + def test_visititems(self): + """check that File.visititems iterates in lexicographic order""" + self.f.visititems(self.v) + assert self.v.names == sorted(self.v.names, key=self.split_parts) + + def test_visititems_links(self): + """check that File.visititems_links iterates in lexicographic order""" + self.f.visititems_links(self.v) + assert self.v.names == sorted(self.v.names, key=self.split_parts) + + def test_visit_group(self): + """check that Group.visit iterates in lexicographic order""" + self.f['A'].visit(self.v) + assert self.v.names == sorted(self.v.names, key=self.split_parts) + +class TestSoftLinks(BaseGroup): + + """ + Feature: Create and manage soft links with the high-level interface + """ + + def test_spath(self): + """ SoftLink path attribute """ + sl = SoftLink('/foo') + self.assertEqual(sl.path, '/foo') + + def test_srepr(self): + """ SoftLink path repr """ + sl = SoftLink('/foo') + self.assertIsInstance(repr(sl), str) + + def test_create(self): + """ Create new soft link by assignment """ + g = self.f.create_group('new') + sl = SoftLink('/new') + self.f['alias'] = sl + g2 = self.f['alias'] + self.assertEqual(g, g2) + + def test_exc(self): + """ Opening dangling soft link results in KeyError """ + self.f['alias'] = SoftLink('new') + with self.assertRaises(KeyError): + self.f['alias'] + +class TestExternalLinks(TestCase): + + """ + Feature: Create and manage external links + """ + + def setUp(self): + self.f = File(self.mktemp(), 'w') + self.ename = self.mktemp() + self.ef = File(self.ename, 'w') + self.ef.create_group('external') + self.ef.close() + + def tearDown(self): + if self.f: + self.f.close() + if self.ef: + self.ef.close() + + def test_epath(self): + """ External link paths attributes """ + el = ExternalLink('foo.hdf5', '/foo') + self.assertEqual(el.filename, 'foo.hdf5') + self.assertEqual(el.path, '/foo') + + def test_erepr(self): + """ External link repr """ + el = ExternalLink('foo.hdf5','/foo') + self.assertIsInstance(repr(el), str) + + def test_create(self): + """ Creating external links """ + self.f['ext'] = ExternalLink(self.ename, '/external') + grp = self.f['ext'] + self.ef = grp.file + self.assertNotEqual(self.ef, self.f) + self.assertEqual(grp.name, '/external') + + def test_exc(self): + """ KeyError raised when attempting to open broken link """ + self.f['ext'] = ExternalLink(self.ename, '/missing') + with self.assertRaises(KeyError): + self.f['ext'] + + # I would prefer OSError but there's no way to fix this as the exception + # class is determined by HDF5. + def test_exc_missingfile(self): + """ KeyError raised when attempting to open missing file """ + self.f['ext'] = ExternalLink('mongoose.hdf5','/foo') + with self.assertRaises(KeyError): + self.f['ext'] + + def test_close_file(self): + """ Files opened by accessing external links can be closed + + Issue 189. + """ + self.f['ext'] = ExternalLink(self.ename, '/') + grp = self.f['ext'] + f2 = grp.file + f2.close() + self.assertFalse(f2) + + @ut.skipIf(NO_FS_UNICODE, "No unicode filename support") + def test_unicode_encode(self): + """ + Check that external links encode unicode filenames properly + Testing issue #732 + """ + ext_filename = os.path.join(mkdtemp(), u"α.hdf5") + with File(ext_filename, "w") as ext_file: + ext_file.create_group('external') + self.f['ext'] = ExternalLink(ext_filename, '/external') + + @ut.skipIf(NO_FS_UNICODE, "No unicode filename support") + def test_unicode_decode(self): + """ + Check that external links decode unicode filenames properly + Testing issue #732 + """ + ext_filename = os.path.join(mkdtemp(), u"α.hdf5") + with File(ext_filename, "w") as ext_file: + ext_file.create_group('external') + ext_file["external"].attrs["ext_attr"] = "test" + self.f['ext'] = ExternalLink(ext_filename, '/external') + self.assertEqual(self.f["ext"].attrs["ext_attr"], "test") + + def test_unicode_hdf5_path(self): + """ + Check that external links handle unicode hdf5 paths properly + Testing issue #333 + """ + ext_filename = os.path.join(mkdtemp(), "external.hdf5") + with File(ext_filename, "w") as ext_file: + ext_file.create_group('α') + ext_file["α"].attrs["ext_attr"] = "test" + self.f['ext'] = ExternalLink(ext_filename, '/α') + self.assertEqual(self.f["ext"].attrs["ext_attr"], "test") + +class TestExtLinkBugs(TestCase): + + """ + Bugs: Specific regressions for external links + """ + + def test_issue_212(self): + """ Issue 212 + + Fails with: + + AttributeError: 'SharedConfig' object has no attribute 'lapl' + """ + def closer(x): + def w(): + try: + if x: + x.close() + except OSError: + pass + return w + orig_name = self.mktemp() + new_name = self.mktemp() + f = File(orig_name, 'w') + self.addCleanup(closer(f)) + f.create_group('a') + f.close() + + g = File(new_name, 'w') + self.addCleanup(closer(g)) + g['link'] = ExternalLink(orig_name, '/') # note root group + g.close() + + h = File(new_name, 'r') + self.addCleanup(closer(h)) + self.assertIsInstance(h['link']['a'], Group) + + +class TestCopy(TestCase): + + def setUp(self): + self.f1 = File(self.mktemp(), 'w') + self.f2 = File(self.mktemp(), 'w') + + def tearDown(self): + if self.f1: + self.f1.close() + if self.f2: + self.f2.close() + + def test_copy_path_to_path(self): + foo = self.f1.create_group('foo') + foo['bar'] = [1,2,3] + + self.f1.copy('foo', 'baz') + baz = self.f1['baz'] + self.assertIsInstance(baz, Group) + self.assertArrayEqual(baz['bar'], np.array([1,2,3])) + + def test_copy_path_to_group(self): + foo = self.f1.create_group('foo') + foo['bar'] = [1,2,3] + baz = self.f1.create_group('baz') + + self.f1.copy('foo', baz) + baz = self.f1['baz'] + self.assertIsInstance(baz, Group) + self.assertArrayEqual(baz['foo/bar'], np.array([1,2,3])) + + self.f1.copy('foo', self.f2['/']) + self.assertIsInstance(self.f2['/foo'], Group) + self.assertArrayEqual(self.f2['foo/bar'], np.array([1,2,3])) + + def test_copy_group_to_path(self): + + foo = self.f1.create_group('foo') + foo['bar'] = [1,2,3] + + self.f1.copy(foo, 'baz') + baz = self.f1['baz'] + self.assertIsInstance(baz, Group) + self.assertArrayEqual(baz['bar'], np.array([1,2,3])) + + self.f2.copy(foo, 'foo') + self.assertIsInstance(self.f2['/foo'], Group) + self.assertArrayEqual(self.f2['foo/bar'], np.array([1,2,3])) + + def test_copy_group_to_group(self): + + foo = self.f1.create_group('foo') + foo['bar'] = [1,2,3] + baz = self.f1.create_group('baz') + + self.f1.copy(foo, baz) + baz = self.f1['baz'] + self.assertIsInstance(baz, Group) + self.assertArrayEqual(baz['foo/bar'], np.array([1,2,3])) + + self.f1.copy(foo, self.f2['/']) + self.assertIsInstance(self.f2['/foo'], Group) + self.assertArrayEqual(self.f2['foo/bar'], np.array([1,2,3])) + + def test_copy_dataset(self): + self.f1['foo'] = [1,2,3] + foo = self.f1['foo'] + grp = self.f1.create_group("grp") + + self.f1.copy(foo, 'bar') + self.assertArrayEqual(self.f1['bar'], np.array([1,2,3])) + + self.f1.copy('foo', 'baz') + self.assertArrayEqual(self.f1['baz'], np.array([1,2,3])) + + self.f1.copy(foo, grp) + self.assertArrayEqual(self.f1['/grp/foo'], np.array([1,2,3])) + + self.f1.copy('foo', self.f2) + self.assertArrayEqual(self.f2['foo'], np.array([1,2,3])) + + self.f2.copy(self.f1['foo'], self.f2, 'bar') + self.assertArrayEqual(self.f2['bar'], np.array([1,2,3])) + + def test_copy_shallow(self): + + foo = self.f1.create_group('foo') + bar = foo.create_group('bar') + foo['qux'] = [1,2,3] + bar['quux'] = [4,5,6] + + self.f1.copy(foo, 'baz', shallow=True) + baz = self.f1['baz'] + self.assertIsInstance(baz, Group) + self.assertIsInstance(baz['bar'], Group) + self.assertEqual(len(baz['bar']), 0) + self.assertArrayEqual(baz['qux'], np.array([1,2,3])) + + self.f2.copy(foo, 'foo', shallow=True) + self.assertIsInstance(self.f2['/foo'], Group) + self.assertIsInstance(self.f2['foo/bar'], Group) + self.assertEqual(len(self.f2['foo/bar']), 0) + self.assertArrayEqual(self.f2['foo/qux'], np.array([1,2,3])) + + def test_copy_without_attributes(self): + + self.f1['foo'] = [1,2,3] + foo = self.f1['foo'] + foo.attrs['bar'] = [4,5,6] + + self.f1.copy(foo, 'baz', without_attrs=True) + self.assertArrayEqual(self.f1['baz'], np.array([1,2,3])) + assert 'bar' not in self.f1['baz'].attrs + + self.f2.copy(foo, 'baz', without_attrs=True) + self.assertArrayEqual(self.f2['baz'], np.array([1,2,3])) + assert 'bar' not in self.f2['baz'].attrs + + def test_copy_soft_links(self): + + self.f1['bar'] = [1, 2, 3] + foo = self.f1.create_group('foo') + foo['baz'] = SoftLink('/bar') + + self.f1.copy(foo, 'qux', expand_soft=True) + self.f2.copy(foo, 'foo', expand_soft=True) + del self.f1['bar'] + + self.assertIsInstance(self.f1['qux'], Group) + self.assertArrayEqual(self.f1['qux/baz'], np.array([1, 2, 3])) + + self.assertIsInstance(self.f2['/foo'], Group) + self.assertArrayEqual(self.f2['foo/baz'], np.array([1, 2, 3])) + + def test_copy_external_links(self): + + filename = self.f1.filename + self.f1['foo'] = [1,2,3] + self.f2['bar'] = ExternalLink(filename, 'foo') + self.f1.close() + self.f1 = None + + self.assertArrayEqual(self.f2['bar'], np.array([1,2,3])) + + self.f2.copy('bar', 'baz', expand_external=True) + os.unlink(filename) + self.assertArrayEqual(self.f2['baz'], np.array([1,2,3])) + + def test_copy_refs(self): + + self.f1['foo'] = [1,2,3] + self.f1['bar'] = [4,5,6] + foo = self.f1['foo'] + bar = self.f1['bar'] + foo.attrs['bar'] = bar.ref + + self.f1.copy(foo, 'baz', expand_refs=True) + self.assertArrayEqual(self.f1['baz'], np.array([1,2,3])) + baz_bar = self.f1['baz'].attrs['bar'] + self.assertArrayEqual(self.f1[baz_bar], np.array([4,5,6])) + # The reference points to a copy of bar, not to bar itself. + self.assertNotEqual(self.f1[baz_bar].name, bar.name) + + self.f1.copy('foo', self.f2, 'baz', expand_refs=True) + self.assertArrayEqual(self.f2['baz'], np.array([1,2,3])) + baz_bar = self.f2['baz'].attrs['bar'] + self.assertArrayEqual(self.f2[baz_bar], np.array([4,5,6])) + + self.f1.copy('/', self.f2, 'root', expand_refs=True) + self.assertArrayEqual(self.f2['root/foo'], np.array([1,2,3])) + self.assertArrayEqual(self.f2['root/bar'], np.array([4,5,6])) + foo_bar = self.f2['root/foo'].attrs['bar'] + self.assertArrayEqual(self.f2[foo_bar], np.array([4,5,6])) + # There's only one copy of bar, which the reference points to. + self.assertEqual(self.f2[foo_bar], self.f2['root/bar']) + + +class TestMove(BaseGroup): + + """ + Feature: Group.move moves links in a file + """ + + def test_move_hardlink(self): + """ Moving an object """ + grp = self.f.create_group("X") + self.f.move("X", "Y") + self.assertEqual(self.f["Y"], grp) + self.f.move("Y", "new/nested/path") + self.assertEqual(self.f['new/nested/path'], grp) + + def test_move_softlink(self): + """ Moving a soft link """ + self.f['soft'] = h5py.SoftLink("relative/path") + self.f.move('soft', 'new_soft') + lnk = self.f.get('new_soft', getlink=True) + self.assertEqual(lnk.path, "relative/path") + + def test_move_conflict(self): + """ Move conflict raises ValueError """ + self.f.create_group("X") + self.f.create_group("Y") + with self.assertRaises(ValueError): + self.f.move("X", "Y") + + def test_short_circuit(self): + ''' Test that a null-move works ''' + self.f.create_group("X") + self.f.move("X", "X") + + +class TestMutableMapping(BaseGroup): + '''Tests if the registration of Group as a MutableMapping + behaves as expected + ''' + def test_resolution(self): + assert issubclass(Group, MutableMapping) + grp = self.f.create_group("K") + assert isinstance(grp, MutableMapping) + + def test_validity(self): + ''' + Test that the required functions are implemented. + ''' + Group.__getitem__ + Group.__setitem__ + Group.__delitem__ + Group.__iter__ + Group.__len__ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5.py new file mode 100644 index 0000000000000000000000000000000000000000..64b17a08a95089260bd204dbbd8171cb4e96badd --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5.py @@ -0,0 +1,45 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +from h5py import h5 + +from .common import TestCase + +def fixnames(): + cfg = h5.get_config() + cfg.complex_names = ('r','i') + +class TestH5(TestCase): + + def test_config(self): + cfg = h5.get_config() + self.assertIsInstance(cfg, h5.H5PYConfig) + cfg2 = h5.get_config() + self.assertIs(cfg, cfg2) + + def test_cnames_get(self): + cfg = h5.get_config() + self.assertEqual(cfg.complex_names, ('r','i')) + + def test_cnames_set(self): + self.addCleanup(fixnames) + cfg = h5.get_config() + cfg.complex_names = ('q','x') + self.assertEqual(cfg.complex_names, ('q','x')) + + def test_cnames_set_exc(self): + self.addCleanup(fixnames) + cfg = h5.get_config() + with self.assertRaises(TypeError): + cfg.complex_names = ('q','i','v') + self.assertEqual(cfg.complex_names, ('r','i')) + + def test_repr(self): + cfg = h5.get_config() + repr(cfg) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5d_direct_chunk.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5d_direct_chunk.py new file mode 100644 index 0000000000000000000000000000000000000000..5bcf5584c569d7e468d3f95bc262ab6be1ea7117 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5d_direct_chunk.py @@ -0,0 +1,184 @@ +import h5py +import numpy +import numpy.testing +import pytest + +from .common import ut, TestCase + + +class TestWriteDirectChunk(TestCase): + def test_write_direct_chunk(self): + + filename = self.mktemp().encode() + with h5py.File(filename, "w") as filehandle: + + dataset = filehandle.create_dataset("data", (100, 100, 100), + maxshape=(None, 100, 100), + chunks=(1, 100, 100), + dtype='float32') + + # writing + array = numpy.zeros((10, 100, 100)) + for index in range(10): + a = numpy.random.rand(100, 100).astype('float32') + dataset.id.write_direct_chunk((index, 0, 0), a.tobytes(), filter_mask=1) + array[index] = a + + + # checking + with h5py.File(filename, "r") as filehandle: + for i in range(10): + read_data = filehandle["data"][i] + numpy.testing.assert_array_equal(array[i], read_data) + + +@ut.skipIf('gzip' not in h5py.filters.encode, "DEFLATE is not installed") +class TestReadDirectChunk(TestCase): + def test_read_compressed_offsets(self): + + filename = self.mktemp().encode() + with h5py.File(filename, "w") as filehandle: + + frame = numpy.arange(16).reshape(4, 4) + frame_dataset = filehandle.create_dataset("frame", + data=frame, + compression="gzip", + compression_opts=9) + dataset = filehandle.create_dataset("compressed_chunked", + data=[frame, frame, frame], + compression="gzip", + compression_opts=9, + chunks=(1, ) + frame.shape) + filter_mask, compressed_frame = frame_dataset.id.read_direct_chunk((0, 0)) + # No filter must be disabled + self.assertEqual(filter_mask, 0) + + for i in range(dataset.shape[0]): + filter_mask, data = dataset.id.read_direct_chunk((i, 0, 0)) + self.assertEqual(compressed_frame, data) + # No filter must be disabled + self.assertEqual(filter_mask, 0) + + def test_read_uncompressed_offsets(self): + + filename = self.mktemp().encode() + frame = numpy.arange(16).reshape(4, 4) + with h5py.File(filename, "w") as filehandle: + dataset = filehandle.create_dataset("frame", + maxshape=(1,) + frame.shape, + shape=(1,) + frame.shape, + compression="gzip", + compression_opts=9) + # Write uncompressed data + DISABLE_ALL_FILTERS = 0xFFFFFFFF + dataset.id.write_direct_chunk((0, 0, 0), frame.tobytes(), filter_mask=DISABLE_ALL_FILTERS) + + # FIXME: Here we have to close the file and load it back else + # a runtime error occurs: + # RuntimeError: Can't get storage size of chunk (chunk storage is not allocated) + with h5py.File(filename, "r") as filehandle: + dataset = filehandle["frame"] + filter_mask, compressed_frame = dataset.id.read_direct_chunk((0, 0, 0)) + + # At least 1 filter is supposed to be disabled + self.assertNotEqual(filter_mask, 0) + self.assertEqual(compressed_frame, frame.tobytes()) + + def test_read_write_chunk(self): + + filename = self.mktemp().encode() + with h5py.File(filename, "w") as filehandle: + + # create a reference + frame = numpy.arange(16).reshape(4, 4) + frame_dataset = filehandle.create_dataset("source", + data=frame, + compression="gzip", + compression_opts=9) + # configure an empty dataset + filter_mask, compressed_frame = frame_dataset.id.read_direct_chunk((0, 0)) + dataset = filehandle.create_dataset("created", + shape=frame_dataset.shape, + maxshape=frame_dataset.shape, + chunks=frame_dataset.chunks, + dtype=frame_dataset.dtype, + compression="gzip", + compression_opts=9) + + # copy the data + dataset.id.write_direct_chunk((0, 0), compressed_frame, filter_mask=filter_mask) + + # checking + with h5py.File(filename, "r") as filehandle: + dataset = filehandle["created"][...] + numpy.testing.assert_array_equal(dataset, frame) + + +class TestReadDirectChunkToOut: + + def test_uncompressed_data(self, writable_file): + ref_data = numpy.arange(16).reshape(4, 4) + dataset = writable_file.create_dataset( + "uncompressed", data=ref_data, chunks=ref_data.shape) + + out = bytearray(ref_data.nbytes) + filter_mask, chunk = dataset.id.read_direct_chunk((0, 0), out=out) + + assert numpy.array_equal( + numpy.frombuffer(out, dtype=ref_data.dtype).reshape(ref_data.shape), + ref_data, + ) + assert filter_mask == 0 + assert len(chunk) == ref_data.nbytes + + @pytest.mark.skipif( + 'gzip' not in h5py.filters.encode, + reason="DEFLATE is not installed", + ) + def test_compressed_data(self, writable_file): + ref_data = numpy.arange(16).reshape(4, 4) + dataset = writable_file.create_dataset( + "gzip", + data=ref_data, + chunks=ref_data.shape, + compression="gzip", + compression_opts=9, + ) + chunk_info = dataset.id.get_chunk_info(0) + + out = bytearray(chunk_info.size) + filter_mask, chunk = dataset.id.read_direct_chunk( + chunk_info.chunk_offset, + out=out, + ) + assert filter_mask == chunk_info.filter_mask + assert len(chunk) == chunk_info.size + assert out == dataset.id.read_direct_chunk(chunk_info.chunk_offset)[1] + + def test_fail_buffer_too_small(self, writable_file): + ref_data = numpy.arange(16).reshape(4, 4) + dataset = writable_file.create_dataset( + "uncompressed", data=ref_data, chunks=ref_data.shape) + + out = bytearray(ref_data.nbytes // 2) + with pytest.raises(ValueError): + dataset.id.read_direct_chunk((0, 0), out=out) + + def test_fail_buffer_readonly(self, writable_file): + ref_data = numpy.arange(16).reshape(4, 4) + dataset = writable_file.create_dataset( + "uncompressed", data=ref_data, chunks=ref_data.shape) + + out = bytes(ref_data.nbytes) + with pytest.raises(BufferError): + dataset.id.read_direct_chunk((0, 0), out=out) + + def test_fail_buffer_not_contiguous(self, writable_file): + ref_data = numpy.arange(16).reshape(4, 4) + dataset = writable_file.create_dataset( + "uncompressed", data=ref_data, chunks=ref_data.shape) + + array = numpy.empty(ref_data.shape + (2,), dtype=ref_data.dtype) + out = array[:, :, ::2] # Array is not contiguous + with pytest.raises(ValueError): + dataset.id.read_direct_chunk((0, 0), out=out) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5f.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5f.py new file mode 100644 index 0000000000000000000000000000000000000000..9d402d0facf19f5124bd8076ed676d5eed91ab31 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5f.py @@ -0,0 +1,108 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +import tempfile +import shutil +import os +import numpy as np +from h5py import File, special_dtype +from h5py._hl.files import direct_vfd + +from .common import ut, TestCase + + +class TestFileID(TestCase): + def test_descriptor_core(self): + with File('TestFileID.test_descriptor_core', driver='core', + backing_store=False, mode='x') as f: + assert isinstance(f.id.get_vfd_handle(), int) + + def test_descriptor_sec2(self): + dn_tmp = tempfile.mkdtemp('h5py.lowtest.test_h5f.TestFileID.test_descriptor_sec2') + fn_h5 = os.path.join(dn_tmp, 'test.h5') + try: + with File(fn_h5, driver='sec2', mode='x') as f: + descriptor = f.id.get_vfd_handle() + self.assertNotEqual(descriptor, 0) + os.fsync(descriptor) + finally: + shutil.rmtree(dn_tmp) + + @ut.skipUnless(direct_vfd, + "DIRECT driver is supported on Linux if hdf5 is " + "built with the appriorate flags.") + def test_descriptor_direct(self): + dn_tmp = tempfile.mkdtemp('h5py.lowtest.test_h5f.TestFileID.test_descriptor_direct') + fn_h5 = os.path.join(dn_tmp, 'test.h5') + try: + with File(fn_h5, driver='direct', mode='x') as f: + descriptor = f.id.get_vfd_handle() + self.assertNotEqual(descriptor, 0) + os.fsync(descriptor) + finally: + shutil.rmtree(dn_tmp) + + +class TestCacheConfig(TestCase): + def test_simple_gets(self): + dn_tmp = tempfile.mkdtemp('h5py.lowtest.test_h5f.TestFileID.TestCacheConfig.test_simple_gets') + fn_h5 = os.path.join(dn_tmp, 'test.h5') + try: + with File(fn_h5, mode='x') as f: + hit_rate = f._id.get_mdc_hit_rate() + mdc_size = f._id.get_mdc_size() + + finally: + shutil.rmtree(dn_tmp) + + def test_hitrate_reset(self): + dn_tmp = tempfile.mkdtemp('h5py.lowtest.test_h5f.TestFileID.TestCacheConfig.test_hitrate_reset') + fn_h5 = os.path.join(dn_tmp, 'test.h5') + try: + with File(fn_h5, mode='x') as f: + hit_rate = f._id.get_mdc_hit_rate() + f._id.reset_mdc_hit_rate_stats() + hit_rate = f._id.get_mdc_hit_rate() + assert hit_rate == 0 + + finally: + shutil.rmtree(dn_tmp) + + def test_mdc_config_get(self): + dn_tmp = tempfile.mkdtemp('h5py.lowtest.test_h5f.TestFileID.TestCacheConfig.test_mdc_config_get') + fn_h5 = os.path.join(dn_tmp, 'test.h5') + try: + with File(fn_h5, mode='x') as f: + conf = f._id.get_mdc_config() + f._id.set_mdc_config(conf) + finally: + shutil.rmtree(dn_tmp) + + +class TestVlenData(TestCase): + def test_vlen_strings(self): + # Create file with dataset containing vlen arrays of vlen strings + dn_tmp = tempfile.mkdtemp('h5py.lowtest.test_h5f.TestVlenStrings.test_vlen_strings') + fn_h5 = os.path.join(dn_tmp, 'test.h5') + try: + with File(fn_h5, mode='w') as h: + vlen_str = special_dtype(vlen=str) + vlen_vlen_str = special_dtype(vlen=vlen_str) + + ds = h.create_dataset('/com', (2,), dtype=vlen_vlen_str) + ds[0] = (np.array(["a", "b", "c"], dtype=vlen_vlen_str)) + ds[1] = (np.array(["d", "e", "f","g"], dtype=vlen_vlen_str)) + + with File(fn_h5, "r") as h: + ds = h["com"] + assert ds[0].tolist() == [b'a', b'b', b'c'] + assert ds[1].tolist() == [b'd', b'e', b'f', b'g'] + + finally: + shutil.rmtree(dn_tmp) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5o.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5o.py new file mode 100644 index 0000000000000000000000000000000000000000..26c44f6106e8fd8997564eca1a05a5866e587bb9 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5o.py @@ -0,0 +1,21 @@ +import pytest + +from .common import TestCase +from h5py import File + + +class SampleException(Exception): + pass + +def throwing(name, obj): + print(name, obj) + raise SampleException("throwing exception") + +class TestVisit(TestCase): + def test_visit(self): + fname = self.mktemp() + fid = File(fname, 'w') + fid.create_dataset('foo', (100,), dtype='uint8') + with pytest.raises(SampleException, match='throwing exception'): + fid.visititems(throwing) + fid.close() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5p.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5p.py new file mode 100644 index 0000000000000000000000000000000000000000..dc8560b945ada1cd0d80f9d597764fe3291f3523 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5p.py @@ -0,0 +1,233 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +import unittest as ut + +from h5py import h5p, h5f, version + +from .common import TestCase + + +class TestLibver(TestCase): + + """ + Feature: Setting/getting lib ver bounds + """ + + def test_libver(self): + """ Test libver bounds set/get """ + plist = h5p.create(h5p.FILE_ACCESS) + plist.set_libver_bounds(h5f.LIBVER_EARLIEST, h5f.LIBVER_LATEST) + self.assertEqual((h5f.LIBVER_EARLIEST, h5f.LIBVER_LATEST), + plist.get_libver_bounds()) + + def test_libver_v18(self): + """ Test libver bounds set/get for H5F_LIBVER_V18""" + plist = h5p.create(h5p.FILE_ACCESS) + plist.set_libver_bounds(h5f.LIBVER_EARLIEST, h5f.LIBVER_V18) + self.assertEqual((h5f.LIBVER_EARLIEST, h5f.LIBVER_V18), + plist.get_libver_bounds()) + + def test_libver_v110(self): + """ Test libver bounds set/get for H5F_LIBVER_V110""" + plist = h5p.create(h5p.FILE_ACCESS) + plist.set_libver_bounds(h5f.LIBVER_V18, h5f.LIBVER_V110) + self.assertEqual((h5f.LIBVER_V18, h5f.LIBVER_V110), + plist.get_libver_bounds()) + + @ut.skipIf(version.hdf5_version_tuple < (1, 11, 4), + 'Requires HDF5 1.11.4 or later') + def test_libver_v112(self): + """ Test libver bounds set/get for H5F_LIBVER_V112""" + plist = h5p.create(h5p.FILE_ACCESS) + plist.set_libver_bounds(h5f.LIBVER_V18, h5f.LIBVER_V112) + self.assertEqual((h5f.LIBVER_V18, h5f.LIBVER_V112), + plist.get_libver_bounds()) + + @ut.skipIf(version.hdf5_version_tuple < (1, 14, 0), + 'Requires HDF5 1.14 or later') + def test_libver_v114(self): + """ Test libver bounds set/get for H5F_LIBVER_V114""" + plist = h5p.create(h5p.FILE_ACCESS) + plist.set_libver_bounds(h5f.LIBVER_V18, h5f.LIBVER_V114) + self.assertEqual((h5f.LIBVER_V18, h5f.LIBVER_V114), + plist.get_libver_bounds()) + + @ut.skipIf(version.hdf5_version_tuple < (2, 0, 0), + 'Requires HDF5 2.0 or later') + def test_libver_v200(self): + """ Test libver bounds set/get for H5F_LIBVER_V200""" + plist = h5p.create(h5p.FILE_ACCESS) + plist.set_libver_bounds(h5f.LIBVER_V18, h5f.LIBVER_V200) + self.assertEqual((h5f.LIBVER_V18, h5f.LIBVER_V200), + plist.get_libver_bounds()) + + +class TestDA(TestCase): + ''' + Feature: setting/getting chunk cache size on a dataset access property list + ''' + def test_chunk_cache(self): + '''test get/set chunk cache ''' + dalist = h5p.create(h5p.DATASET_ACCESS) + nslots = 10000 # 40kb hash table + nbytes = 1000000 # 1MB cache size + w0 = .5 # even blend of eviction strategy + + dalist.set_chunk_cache(nslots, nbytes, w0) + self.assertEqual((nslots, nbytes, w0), + dalist.get_chunk_cache()) + + def test_efile_prefix(self): + '''test get/set efile prefix ''' + dalist = h5p.create(h5p.DATASET_ACCESS) + self.assertEqual(dalist.get_efile_prefix().decode(), '') + + efile_prefix = "path/to/external/dataset" + dalist.set_efile_prefix(efile_prefix.encode('utf-8')) + self.assertEqual(dalist.get_efile_prefix().decode(), + efile_prefix) + + efile_prefix = "${ORIGIN}" + dalist.set_efile_prefix(efile_prefix.encode('utf-8')) + self.assertEqual(dalist.get_efile_prefix().decode(), + efile_prefix) + + def test_virtual_prefix(self): + '''test get/set virtual prefix ''' + dalist = h5p.create(h5p.DATASET_ACCESS) + self.assertEqual(dalist.get_virtual_prefix().decode(), '') + + virtual_prefix = "path/to/virtual/dataset" + dalist.set_virtual_prefix(virtual_prefix.encode('utf-8')) + self.assertEqual(dalist.get_virtual_prefix().decode(), + virtual_prefix) + + +class TestFA(TestCase): + ''' + Feature: setting/getting mdc config on a file access property list + ''' + def test_mdc_config(self): + '''test get/set mdc config ''' + falist = h5p.create(h5p.FILE_ACCESS) + + config = falist.get_mdc_config() + falist.set_mdc_config(config) + + def test_set_alignment(self): + '''test get/set chunk cache ''' + falist = h5p.create(h5p.FILE_ACCESS) + threshold = 10 * 1024 # threshold of 10kiB + alignment = 1024 * 1024 # threshold of 1kiB + + falist.set_alignment(threshold, alignment) + self.assertEqual((threshold, alignment), + falist.get_alignment()) + + def test_set_file_locking(self): + '''test get/set file locking''' + falist = h5p.create(h5p.FILE_ACCESS) + use_file_locking = False + ignore_when_disabled = False + + falist.set_file_locking(use_file_locking, ignore_when_disabled) + self.assertEqual((use_file_locking, ignore_when_disabled), + falist.get_file_locking()) + + +class TestPL(TestCase): + def test_obj_track_times(self): + """ + tests if the object track times set/get + """ + # test for groups + gcid = h5p.create(h5p.GROUP_CREATE) + gcid.set_obj_track_times(False) + self.assertEqual(False, gcid.get_obj_track_times()) + + gcid.set_obj_track_times(True) + self.assertEqual(True, gcid.get_obj_track_times()) + # test for datasets + dcid = h5p.create(h5p.DATASET_CREATE) + dcid.set_obj_track_times(False) + self.assertEqual(False, dcid.get_obj_track_times()) + + dcid.set_obj_track_times(True) + self.assertEqual(True, dcid.get_obj_track_times()) + + # test for generic objects + ocid = h5p.create(h5p.OBJECT_CREATE) + ocid.set_obj_track_times(False) + self.assertEqual(False, ocid.get_obj_track_times()) + + ocid.set_obj_track_times(True) + self.assertEqual(True, ocid.get_obj_track_times()) + + def test_link_creation_tracking(self): + """ + tests the link creation order set/get + """ + + gcid = h5p.create(h5p.GROUP_CREATE) + gcid.set_link_creation_order(0) + self.assertEqual(0, gcid.get_link_creation_order()) + + flags = h5p.CRT_ORDER_TRACKED | h5p.CRT_ORDER_INDEXED + gcid.set_link_creation_order(flags) + self.assertEqual(flags, gcid.get_link_creation_order()) + + # test for file creation + fcpl = h5p.create(h5p.FILE_CREATE) + fcpl.set_link_creation_order(flags) + self.assertEqual(flags, fcpl.get_link_creation_order()) + + def test_attr_phase_change(self): + """ + test the attribute phase change + """ + + cid = h5p.create(h5p.OBJECT_CREATE) + # test default value + ret = cid.get_attr_phase_change() + self.assertEqual((8,6), ret) + + # max_compact must < 65536 (64kb) + with self.assertRaises(ValueError): + cid.set_attr_phase_change(65536, 6) + + # Using dense attributes storage to avoid 64kb size limitation + # for a single attribute in compact attribute storage. + cid.set_attr_phase_change(0, 0) + self.assertEqual((0,0), cid.get_attr_phase_change()) + + +def test_proplaid(): + """Test Link Access Property List""" + lapl = h5p.create(h5p.LINK_ACCESS) + + nlinks = 3 + lapl.set_nlinks(nlinks) + assert lapl.get_nlinks() == nlinks + + prefix = b"/prefix" + lapl.set_elink_prefix(prefix) + assert lapl.get_elink_prefix() == prefix + + flags = h5f.ACC_RDWR & h5f.ACC_SWMR_WRITE + lapl.set_elink_acc_flags(flags) + assert lapl.get_elink_acc_flags() == flags + + fapl = h5p.create(h5p.FILE_ACCESS) + fapl.set_file_locking(False, False) + lapl.set_elink_fapl(fapl) + assert lapl.get_elink_fapl().get_file_locking() == (False, False) + + fapl.close() + lapl.close() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5pl.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5pl.py new file mode 100644 index 0000000000000000000000000000000000000000..6f60a325496b0426c36d24dadf12ace7d67ff088 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5pl.py @@ -0,0 +1,68 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2019 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +import pytest + +from h5py import h5pl +from h5py.tests.common import insubprocess, subproc_env + + +@pytest.mark.mpi_skip +@insubprocess +@subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) +def test_default(request): + assert h5pl.size() == 1 + assert h5pl.get(0) == b'h5py_plugin_test' + + +@pytest.mark.mpi_skip +@insubprocess +@subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) +def test_append(request): + h5pl.append(b'/opt/hdf5/vendor-plugin') + assert h5pl.size() == 2 + assert h5pl.get(0) == b'h5py_plugin_test' + assert h5pl.get(1) == b'/opt/hdf5/vendor-plugin' + + +@pytest.mark.mpi_skip +@insubprocess +@subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) +def test_prepend(request): + h5pl.prepend(b'/opt/hdf5/vendor-plugin') + assert h5pl.size() == 2 + assert h5pl.get(0) == b'/opt/hdf5/vendor-plugin' + assert h5pl.get(1) == b'h5py_plugin_test' + + +@pytest.mark.mpi_skip +@insubprocess +@subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) +def test_insert(request): + h5pl.insert(b'/opt/hdf5/vendor-plugin', 0) + assert h5pl.size() == 2 + assert h5pl.get(0) == b'/opt/hdf5/vendor-plugin' + assert h5pl.get(1) == b'h5py_plugin_test' + + +@pytest.mark.mpi_skip +@insubprocess +@subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) +def test_replace(request): + h5pl.replace(b'/opt/hdf5/vendor-plugin', 0) + assert h5pl.size() == 1 + assert h5pl.get(0) == b'/opt/hdf5/vendor-plugin' + + +@pytest.mark.mpi_skip +@insubprocess +@subproc_env({'HDF5_PLUGIN_PATH': 'h5py_plugin_test'}) +def test_remove(request): + h5pl.remove(0) + assert h5pl.size() == 0 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5s.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5s.py new file mode 100644 index 0000000000000000000000000000000000000000..a8c19fc74fcc985329686ecf1454e685759ea181 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5s.py @@ -0,0 +1,24 @@ + +from h5py import h5s +from h5py._selector import Selector + +class Helper: + def __init__(self, shape: tuple): + self.shape = shape + + def __getitem__(self, item) -> h5s.SpaceID: + if not isinstance(item, tuple): + item = (item,) + space = h5s.create_simple(self.shape) + sel = Selector(space) + sel.make_selection(item) + return space + + +def test_same_shape(): + s1 = Helper((5, 6))[:3, :4] + s2 = Helper((5, 6))[2:, 2:] + assert s1.select_shape_same(s2) + + s3 = Helper((5, 6))[:4, :3] + assert not s1.select_shape_same(s3) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5t.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5t.py new file mode 100644 index 0000000000000000000000000000000000000000..b3175d8d8b7ea8a4ba8ddafc1369d89d88635ce8 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_h5t.py @@ -0,0 +1,188 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +import numpy as np + +import h5py +from h5py import h5t + +from .common import TestCase, ut + + +class TestCompound(ut.TestCase): + + """ + Feature: Compound types can be created from Python dtypes + """ + + def test_ref(self): + """ Reference types are correctly stored in compound types (issue 144) + """ + dt = np.dtype([('a', h5py.ref_dtype), ('b', '= 2 +pytestmark = pytest.mark.skipif(not NUMPY_GE2, reason="requires numpy >=2.0") + + +def test_create_with_dtype_T(writable_file): + ds = writable_file.create_dataset("x", shape=(2, 2), dtype="T") + data = [["foo", "bar"], ["hello world", ""]] + ds[:] = data + a = ds.asstr()[:] + np.testing.assert_array_equal(a, data) + + ds = writable_file["x"] + assert ds.dtype == object + np.testing.assert_array_equal(ds.asstr()[:], data) + + ds[0, 0] = "baz" + data[0][0] = "baz" + a = ds.astype("T")[:] + assert a.dtype.kind == "T" + np.testing.assert_array_equal(a, data) + + ds[0, 0] = np.asarray("123", dtype="O") + data[0][0] = "123" + np.testing.assert_array_equal(ds.asstr()[:], data) + + +def test_fromdata(writable_file): + data = [["foo", "bar"]] + np_data = np.asarray(data, dtype="T") + x = writable_file.create_dataset("x", data=data, dtype="T") + y = writable_file.create_dataset("y", data=data, dtype=np.dtypes.StringDType()) + z = writable_file.create_dataset("z", data=np_data) + + for ds in (x, y, z): + assert ds.dtype.kind == "O" + np.testing.assert_array_equal(ds.astype("T")[:], np_data) + for name in ("x", "y", "z"): + ds = writable_file[name] + assert ds.dtype == object + np.testing.assert_array_equal(ds.asstr()[:], data) + ds = ds.astype("T") + assert ds.dtype.kind == "T" + a = ds[:] + assert a.dtype.kind == "T" + np.testing.assert_array_equal(a, data) + + +def test_fixed_to_variable_width(writable_file): + data = ["foo", "longer than 8 bytes"] + x = writable_file.create_dataset( + "x", data=data, dtype=h5py.string_dtype(length=20) + ) + assert x.dtype == "S20" + + # read T <- S + y = x.astype("T") + assert y.dtype.kind == "T" + assert y[:].dtype.kind == "T" + np.testing.assert_array_equal(y[:], data) + + # write T -> S + x[0] = np.asarray("1234", dtype="T") + data[0] = "1234" + np.testing.assert_array_equal(y[:], data) + + +def test_fixed_to_variable_width_too_short(writable_file): + # Note: this test triggers calls to H5Tconvert which are otherwise skipped. + + data = ["foo", "bar"] + x = writable_file.create_dataset( + "x", data=data, dtype=h5py.string_dtype(length=3) + ) + assert x.dtype == "S3" + + # write T -> S + x[0] = np.asarray("1234", dtype="T") + np.testing.assert_array_equal(x[:], [b"123", b"bar"]) + + +def test_variable_to_fixed_width(writable_file): + data = ["foo", "longer than 8 bytes"] + bdata = [b"foo", b"longer than 8 bytes"] + x = writable_file.create_dataset("x", data=data, dtype="T") + + # read S <- T + y = x.astype("S20") + assert y.dtype == "S20" + assert y[:].dtype == "S20" + np.testing.assert_array_equal(y[:], bdata) + + y = x.astype("S3") + assert y.dtype == "S3" + assert y[:].dtype == "S3" + np.testing.assert_array_equal(y[:], [b"foo", b"lon"]) + + # write S -> T + x[0] = np.asarray(b"1234", dtype="S5") + bdata[0] = b"1234" + np.testing.assert_array_equal(x[:], bdata) + + +def test_write_object_into_npystrings(writable_file): + x = writable_file.create_dataset("x", data=["foo"], dtype="T") + x[0] = np.asarray("1234", dtype="O") + np.testing.assert_array_equal(x[:], b"1234") + + +def test_write_npystrings_into_object(writable_file): + x = writable_file.create_dataset( + "x", data=["foo"], dtype=h5py.string_dtype() + ) + assert x.dtype == object + x[0] = np.asarray("1234", dtype="T") + np.testing.assert_array_equal(x[:], b"1234") + + # Test with HDF5 variable-length strings with ASCII character set + xa = writable_file.create_dataset( + "xa", shape=(1,), dtype=h5py.string_dtype('ascii') + ) + xa[0] = np.asarray("2345", dtype="T") + np.testing.assert_array_equal(xa[:], b"2345") + + +def test_fillvalue(writable_file): + # Create as NpyString dtype + x = writable_file.create_dataset("x", shape=(2,), dtype="T", fillvalue="foo") + assert isinstance(x.fillvalue, bytes) + assert x.fillvalue == b"foo" + assert x[0] == b"foo" + + # Create as object dtype + y = writable_file.create_dataset( + "y", shape=(2,), dtype=h5py.string_dtype(), fillvalue=b"foo" + ) + assert isinstance(y.fillvalue, bytes) + assert y.fillvalue == b"foo" + assert y[0] == b"foo" + # Convert object dtype to NpyString + y = y.astype("T") + assert y[0] == "foo" + + +def test_empty_string(writable_file): + data = np.array(["", "a", "b"], dtype="T") + x = writable_file.create_dataset("x", data=data) + np.testing.assert_array_equal(x[:], [b"", b"a", b"b"]) + np.testing.assert_array_equal(x.astype("T")[:], data) + data[:2] = ["c", ""] + x[:2] = data[:2] + np.testing.assert_array_equal(x[:], [b"c", b"", b"b"]) + np.testing.assert_array_equal(x.astype("T")[:], data) + + +def test_astype_nonstring(writable_file): + x = writable_file.create_dataset("x", shape=(2, ), dtype="i8") + with pytest.raises(TypeError, match="HDF5 string datatype"): + x.astype("T") + + +def test_resized_read(writable_file): + """Read default values created by resize(). This triggers a special case + where libhdf5 returns a char** containing NULL pointers. + """ + l = ["string1", "string2", "string3"] + data = np.array(l, dtype='T') + d = writable_file.create_dataset("dset", data=data, maxshape=(None,)) + d.resize((10,)) + + np.testing.assert_array_equal(d[:], np.array( + [s.encode() for s in l] + [b''] * 7, dtype=object + )) + np.testing.assert_array_equal(d.astype('T')[:], np.array(l + [''] * 7, dtype='T')) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_objects.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..7e36a4172f0f539015108e61f0c829ee1c6b480f --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_objects.py @@ -0,0 +1,88 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. +import os +import threading +from unittest import SkipTest + +import time + +from h5py import _objects as o +from .common import TestCase + + +class TestObjects(TestCase): + + def test_invalid(self): + # Check for segfault on close + oid = o.ObjectID(0) + del oid + oid = o.ObjectID(1) + del oid + + def test_equality(self): + # Identifier-based equality + oid1 = o.ObjectID(42) + oid2 = o.ObjectID(42) + oid3 = o.ObjectID(43) + + self.assertEqual(oid1, oid2) + self.assertNotEqual(oid1, oid3) + + def test_hash(self): + # Default objects are not hashable + oid = o.ObjectID(42) + with self.assertRaises(TypeError): + hash(oid) + + def test_phil_fork_with_threads(self): + # Test that handling of the phil Lock after fork is correct. + # We simulate a deadlock in the forked process by explicitly + # waiting for the phil Lock to be acquired in a different thread + # before forking. + + # On Windows forking (and the register_at_fork handler) + # are not available, skip this test. + if not hasattr(os, "fork"): + raise SkipTest("os.fork not available") + + thread_acquired_phil_event = threading.Event() + + def f(): + o.phil.acquire() + try: + thread_acquired_phil_event.set() + time.sleep(1) + finally: + o.phil.release() + + thread = threading.Thread(target=f) + thread.start() + try: + # wait for the thread running "f" to have acquired the phil lock + thread_acquired_phil_event.wait() + + # now fork the current (main) thread while the other thread holds the lock + pid = os.fork() + if pid == 0: + # child process + # If we handle the phil lock correctly, this should not deadlock, + # and we should be able to acquire the lock here. + if o.phil.acquire(blocking=False): + o.phil.release() + os._exit(0) + else: + os._exit(1) + else: + # parent process + # wait for the child process to finish + _, status = os.waitpid(pid, 0) + assert os.WIFEXITED(status) + assert os.WEXITSTATUS(status) == 0 + finally: + thread.join() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_ros3.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_ros3.py new file mode 100644 index 0000000000000000000000000000000000000000..e9f6d53069728e759a883d02c85cc8bdeb2c1488 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_ros3.py @@ -0,0 +1,112 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Read-only S3 virtual file driver (VFD) test module. +""" + +import h5py +from h5py._hl.files import make_fapl +import pytest + + +pytestmark = [ + pytest.mark.skipif( + not h5py.h5.get_config().ros3, + reason="ros3 driver not available") +] + + +@pytest.mark.network +@pytest.mark.parametrize( + "kwargs", + [ + pytest.param( + {}, + id="HDF5-v1", + marks=pytest.mark.skipif( + h5py.version.hdf5_version_tuple >= (2, 0, 0), + reason="Requires HDF5 < 2.0", + ), + ), + pytest.param( + {"aws_region": b"us-east-2"}, + id="HDF5-v2", + marks=pytest.mark.skipif( + h5py.version.hdf5_version_tuple < (2, 0, 0), + reason="Requires HDF5 >= 2.0", + ), + ), + ], +) +def test_ros3(kwargs): + """ ROS3 driver and options """ + + with h5py.File("https://dandiarchive.s3.amazonaws.com/ros3test.hdf5", 'r', + driver='ros3', **kwargs) as f: + assert f + assert 'mydataset' in f.keys() + assert f["mydataset"].shape == (100,) + + +@pytest.mark.parametrize( + "exc,match_exc", + [ + pytest.param( + ValueError, + [ + "AWS region required for s3:// location", + r"^foo://wrong/scheme: S3 location must begin with", + ], + id="HDF5-v1", + marks=pytest.mark.skipif( + h5py.version.hdf5_version_tuple >= (2, 0, 0), + reason="Requires HDF5 < 2.0", + ), + ), + pytest.param( + OSError, + [None, "can't parse object key from path"], + id="HDF5-v2", + marks=pytest.mark.skipif( + h5py.version.hdf5_version_tuple < (2, 0, 0), + reason="Requires HDF5 >= 2.0", + ), + ), + ], +) +def test_ros3_s3_fails(exc, match_exc): + """ROS3 exceptions for s3:// location""" + with pytest.raises(exc, match=match_exc[0]): + h5py.File('s3://fakebucket/fakekey', 'r', driver='ros3') + + with pytest.raises(exc, match=match_exc[1]): + h5py.File('foo://wrong/scheme', 'r', driver='ros3') + + +@pytest.mark.network +def test_ros3_s3uri(): + """Use S3 URI with ROS3 driver""" + with h5py.File('s3://dandiarchive/ros3test.hdf5', 'r', driver='ros3', + aws_region=b'us-east-2') as f: + assert f + assert 'mydataset' in f.keys() + assert f["mydataset"].shape == (100,) + + +@pytest.mark.skipif(h5py.version.hdf5_version_tuple < (1, 14, 2), + reason='AWS S3 access token support in HDF5 >= 1.14.2') +def test_ros3_temp_token(): + """Set and get S3 access token""" + token = b'#0123FakeToken4567/8/9' + fapl = make_fapl('ros3', libver=None, rdcc_nslots=None, rdcc_nbytes=None, + rdcc_w0=None, locking=None, page_buf_size=None, min_meta_keep=None, + min_raw_keep=None, alignment_threshold=1, alignment_interval=1, + meta_block_size=None, session_token=token) + assert token, fapl.get_fapl_ros3_token() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_selections.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_selections.py new file mode 100644 index 0000000000000000000000000000000000000000..642d46e9584e96c0e1c552c79fb93035f0596ab4 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_selections.py @@ -0,0 +1,142 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Tests for the (internal) selections module +""" + +import numpy as np +import h5py +import h5py._hl.selections as sel +import h5py._hl.selections2 as sel2 + +from .common import TestCase + +class BaseSelection(TestCase): + def setUp(self): + self.f = h5py.File(self.mktemp(), 'w') + self.dsid = self.f.create_dataset('x', ()).id + + def tearDown(self): + if self.f: + self.f.close() + +class TestTypeGeneration(BaseSelection): + + """ + Internal feature: Determine output types from dataset dtype and fields. + """ + + def test_simple(self): + """ Non-compound types are handled appropriately """ + dt = np.dtype('i') + out, format = sel2.read_dtypes(dt, ()) + self.assertEqual(out, format) + self.assertEqual(out, np.dtype('i')) + + def test_simple_fieldexc(self): + """ Field names for non-field types raises ValueError """ + dt = np.dtype('i') + with self.assertRaises(ValueError): + out, format = sel2.read_dtypes(dt, ('a',)) + + def test_compound_simple(self): + """ Compound types with elemental subtypes """ + dt = np.dtype( [('a','i'), ('b','f'), ('c','|S10')] ) + + # Implicit selection of all fields -> all fields + out, format = sel2.read_dtypes(dt, ()) + self.assertEqual(out, format) + self.assertEqual(out, dt) + + # Explicit selection of fields -> requested fields + out, format = sel2.read_dtypes(dt, ('a','b')) + self.assertEqual(out, format) + self.assertEqual(out, np.dtype( [('a','i'), ('b','f')] )) + + # Explicit selection of exactly one field -> no fields + out, format = sel2.read_dtypes(dt, ('a',)) + self.assertEqual(out, np.dtype('i')) + self.assertEqual(format, np.dtype( [('a','i')] )) + + # Field does not appear in named typed + with self.assertRaises(ValueError): + out, format = sel2.read_dtypes(dt, ('j', 'k')) + +class TestScalarSliceRules(BaseSelection): + + """ + Internal feature: selections rules for scalar datasets + """ + + def test_args(self): + """ Permissible arguments for scalar slicing """ + shape, selection = sel2.read_selections_scalar(self.dsid, ()) + self.assertEqual(shape, None) + self.assertEqual(selection.get_select_npoints(), 1) + + shape, selection = sel2.read_selections_scalar(self.dsid, (Ellipsis,)) + self.assertEqual(shape, ()) + self.assertEqual(selection.get_select_npoints(), 1) + + with self.assertRaises(ValueError): + shape, selection = sel2.read_selections_scalar(self.dsid, (1,)) + + dsid = self.f.create_dataset('y', (1,)).id + with self.assertRaises(RuntimeError): + shape, selection = sel2.read_selections_scalar(dsid, (1,)) + +class TestSelection(BaseSelection): + + """ High-level routes to generate a selection + """ + + def test_selection(self): + dset = self.f.create_dataset('dset', (100,100)) + regref = dset.regionref[0:100, 0:100] + + # args is list, return a FancySelection + st = sel.select((10,), list([1,2,3]), dset) + self.assertIsInstance(st, sel.FancySelection) + + # args[0] is tuple, return a FancySelection + st = sel.select((10,), ((1, 2, 3),), dset) + self.assertIsInstance(st, sel.FancySelection) + + # args is a Boolean mask, return a PointSelection + st1 = sel.select((5,), np.array([True,False,False,False,True]), dset) + self.assertIsInstance(st1, sel.PointSelection) + + # args is int, return a SimpleSelection + st2 = sel.select((10,), 1, dset) + self.assertIsInstance(st2, sel.SimpleSelection) + + # args is str, should be rejected + with self.assertRaises(TypeError): + sel.select((100,), "foo", dset) + + # args is RegionReference, return a Selection instance + st3 = sel.select((100,100), regref, dset) + self.assertIsInstance(st3, sel.Selection) + + # args is RegionReference, but dataset is None + with self.assertRaises(TypeError): + sel.select((100,), regref, None) + + # args is RegionReference, but its shape doesn't match dataset shape + with self.assertRaises(TypeError): + sel.select((100,), regref, dset) + + # args is a single Selection instance, return the arg + st4 = sel.select((100,100), st3, dset) + self.assertEqual(st4,st3) + + # args is a single Selection instance, but args shape doesn't match Shape + with self.assertRaises(TypeError): + sel.select((100,), st3, dset) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_slicing.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_slicing.py new file mode 100644 index 0000000000000000000000000000000000000000..056dc719bad6bcf3e19feb1cf22594107f6d7def --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_slicing.py @@ -0,0 +1,415 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Dataset slicing test module. + + Tests all supported slicing operations, including read/write and + broadcasting operations. Does not test type conversion except for + corner cases overlapping with slicing; for example, when selecting + specific fields of a compound type. +""" + +import numpy as np + +from .common import TestCase + +import h5py +from h5py import File, MultiBlockSlice + +class BaseSlicing(TestCase): + + def setUp(self): + self.f = File(self.mktemp(), 'w') + + def tearDown(self): + if self.f: + self.f.close() + +class TestSingleElement(BaseSlicing): + + """ + Feature: Retrieving a single element works with NumPy semantics + """ + + def test_single_index(self): + """ Single-element selection with [index] yields array scalar """ + dset = self.f.create_dataset('x', (1,), dtype='i1') + out = dset[0] + self.assertIsInstance(out, np.int8) + + def test_single_null(self): + """ Single-element selection with [()] yields ndarray """ + dset = self.f.create_dataset('x', (1,), dtype='i1') + out = dset[()] + self.assertIsInstance(out, np.ndarray) + self.assertEqual(out.shape, (1,)) + + def test_scalar_index(self): + """ Slicing with [...] yields scalar ndarray """ + dset = self.f.create_dataset('x', shape=(), dtype='f') + out = dset[...] + self.assertIsInstance(out, np.ndarray) + self.assertEqual(out.shape, ()) + + def test_scalar_null(self): + """ Slicing with [()] yields array scalar """ + dset = self.f.create_dataset('x', shape=(), dtype='i1') + out = dset[()] + self.assertIsInstance(out, np.int8) + + def test_compound(self): + """ Compound scalar is numpy.void, not tuple (issue 135) """ + dt = np.dtype([('a','i4'),('b','f8')]) + v = np.ones((4,), dtype=dt) + dset = self.f.create_dataset('foo', (4,), data=v) + self.assertEqual(dset[0], v[0]) + self.assertIsInstance(dset[0], np.void) + +class TestObjectIndex(BaseSlicing): + + """ + Feature: numpy.object_ subtypes map to real Python objects + """ + + def test_reference(self): + """ Indexing a reference dataset returns a h5py.Reference instance """ + dset = self.f.create_dataset('x', (1,), dtype=h5py.ref_dtype) + dset[0] = self.f.ref + self.assertEqual(type(dset[0]), h5py.Reference) + + def test_regref(self): + """ Indexing a region reference dataset returns a h5py.RegionReference + """ + dset1 = self.f.create_dataset('x', (10,10)) + regref = dset1.regionref[...] + dset2 = self.f.create_dataset('y', (1,), dtype=h5py.regionref_dtype) + dset2[0] = regref + self.assertEqual(type(dset2[0]), h5py.RegionReference) + + def test_reference_field(self): + """ Compound types of which a reference is an element work right """ + dt = np.dtype([('a', 'i'),('b', h5py.ref_dtype)]) + + dset = self.f.create_dataset('x', (1,), dtype=dt) + dset[0] = (42, self.f['/'].ref) + + out = dset[0] + self.assertEqual(type(out[1]), h5py.Reference) # isinstance does NOT work + + def test_scalar(self): + """ Indexing returns a real Python object on scalar datasets """ + dset = self.f.create_dataset('x', (), dtype=h5py.ref_dtype) + dset[()] = self.f.ref + self.assertEqual(type(dset[()]), h5py.Reference) + + def test_bytestr(self): + """ Indexing a byte string dataset returns a real python byte string + """ + dset = self.f.create_dataset('x', (1,), dtype=h5py.string_dtype(encoding='ascii')) + dset[0] = b"Hello there!" + self.assertEqual(type(dset[0]), bytes) + +class TestSimpleSlicing(TestCase): + + """ + Feature: Simple NumPy-style slices (start:stop:step) are supported. + """ + + def setUp(self): + self.f = File(self.mktemp(), 'w') + self.arr = np.arange(10) + self.dset = self.f.create_dataset('x', data=self.arr) + + def tearDown(self): + if self.f: + self.f.close() + + def test_negative_stop(self): + """ Negative stop indexes work as they do in NumPy """ + self.assertArrayEqual(self.dset[2:-2], self.arr[2:-2]) + + def test_write(self): + """Assigning to a 1D slice of a 2D dataset + """ + dset = self.f.create_dataset('x2', (10, 2)) + + x = np.zeros((10, 1)) + dset[:, 0] = x[:, 0] + with self.assertRaises(TypeError): + dset[:, 1] = x + +class TestArraySlicing(BaseSlicing): + + """ + Feature: Array types are handled appropriately + """ + + def test_read(self): + """ Read arrays tack array dimensions onto end of shape tuple """ + dt = np.dtype('(3,)f8') + dset = self.f.create_dataset('x',(10,),dtype=dt) + self.assertEqual(dset.shape, (10,)) + self.assertEqual(dset.dtype, dt) + + # Full read + out = dset[...] + self.assertEqual(out.dtype, np.dtype('f8')) + self.assertEqual(out.shape, (10,3)) + + # Single element + out = dset[0] + self.assertEqual(out.dtype, np.dtype('f8')) + self.assertEqual(out.shape, (3,)) + + # Range + out = dset[2:8:2] + self.assertEqual(out.dtype, np.dtype('f8')) + self.assertEqual(out.shape, (3,3)) + + def test_write_broadcast(self): + """ Array fill from constant is not supported (issue 211). + """ + dt = np.dtype('(3,)i') + + dset = self.f.create_dataset('x', (10,), dtype=dt) + + with self.assertRaises(TypeError): + dset[...] = 42 + + def test_write_element(self): + """ Write a single element to the array + + Issue 211. + """ + dt = np.dtype('(3,)f8') + dset = self.f.create_dataset('x', (10,), dtype=dt) + + data = np.array([1,2,3.0]) + dset[4] = data + + out = dset[4] + self.assertTrue(np.all(out == data)) + + def test_write_slices(self): + """ Write slices to array type """ + dt = np.dtype('(3,)i') + + data1 = np.ones((2,), dtype=dt) + data2 = np.ones((4,5), dtype=dt) + + dset = self.f.create_dataset('x', (10,9,11), dtype=dt) + + dset[0,0,2:4] = data1 + self.assertArrayEqual(dset[0,0,2:4], data1) + + dset[3, 1:5, 6:11] = data2 + self.assertArrayEqual(dset[3, 1:5, 6:11], data2) + + + def test_roundtrip(self): + """ Read the contents of an array and write them back + + Issue 211. + """ + dt = np.dtype('(3,)f8') + dset = self.f.create_dataset('x', (10,), dtype=dt) + + out = dset[...] + dset[...] = out + + self.assertTrue(np.all(dset[...] == out)) + + +class TestZeroLengthSlicing(BaseSlicing): + + """ + Slices resulting in empty arrays + """ + + def test_slice_zero_length_dimension(self): + """ Slice a dataset with a zero in its shape vector + along the zero-length dimension """ + for i, shape in enumerate([(0,), (0, 3), (0, 2, 1)]): + dset = self.f.create_dataset('x%d'%i, shape, dtype=int, maxshape=(None,)*len(shape)) + self.assertEqual(dset.shape, shape) + out = dset[...] + self.assertIsInstance(out, np.ndarray) + self.assertEqual(out.shape, shape) + out = dset[:] + self.assertIsInstance(out, np.ndarray) + self.assertEqual(out.shape, shape) + if len(shape) > 1: + out = dset[:, :1] + self.assertIsInstance(out, np.ndarray) + self.assertEqual(out.shape[:2], (0, 1)) + + def test_slice_other_dimension(self): + """ Slice a dataset with a zero in its shape vector + along a non-zero-length dimension """ + for i, shape in enumerate([(3, 0), (1, 2, 0), (2, 0, 1)]): + dset = self.f.create_dataset('x%d'%i, shape, dtype=int, maxshape=(None,)*len(shape)) + self.assertEqual(dset.shape, shape) + out = dset[:1] + self.assertIsInstance(out, np.ndarray) + self.assertEqual(out.shape, (1,)+shape[1:]) + + def test_slice_of_length_zero(self): + """ Get a slice of length zero from a non-empty dataset """ + for i, shape in enumerate([(3,), (2, 2,), (2, 1, 5)]): + dset = self.f.create_dataset('x%d'%i, data=np.zeros(shape, int), maxshape=(None,)*len(shape)) + self.assertEqual(dset.shape, shape) + out = dset[1:1] + self.assertIsInstance(out, np.ndarray) + self.assertEqual(out.shape, (0,)+shape[1:]) + +class TestFieldNames(BaseSlicing): + + """ + Field names for read & write + """ + + dt = np.dtype([('a', 'f'), ('b', 'i'), ('c', 'f4')]) + data = np.ones((100,), dtype=dt) + + def setUp(self): + BaseSlicing.setUp(self) + self.dset = self.f.create_dataset('x', (100,), dtype=self.dt) + self.dset[...] = self.data + + def test_read(self): + """ Test read with field selections """ + self.assertArrayEqual(self.dset['a'], self.data['a']) + + def test_unicode_names(self): + """ Unicode field names for for read and write """ + self.assertArrayEqual(self.dset['a'], self.data['a']) + self.dset['a'] = 42 + data = self.data.copy() + data['a'] = 42 + self.assertArrayEqual(self.dset['a'], data['a']) + + def test_write(self): + """ Test write with field selections """ + data2 = self.data.copy() + data2['a'] *= 2 + self.dset['a'] = data2 + self.assertTrue(np.all(self.dset[...] == data2)) + data2['b'] *= 4 + self.dset['b'] = data2 + self.assertTrue(np.all(self.dset[...] == data2)) + data2['a'] *= 3 + data2['c'] *= 3 + self.dset['a','c'] = data2 + self.assertTrue(np.all(self.dset[...] == data2)) + + def test_write_noncompound(self): + """ Test write with non-compound source (single-field) """ + data2 = self.data.copy() + data2['b'] = 1.0 + self.dset['b'] = 1.0 + self.assertTrue(np.all(self.dset[...] == data2)) + + +class TestMultiBlockSlice(BaseSlicing): + + def setUp(self): + super().setUp() + self.arr = np.arange(10) + self.dset = self.f.create_dataset('x', data=self.arr) + + def test_default(self): + # Default selects entire dataset as one block + mbslice = MultiBlockSlice() + + self.assertEqual(mbslice.indices(10), (0, 1, 10, 1)) + np.testing.assert_array_equal(self.dset[mbslice], self.arr) + + def test_default_explicit(self): + mbslice = MultiBlockSlice(start=0, count=10, stride=1, block=1) + + self.assertEqual(mbslice.indices(10), (0, 1, 10, 1)) + np.testing.assert_array_equal(self.dset[mbslice], self.arr) + + def test_start(self): + mbslice = MultiBlockSlice(start=4) + + self.assertEqual(mbslice.indices(10), (4, 1, 6, 1)) + np.testing.assert_array_equal(self.dset[mbslice], np.array([4, 5, 6, 7, 8, 9])) + + def test_count(self): + mbslice = MultiBlockSlice(count=7) + + self.assertEqual(mbslice.indices(10), (0, 1, 7, 1)) + np.testing.assert_array_equal( + self.dset[mbslice], np.array([0, 1, 2, 3, 4, 5, 6]) + ) + + def test_count_more_than_length_error(self): + mbslice = MultiBlockSlice(count=11) + with self.assertRaises(ValueError): + mbslice.indices(10) + + def test_stride(self): + mbslice = MultiBlockSlice(stride=2) + + self.assertEqual(mbslice.indices(10), (0, 2, 5, 1)) + np.testing.assert_array_equal(self.dset[mbslice], np.array([0, 2, 4, 6, 8])) + + def test_stride_zero_error(self): + with self.assertRaises(ValueError): + # This would cause a ZeroDivisionError if not caught + MultiBlockSlice(stride=0, block=0).indices(10) + + def test_stride_block_equal(self): + mbslice = MultiBlockSlice(stride=2, block=2) + + self.assertEqual(mbslice.indices(10), (0, 2, 5, 2)) + np.testing.assert_array_equal(self.dset[mbslice], self.arr) + + def test_block_more_than_stride_error(self): + with self.assertRaises(ValueError): + MultiBlockSlice(block=3) + + with self.assertRaises(ValueError): + MultiBlockSlice(stride=2, block=3) + + def test_stride_more_than_block(self): + mbslice = MultiBlockSlice(stride=3, block=2) + + self.assertEqual(mbslice.indices(10), (0, 3, 3, 2)) + np.testing.assert_array_equal(self.dset[mbslice], np.array([0, 1, 3, 4, 6, 7])) + + def test_block_overruns_extent_error(self): + # If fully described then must fit within extent + mbslice = MultiBlockSlice(start=2, count=2, stride=5, block=4) + with self.assertRaises(ValueError): + mbslice.indices(10) + + def test_fully_described(self): + mbslice = MultiBlockSlice(start=1, count=2, stride=5, block=4) + + self.assertEqual(mbslice.indices(10), (1, 5, 2, 4)) + np.testing.assert_array_equal( + self.dset[mbslice], np.array([1, 2, 3, 4, 6, 7, 8, 9]) + ) + + def test_count_calculated(self): + # If not given, count should be calculated to select as many full blocks as possible + mbslice = MultiBlockSlice(start=1, stride=3, block=2) + + self.assertEqual(mbslice.indices(10), (1, 3, 3, 2)) + np.testing.assert_array_equal(self.dset[mbslice], np.array([1, 2, 4, 5, 7, 8])) + + def test_zero_count_calculated_error(self): + # In this case, there is no possible count to select even one block, so error + mbslice = MultiBlockSlice(start=8, stride=4, block=3) + + with self.assertRaises(ValueError): + mbslice.indices(10) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_vds/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_vds/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a4d4dca4578ae2d73a9cea822203232d29508d35 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_vds/__init__.py @@ -0,0 +1,4 @@ + +from .test_virtual_source import * +from .test_highlevel_vds import * +from .test_lowlevel_vds import * diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_vds/test_highlevel_vds.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_vds/test_highlevel_vds.py new file mode 100644 index 0000000000000000000000000000000000000000..60f659aee421aaebfa7e4891a54f6db69b6af56b --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_vds/test_highlevel_vds.py @@ -0,0 +1,476 @@ +''' +Unit test for the high level vds interface for eiger +https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf +''' +import numpy as np +from numpy.testing import assert_array_equal +import os +import os.path as osp +import shutil +import tempfile + +import h5py as h5 +from ..common import ut +from ..._hl.vds import vds_support + + +@ut.skipUnless(vds_support, + 'VDS requires HDF5 >= 1.9.233') +class TestEigerHighLevel(ut.TestCase): + def setUp(self): + self.working_dir = tempfile.mkdtemp() + self.fname = ['raw_file_1.h5', 'raw_file_2.h5', 'raw_file_3.h5'] + for k, outfile in enumerate(self.fname): + filename = osp.join(self.working_dir, outfile) + f = h5.File(filename, 'w') + f['data'] = np.ones((20, 200, 200)) * k + f.close() + + f = h5.File(osp.join(self.working_dir, 'raw_file_4.h5'), 'w') + f['data'] = np.ones((18, 200, 200)) * 3 + self.fname.append('raw_file_4.h5') + self.fname = [osp.join(self.working_dir, ix) for ix in self.fname] + f.close() + + def test_eiger_high_level(self): + outfile = osp.join(self.working_dir, 'eiger.h5') + layout = h5.VirtualLayout(shape=(78, 200, 200), dtype=float) + + M_minus_1 = 0 + # Create the virtual dataset file + with h5.File(outfile, 'w', libver='latest') as f: + for foo in self.fname: + in_data = h5.File(foo, 'r')['data'] + src_shape = in_data.shape + in_data.file.close() + M = M_minus_1 + src_shape[0] + vsource = h5.VirtualSource(foo, 'data', shape=src_shape) + layout[M_minus_1:M, :, :] = vsource + M_minus_1 = M + f.create_virtual_dataset('data', layout, fillvalue=45) + + f = h5.File(outfile, 'r')['data'] + self.assertEqual(f[10, 100, 10], 0.0) + self.assertEqual(f[30, 100, 100], 1.0) + self.assertEqual(f[50, 100, 100], 2.0) + self.assertEqual(f[70, 100, 100], 3.0) + f.file.close() + + def tearDown(self): + shutil.rmtree(self.working_dir) + +''' +Unit test for the high level vds interface for excalibur +https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf +''' + +class ExcaliburData: + FEM_PIXELS_PER_CHIP_X = 256 + FEM_PIXELS_PER_CHIP_Y = 256 + FEM_CHIPS_PER_STRIPE_X = 8 + FEM_CHIPS_PER_STRIPE_Y = 1 + FEM_STRIPES_PER_MODULE = 2 + + @property + def sensor_module_dimensions(self): + x_pixels = self.FEM_PIXELS_PER_CHIP_X * self.FEM_CHIPS_PER_STRIPE_X + y_pixels = self.FEM_PIXELS_PER_CHIP_Y * self.FEM_CHIPS_PER_STRIPE_Y * self.FEM_STRIPES_PER_MODULE + return y_pixels, x_pixels, + + @property + def fem_stripe_dimensions(self): + x_pixels = self.FEM_PIXELS_PER_CHIP_X * self.FEM_CHIPS_PER_STRIPE_X + y_pixels = self.FEM_PIXELS_PER_CHIP_Y * self.FEM_CHIPS_PER_STRIPE_Y + return y_pixels, x_pixels, + + def generate_sensor_module_image(self, value, dtype='uint16'): + dset = np.empty(shape=self.sensor_module_dimensions, dtype=dtype) + dset.fill(value) + return dset + + def generate_fem_stripe_image(self, value, dtype='uint16'): + dset = np.empty(shape=self.fem_stripe_dimensions, dtype=dtype) + dset.fill(value) + return dset + + +@ut.skipUnless(vds_support, + 'VDS requires HDF5 >= 1.9.233') +class TestExcaliburHighLevel(ut.TestCase): + def create_excalibur_fem_stripe_datafile(self, fname, nframes, excalibur_data,scale): + shape = (nframes,) + excalibur_data.fem_stripe_dimensions + max_shape = shape#(None,) + excalibur_data.fem_stripe_dimensions + chunk = (1,) + excalibur_data.fem_stripe_dimensions + with h5.File(fname, 'w', libver='latest') as f: + dset = f.create_dataset('data', shape=shape, maxshape=max_shape, chunks=chunk, dtype='uint16') + for data_value_index in np.arange(nframes): + dset[data_value_index] = excalibur_data.generate_fem_stripe_image(data_value_index*scale) + + def setUp(self): + self.working_dir = tempfile.mkdtemp() + self.fname = ["stripe_%d.h5" % stripe for stripe in range(1,7)] + self.fname = [osp.join(self.working_dir, f) for f in self.fname] + nframes = 5 + self.edata = ExcaliburData() + for k, raw_file in enumerate(self.fname): + self.create_excalibur_fem_stripe_datafile(raw_file, nframes, self.edata,k) + + def test_excalibur_high_level(self): + outfile = osp.join(self.working_dir, 'excalibur.h5') + f = h5.File(outfile,'w',libver='latest') # create an output file. + in_key = 'data' # where is the data at the input? + in_sh = h5.File(self.fname[0],'r')[in_key].shape # get the input shape + dtype = h5.File(self.fname[0],'r')[in_key].dtype # get the datatype + + # now generate the output shape + vertical_gap = 10 # pixels spacing in the vertical + nfiles = len(self.fname) + nframes = in_sh[0] + width = in_sh[2] + height = (in_sh[1]*nfiles) + (vertical_gap*(nfiles-1)) + out_sh = (nframes, height, width) + + # Virtual layout is a representation of the output dataset + layout = h5.VirtualLayout(shape=out_sh, dtype=dtype) + offset = 0 # initial offset + for i, filename in enumerate(self.fname): + # A representation of the input dataset + vsource = h5.VirtualSource(filename, in_key, shape=in_sh) + layout[:, offset:(offset + in_sh[1]), :] = vsource # map them with indexing + offset += in_sh[1] + vertical_gap # increment the offset + + # pass the fill value and list of maps + f.create_virtual_dataset('data', layout, fillvalue=0x1) + f.close() + + f = h5.File(outfile,'r')['data'] + self.assertEqual(f[3,100,0], 0.0) + self.assertEqual(f[3,260,0], 1.0) + self.assertEqual(f[3,350,0], 3.0) + self.assertEqual(f[3,650,0], 6.0) + self.assertEqual(f[3,900,0], 9.0) + self.assertEqual(f[3,1150,0], 12.0) + self.assertEqual(f[3,1450,0], 15.0) + f.file.close() + + def tearDown(self): + shutil.rmtree(self.working_dir) + + +''' +Unit test for the high level vds interface for percival +https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf +''' + + +@ut.skipUnless(vds_support, + 'VDS requires HDF5 >= 1.9.233') +class TestPercivalHighLevel(ut.TestCase): + + def setUp(self): + self.working_dir = tempfile.mkdtemp() + self.fname = ['raw_file_1.h5','raw_file_2.h5','raw_file_3.h5'] + k = 0 + for outfile in self.fname: + filename = osp.join(self.working_dir, outfile) + f = h5.File(filename,'w') + f['data'] = np.ones((20,200,200))*k + k +=1 + f.close() + + f = h5.File(osp.join(self.working_dir, 'raw_file_4.h5'), 'w') + f['data'] = np.ones((19,200,200))*3 + self.fname.append('raw_file_4.h5') + self.fname = [osp.join(self.working_dir, ix) for ix in self.fname] + f.close() + + def test_percival_high_level(self): + outfile = osp.join(self.working_dir, 'percival.h5') + + # Virtual layout is a representation of the output dataset + layout = h5.VirtualLayout(shape=(79, 200, 200), dtype=np.float64) + for k, filename in enumerate(self.fname): + dim1 = 19 if k == 3 else 20 + vsource = h5.VirtualSource(filename, 'data',shape=(dim1, 200, 200)) + layout[k:79:4, :, :] = vsource[:, :, :] + + # Create the virtual dataset file + with h5.File(outfile, 'w', libver='latest') as f: + f.create_virtual_dataset('data', layout, fillvalue=-5) + + foo = np.array(2 * list(range(4))) + with h5.File(outfile,'r') as f: + ds = f['data'] + line = ds[:8,100,100] + self.assertEqual(ds.shape, (79,200,200),) + assert_array_equal(line, foo) + + def test_percival_source_from_dataset(self): + outfile = osp.join(self.working_dir, 'percival.h5') + + # Virtual layout is a representation of the output dataset + layout = h5.VirtualLayout(shape=(79, 200, 200), dtype=np.float64) + for k, filename in enumerate(self.fname): + with h5.File(filename, 'r') as f: + vsource = h5.VirtualSource(f['data']) + layout[k:79:4, :, :] = vsource + + # Create the virtual dataset file + with h5.File(outfile, 'w', libver='latest') as f: + f.create_virtual_dataset('data', layout, fillvalue=-5) + + foo = np.array(2 * list(range(4))) + with h5.File(outfile,'r') as f: + ds = f['data'] + line = ds[:8,100,100] + self.assertEqual(ds.shape, (79,200,200),) + assert_array_equal(line, foo) + + def tearDown(self): + shutil.rmtree(self.working_dir) + +@ut.skipUnless(vds_support, + 'VDS requires HDF5 >= 1.9.233') +class SlicingTestCase(ut.TestCase): + + def setUp(self): + self.tmpdir = tempfile.mkdtemp() + # Create source files (1.h5 to 4.h5) + for n in range(1, 5): + with h5.File(osp.join(self.tmpdir, '{}.h5'.format(n)), 'w') as f: + d = f.create_dataset('data', (100,), 'i4') + d[:] = np.arange(100) + n + + def make_virtual_ds(self): + # Assemble virtual dataset + layout = h5.VirtualLayout((4, 100), 'i4', maxshape=(4, None)) + + for n in range(1, 5): + filename = osp.join(self.tmpdir, "{}.h5".format(n)) + vsource = h5.VirtualSource(filename, 'data', shape=(100,)) + # Fill the first half with positions 0, 2, 4... from the source + layout[n - 1, :50] = vsource[0:100:2] + # Fill the second half with places 1, 3, 5... from the source + layout[n - 1, 50:] = vsource[1:100:2] + + outfile = osp.join(self.tmpdir, 'VDS.h5') + + # Add virtual dataset to output file + with h5.File(outfile, 'w', libver='latest') as f: + f.create_virtual_dataset('/group/data', layout, fillvalue=-5) + + return outfile + + def test_slice_source(self): + outfile = self.make_virtual_ds() + + with h5.File(outfile, 'r') as f: + assert_array_equal(f['/group/data'][0][:3], [1, 3, 5]) + assert_array_equal(f['/group/data'][0][50:53], [2, 4, 6]) + assert_array_equal(f['/group/data'][3][:3], [4, 6, 8]) + assert_array_equal(f['/group/data'][3][50:53], [5, 7, 9]) + + def test_inspection(self): + with h5.File(osp.join(self.tmpdir, '1.h5'), 'r') as f: + assert not f['data'].is_virtual + + outfile = self.make_virtual_ds() + + with h5.File(outfile, 'r') as f: + ds = f['/group/data'] + assert ds.is_virtual + + src_files = {osp.join(self.tmpdir, '{}.h5'.format(n)) + for n in range(1, 5)} + assert {s.file_name for s in ds.virtual_sources()} == src_files + + def test_mismatched_selections(self): + layout = h5.VirtualLayout((4, 100), 'i4', maxshape=(4, None)) + + filename = osp.join(self.tmpdir, "1.h5") + vsource = h5.VirtualSource(filename, 'data', shape=(100,)) + with self.assertRaisesRegex(ValueError, r'different number'): + layout[0, :49] = vsource[0:100:2] + + def tearDown(self): + shutil.rmtree(self.tmpdir) + +@ut.skipUnless(vds_support, + 'VDS requires HDF5 >= 1.9.233') +class IndexingTestCase(ut.TestCase): + + def setUp(self): + self.tmpdir = tempfile.mkdtemp() + # Create source file (1.h5) + with h5.File(osp.join(self.tmpdir, '1.h5'), 'w') as f: + d = f.create_dataset('data', (10,), 'i4') + d[:] = np.arange(10)*10 + + def test_index_layout(self): + # Assemble virtual dataset (indexing target) + layout = h5.VirtualLayout((100,), 'i4') + + inds = [3,6,20,25,33,47,70,75,96,98] + + filename = osp.join(self.tmpdir, "1.h5") + vsource = h5.VirtualSource(filename, 'data', shape=(10,)) + layout[inds] = vsource + + outfile = osp.join(self.tmpdir, 'VDS.h5') + + # Assembly virtual dataset (indexing source) + layout2 = h5.VirtualLayout((6,), 'i4') + + inds2 = [0,1,4,5,8] + layout2[1:] = vsource[inds2] + + # Add virtual datasets to output file and close + with h5.File(outfile, 'w', libver='latest') as f: + f.create_virtual_dataset('/data', layout, fillvalue=-5) + f.create_virtual_dataset(b'/data2', layout2, fillvalue=-3) + + # Read data from virtual datasets + with h5.File(outfile, 'r') as f: + data = f['/data'][()] + data2 = f['/data2'][()] + + # Verify + assert_array_equal(data[inds], np.arange(10)*10) + assert_array_equal(data2[1:], [0,10,40,50,80]) + + mask = np.zeros(100) + mask[inds] = 1 + self.assertEqual(data[mask == 0].min(), -5) + self.assertEqual(data[mask == 0].max(), -5) + self.assertEqual(data2[0], -3) + + def tearDown(self): + shutil.rmtree(self.tmpdir) + +@ut.skipUnless(vds_support, + 'VDS requires HDF5 >= 1.9.233') +class RelativeLinkTestCase(ut.TestCase): + + def setUp(self): + self.tmpdir = tempfile.mkdtemp() + self.f1 = osp.join(self.tmpdir, 'testfile1.h5') + self.f2 = osp.join(self.tmpdir, 'testfile2.h5') + + self.data1 = np.arange(10) + self.data2 = np.arange(10) * -1 + + with h5.File(self.f1, 'w') as f: + # dataset + ds = f.create_dataset('data', (10,), 'f4') + ds[:] = self.data1 + + with h5.File(self.f2, 'w') as f: + # dataset + ds = f.create_dataset('data', (10,), 'f4') + ds[:] = self.data2 + self.make_vds(f) + + def make_vds(self, f): + # virtual dataset + layout = h5.VirtualLayout((2, 10), 'f4') + vsource1 = h5.VirtualSource(self.f1, 'data', shape=(10,)) + vsource2 = h5.VirtualSource(self.f2, 'data', shape=(10,)) + layout[0] = vsource1 + layout[1] = vsource2 + f.create_virtual_dataset('virtual', layout) + + def test_relative_vds(self): + with h5.File(self.f2) as f: + data = f['virtual'][:] + np.testing.assert_array_equal(data[0], self.data1) + np.testing.assert_array_equal(data[1], self.data2) + + # move f2 -> f3 + f3 = osp.join(self.tmpdir, 'testfile3.h5') + os.rename(self.f2, f3) + + with h5.File(f3) as f: + data = f['virtual'][:] + assert data.dtype == 'f4' + np.testing.assert_array_equal(data[0], self.data1) + np.testing.assert_array_equal(data[1], self.data2) + + # moving other file + f4 = osp.join(self.tmpdir, 'testfile4.h5') + os.rename(self.f1, f4) + + with h5.File(f3) as f: + data = f['virtual'][:] + assert data.dtype == 'f4' + # unavailable data is silently converted to default value + np.testing.assert_array_equal(data[0], 0) + np.testing.assert_array_equal(data[1], self.data2) + + def tearDown(self): + shutil.rmtree(self.tmpdir) + +class RelativeLinkBuildVDSTestCase(RelativeLinkTestCase): + # Test a link to the same file with the virtual dataset created by + # File.build_virtual_dataset() + def make_vds(self, f): + with f.build_virtual_dataset('virtual', (2, 10), dtype='f4') as layout: + layout[0] = h5.VirtualSource(self.f1, 'data', shape=(10,)) + layout[1] = h5.VirtualSource(self.f2, 'data', shape=(10,)) + +@ut.skipUnless(vds_support, + 'VDS requires HDF5 >= 1.9.233') +class VDSUnlimitedTestCase(ut.TestCase): + + def setUp(self): + self.tmpdir = tempfile.mkdtemp() + self.path = osp.join(self.tmpdir, "resize.h5") + with h5.File(self.path, "w") as f: + source_dset = f.create_dataset( + "source", + data=np.arange(20), + shape=(10, 2), + maxshape=(None, 2), + chunks=(10, 1), + fillvalue=-1 + ) + self.layout = h5.VirtualLayout((10, 1), int, maxshape=(None, 1)) + layout_source = h5.VirtualSource(source_dset) + self.layout[:h5.UNLIMITED, 0] = layout_source[:h5.UNLIMITED, 1] + + f.create_virtual_dataset("virtual", self.layout) + + def test_unlimited_axis(self): + comp1 = np.arange(1, 20, 2).reshape(10, 1) + comp2 = np.vstack(( + comp1, + np.full(shape=(10, 1), fill_value=-1) + )) + comp3 = np.vstack(( + comp1, + np.full(shape=(10, 1), fill_value=0) + )) + with h5.File(self.path, "a") as f: + source_dset = f['source'] + virtual_dset = f['virtual'] + np.testing.assert_array_equal(comp1, virtual_dset) + source_dset.resize(20, axis=0) + np.testing.assert_array_equal(comp2, virtual_dset) + source_dset[10:, 1] = np.zeros((10,), dtype=int) + np.testing.assert_array_equal(comp3, virtual_dset) + + def tearDown(self): + shutil.rmtree(self.tmpdir) + + +def test_no_mappings(writable_file): + with writable_file.build_virtual_dataset("foo", (10, 20), np.int32): + pass + + dset = writable_file['foo'] + assert dset.is_virtual + assert dset.virtual_sources() == [] + np.testing.assert_array_equal(dset[()], np.zeros((10, 20), np.int32)) + + +if __name__ == "__main__": + ut.main() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_vds/test_lowlevel_vds.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_vds/test_lowlevel_vds.py new file mode 100644 index 0000000000000000000000000000000000000000..7dfd19bd83b0a214e780bdd38c0f19dc1eda9018 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_vds/test_lowlevel_vds.py @@ -0,0 +1,298 @@ +''' +Unit test for the low level vds interface for eiger +https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf +''' + +import os.path as osp +import tempfile + +import numpy as np + +import h5py as h5 +from ..common import ut + + +class TestEigerLowLevel(ut.TestCase): + def setUp(self): + self.working_dir = tempfile.TemporaryDirectory() + self.fname = ['raw_file_1.h5', 'raw_file_2.h5', 'raw_file_3.h5'] + k = 0 + for outfile in self.fname: + filename = osp.join(self.working_dir.name, outfile) + with h5.File(filename, 'w') as f: + f['data'] = np.ones((20, 200, 200))*k + k += 1 + + with h5.File(osp.join(self.working_dir.name, 'raw_file_4.h5'), 'w') as f: + f['data'] = np.ones((18, 200, 200))*3 + self.fname.append('raw_file_4.h5') + self.fname = [osp.join(self.working_dir.name, ix) for ix in self.fname] + + def test_eiger_low_level(self): + outfile = osp.join(self.working_dir.name, 'eiger.h5') + with h5.File(outfile, 'w', libver='latest') as f: + vdset_shape = (78, 200, 200) + vdset_max_shape = vdset_shape + virt_dspace = h5.h5s.create_simple(vdset_shape, vdset_max_shape) + dcpl = h5.h5p.create(h5.h5p.DATASET_CREATE) + dcpl.set_fill_value(np.array([-1])) + # Create the source dataset dataspace + k = 0 + for foo in self.fname: + with h5.File(foo, 'r') as in_f: + src_shape = in_f['data'].shape + src_dspace = h5.h5s.create_simple(src_shape, src_shape) + # Select the source dataset hyperslab + src_dspace.select_hyperslab(start=(0, 0, 0), + stride=(1, 1, 1), + count=(1, 1, 1), + block=src_shape) + + virt_dspace.select_hyperslab(start=(k, 0, 0), + stride=(1, 1, 1), + count=(1, 1, 1), + block=src_shape) + + dcpl.set_virtual(virt_dspace, foo.encode('utf-8'), + b'data', src_dspace) + k += src_shape[0] + + # Create the virtual dataset + h5.h5d.create(f.id, name=b"data", tid=h5.h5t.NATIVE_INT16, + space=virt_dspace, dcpl=dcpl) + + with h5.File(outfile, 'r') as f: + d = f['data'] + self.assertEqual(d[10, 100, 10], 0.0) + self.assertEqual(d[30, 100, 100], 1.0) + self.assertEqual(d[50, 100, 100], 2.0) + self.assertEqual(d[70, 100, 100], 3.0) + + def tearDown(self): + self.working_dir.cleanup() + + +if __name__ == "__main__": + ut.main() +''' +Unit test for the low level vds interface for excalibur +https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf +''' + + +class ExcaliburData: + FEM_PIXELS_PER_CHIP_X = 256 + FEM_PIXELS_PER_CHIP_Y = 256 + FEM_CHIPS_PER_STRIPE_X = 8 + FEM_CHIPS_PER_STRIPE_Y = 1 + FEM_STRIPES_PER_MODULE = 2 + + @property + def sensor_module_dimensions(self): + x_pixels = self.FEM_PIXELS_PER_CHIP_X * self.FEM_CHIPS_PER_STRIPE_X + y_pixels = self.FEM_PIXELS_PER_CHIP_Y * self.FEM_CHIPS_PER_STRIPE_Y * self.FEM_STRIPES_PER_MODULE + return y_pixels, x_pixels, + + @property + def fem_stripe_dimensions(self): + x_pixels = self.FEM_PIXELS_PER_CHIP_X * self.FEM_CHIPS_PER_STRIPE_X + y_pixels = self.FEM_PIXELS_PER_CHIP_Y * self.FEM_CHIPS_PER_STRIPE_Y + return y_pixels, x_pixels, + + def generate_sensor_module_image(self, value, dtype='uint16'): + dset = np.empty(shape=self.sensor_module_dimensions, dtype=dtype) + dset.fill(value) + return dset + + def generate_fem_stripe_image(self, value, dtype='uint16'): + dset = np.empty(shape=self.fem_stripe_dimensions, dtype=dtype) + dset.fill(value) + return dset + + +class TestExcaliburLowLevel(ut.TestCase): + def create_excalibur_fem_stripe_datafile(self, fname, nframes, excalibur_data,scale): + shape = (nframes,) + excalibur_data.fem_stripe_dimensions + max_shape = (nframes,) + excalibur_data.fem_stripe_dimensions + chunk = (1,) + excalibur_data.fem_stripe_dimensions + with h5.File(fname, 'w', libver='latest') as f: + dset = f.create_dataset('data', shape=shape, maxshape=max_shape, chunks=chunk, dtype='uint16') + for data_value_index in np.arange(nframes): + dset[data_value_index] = excalibur_data.generate_fem_stripe_image(data_value_index*scale) + + def setUp(self): + self.working_dir = tempfile.TemporaryDirectory() + self.fname = ["stripe_%d.h5" % stripe for stripe in range(1,7)] + self.fname = [osp.join(self.working_dir.name, ix) for ix in self.fname] + nframes = 5 + self.edata = ExcaliburData() + k=0 + for raw_file in self.fname: + self.create_excalibur_fem_stripe_datafile(raw_file, nframes, self.edata,k) + k+=1 + + def test_excalibur_low_level(self): + + excalibur_data = self.edata + outfile = osp.join(self.working_dir.name, 'excalibur.h5') + vdset_stripe_shape = (1,) + excalibur_data.fem_stripe_dimensions + vdset_stripe_max_shape = (5, ) + excalibur_data.fem_stripe_dimensions + vdset_shape = (5, + excalibur_data.fem_stripe_dimensions[0] * len(self.fname) + (10 * (len(self.fname)-1)), + excalibur_data.fem_stripe_dimensions[1]) + vdset_max_shape = (5, + excalibur_data.fem_stripe_dimensions[0] * len(self.fname) + (10 * (len(self.fname)-1)), + excalibur_data.fem_stripe_dimensions[1]) + vdset_y_offset = 0 + + # Create the virtual dataset file + with h5.File(outfile, 'w', libver='latest') as f: + + # Create the source dataset dataspace + src_dspace = h5.h5s.create_simple(vdset_stripe_shape, vdset_stripe_max_shape) + # Create the virtual dataset dataspace + virt_dspace = h5.h5s.create_simple(vdset_shape, vdset_max_shape) + + # Create the virtual dataset property list + dcpl = h5.h5p.create(h5.h5p.DATASET_CREATE) + dcpl.set_fill_value(np.array([0x01])) + + # Select the source dataset hyperslab + src_dspace.select_hyperslab(start=(0, 0, 0), count=(1, 1, 1), block=vdset_stripe_max_shape) + + for raw_file in self.fname: + # Select the virtual dataset hyperslab (for the source dataset) + virt_dspace.select_hyperslab(start=(0, vdset_y_offset, 0), + count=(1, 1, 1), + block=vdset_stripe_max_shape) + # Set the virtual dataset hyperslab to point to the real first dataset + dcpl.set_virtual(virt_dspace, raw_file.encode('utf-8'), + b"/data", src_dspace) + vdset_y_offset += vdset_stripe_shape[1] + 10 + + # Create the virtual dataset + h5.h5d.create( + f.id, + name=b"data", + tid=h5.h5t.NATIVE_INT16, + space=virt_dspace, + dcpl=dcpl, + ) + assert(f['data'].fillvalue == 0x01) + + with h5.File(outfile,'r') as f: + d = f['data'] + self.assertEqual(d[3,100,0], 0.0) + self.assertEqual(d[3,260,0], 1.0) + self.assertEqual(d[3,350,0], 3.0) + self.assertEqual(d[3,650,0], 6.0) + self.assertEqual(d[3,900,0], 9.0) + self.assertEqual(d[3,1150,0], 12.0) + self.assertEqual(d[3,1450,0], 15.0) + + def tearDown(self): + self.working_dir.cleanup() + +''' +Unit test for the low level vds interface for percival +https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf +''' + + +class TestPercivalLowLevel(ut.TestCase): + + def setUp(self): + self.working_dir = tempfile.TemporaryDirectory() + self.fname = ['raw_file_1.h5','raw_file_2.h5','raw_file_3.h5'] + k = 0 + for outfile in self.fname: + filename = osp.join(self.working_dir.name, outfile) + with h5.File(filename,'w') as f: + f['data'] = np.ones((20,200,200))*k + k +=1 + + with h5.File(osp.join(self.working_dir.name, 'raw_file_4.h5'),'w') as f: + f['data'] = np.ones((19,200,200))*3 + self.fname.append('raw_file_4.h5') + self.fname = [osp.join(self.working_dir.name, ix) for ix in self.fname] + + def test_percival_low_level(self): + outfile = osp.join(self.working_dir.name, 'percival.h5') + + with h5.File(outfile, 'w', libver='latest') as f: + vdset_shape = (1,200,200) + num = h5.h5s.UNLIMITED + vdset_max_shape = (num,)+vdset_shape[1:] + virt_dspace = h5.h5s.create_simple(vdset_shape, vdset_max_shape) + dcpl = h5.h5p.create(h5.h5p.DATASET_CREATE) + dcpl.set_fill_value(np.array([-1])) + # Create the source dataset dataspace + k = 0 + for foo in self.fname: + with h5.File(foo, 'r') as in_f: + src_shape = in_f['data'].shape + max_src_shape = (num,)+src_shape[1:] + src_dspace = h5.h5s.create_simple(src_shape, max_src_shape) + # Select the source dataset hyperslab + src_dspace.select_hyperslab(start=(0, 0, 0), + stride=(1,1,1), + count=(num, 1, 1), + block=(1,)+src_shape[1:]) + + virt_dspace.select_hyperslab(start=(k, 0, 0), + stride=(4,1,1), + count=(num, 1, 1), + block=(1,)+src_shape[1:]) + + dcpl.set_virtual(virt_dspace, foo.encode('utf-8'), b'data', src_dspace) + k+=1 + + # Create the virtual dataset + h5.h5d.create( + f.id, + name=b"data", + tid=h5.h5t.NATIVE_INT16, + space=virt_dspace, + dcpl=dcpl, + ) + + with h5.File(outfile, 'r') as f: + sh = f['data'].shape + line = f['data'][:8,100,100] + foo = np.array(2*list(range(4))) + self.assertEqual(sh,(79,200,200),) + np.testing.assert_array_equal(line,foo) + + def tearDown(self): + self.working_dir.cleanup() + + +def test_virtual_prefix(tmp_path): + a = tmp_path / 'a' + b = tmp_path / 'b' + a.mkdir() + b.mkdir() + src_file = h5.File(a / 'src.h5', 'w') + src_file['data'] = np.arange(10) + + vds_file = h5.File(b / 'vds.h5', 'w') + layout = h5.VirtualLayout(shape=(10,), dtype=np.int64) + layout[:] = h5.VirtualSource('src.h5', 'data', shape=(10,)) + vds_file.create_virtual_dataset('data', layout, fillvalue=-1) + + # Path doesn't resolve + np.testing.assert_array_equal(vds_file['data'], np.full(10, fill_value=-1)) + + a_bytes = bytes(a) + dapl = h5.h5p.create(h5.h5p.DATASET_ACCESS) + dapl.set_virtual_prefix(a_bytes) + vds_id = h5.h5d.open(vds_file.id, b'data', dapl=dapl) + vds = h5.Dataset(vds_id) + + # Now it should find the source file and read the data correctly + np.testing.assert_array_equal(vds[:], np.arange(10)) + # Check that get_virtual_prefix gives back what we put in + assert vds.id.get_access_plist().get_virtual_prefix() == a_bytes + + src_file.close() + vds_file.close() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_vds/test_virtual_source.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_vds/test_virtual_source.py new file mode 100644 index 0000000000000000000000000000000000000000..3cef1654732e9f77965cddb82b03c460e735611e --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/tests/test_vds/test_virtual_source.py @@ -0,0 +1,166 @@ +from ..common import ut +import h5py as h5 +import numpy as np + + +class TestVirtualSource(ut.TestCase): + def test_full_slice(self): + dataset = h5.VirtualSource('test','test',(20,30,30)) + sliced = dataset[:,:,:] + self.assertEqual(dataset.shape,sliced.shape) + + # def test_full_slice_inverted(self): + # dataset = h5.VirtualSource('test','test',(20,30,30)) + # sliced = dataset[:,:,::-1] + # self.assertEqual(dataset.shape,sliced.shape) + # + # def test_subsampled_slice_inverted(self): + # dataset = h5.VirtualSource('test','test',(20,30,30)) + # sliced = dataset[:,:,::-2] + # self.assertEqual((20,30,15),sliced.shape) + + def test_integer_indexed(self): + dataset = h5.VirtualSource('test','test',(20,30,30)) + sliced = dataset[5,:,:] + self.assertEqual((30,30),sliced.shape) + + def test_integer_single_indexed(self): + dataset = h5.VirtualSource('test','test',(20,30,30)) + sliced = dataset[5] + self.assertEqual((30,30),sliced.shape) + + def test_two_integer_indexed(self): + dataset = h5.VirtualSource('test','test',(20,30,30)) + sliced = dataset[5,:,10] + self.assertEqual((30,),sliced.shape) + + def test_single_range(self): + dataset = h5.VirtualSource('test','test',(20,30,30)) + sliced = dataset[5:10,:,:] + self.assertEqual((5,)+dataset.shape[1:],sliced.shape) + + def test_shape_calculation_positive_step(self): + dataset = h5.VirtualSource('test','test',(20,)) + cmp = [] + for i in range(5): + d = dataset[2:12+i:3].shape[0] + ref = np.arange(20)[2:12+i:3].size + cmp.append(ref==d) + self.assertEqual(5, sum(cmp)) + + # def test_shape_calculation_positive_step_switched_start_stop(self): + # dataset = h5.VirtualSource('test','test',(20,)) + # cmp = [] + # for i in range(5): + # d = dataset[12+i:2:3].shape[0] + # ref = np.arange(20)[12+i:2:3].size + # cmp.append(ref==d) + # self.assertEqual(5, sum(cmp)) + # + # + # def test_shape_calculation_negative_step(self): + # dataset = h5.VirtualSource('test','test',(20,)) + # cmp = [] + # for i in range(5): + # d = dataset[12+i:2:-3].shape[0] + # ref = np.arange(20)[12+i:2:-3].size + # cmp.append(ref==d) + # self.assertEqual(5, sum(cmp)) + # + # def test_shape_calculation_negative_step_switched_start_stop(self): + # dataset = h5.VirtualSource('test','test',(20,)) + # cmp = [] + # for i in range(5): + # d = dataset[2:12+i:-3].shape[0] + # ref = np.arange(20)[2:12+i:-3].size + # cmp.append(ref==d) + # self.assertEqual(5, sum(cmp)) + + + def test_double_range(self): + dataset = h5.VirtualSource('test','test',(20,30,30)) + sliced = dataset[5:10,:,20:25] + self.assertEqual((5,30,5),sliced.shape) + + def test_double_strided_range(self): + dataset = h5.VirtualSource('test','test',(20,30,30)) + sliced = dataset[6:12:2,:,20:26:3] + self.assertEqual((3,30,2,),sliced.shape) + + # def test_double_strided_range_inverted(self): + # dataset = h5.VirtualSource('test','test',(20,30,30)) + # sliced = dataset[12:6:-2,:,26:20:-3] + # self.assertEqual((3,30,2),sliced.shape) + + def test_negative_start_index(self): + dataset = h5.VirtualSource('test','test',(20,30,30)) + sliced = dataset[-10:16] + self.assertEqual((6,30,30),sliced.shape) + + def test_negative_stop_index(self): + dataset = h5.VirtualSource('test','test',(20,30,30)) + sliced = dataset[10:-4] + self.assertEqual((6,30,30),sliced.shape) + + def test_negative_start_and_stop_index(self): + dataset = h5.VirtualSource('test','test',(20,30,30)) + sliced = dataset[-10:-4] + self.assertEqual((6,30,30),sliced.shape) + + # def test_negative_start_and_stop_and_stride_index(self): + # dataset = h5.VirtualSource('test','test',(20,30,30)) + # sliced = dataset[-4:-10:-2] + # self.assertEqual((3,30,30),sliced.shape) +# + def test_ellipsis(self): + dataset = h5.VirtualSource('test','test',(20,30,30)) + sliced = dataset[...] + self.assertEqual(dataset.shape,sliced.shape) + + def test_ellipsis_end(self): + dataset = h5.VirtualSource('test','test',(20,30,30)) + sliced = dataset[0:1,...] + self.assertEqual((1,)+dataset.shape[1:],sliced.shape) + + def test_ellipsis_start(self): + dataset = h5.VirtualSource('test','test',(20,30,30)) + sliced = dataset[...,0:1] + self.assertEqual(dataset.shape[:-1]+(1,),sliced.shape) + + def test_ellipsis_sandwich(self): + dataset = h5.VirtualSource('test','test',(20,30,30,40)) + sliced = dataset[0:1,...,5:6] + self.assertEqual((1,)+dataset.shape[1:-1]+(1,),sliced.shape) + + def test_integer_shape(self): + dataset = h5.VirtualSource('test','test', 20) + self.assertEqual(dataset.shape, (20,)) + + def test_integer_maxshape(self): + dataset = h5.VirtualSource('test','test', 20, maxshape=30) + self.assertEqual(dataset.maxshape, (30,)) + + def test_extra_args(self): + with h5.File(name='f1', driver='core', + backing_store=False, mode='w') as ftest: + ftest['a'] = [1, 2, 3] + a = ftest['a'] + + with self.assertRaises(TypeError): + h5.VirtualSource(a, 'b') + with self.assertRaises(TypeError): + h5.VirtualSource(a, shape=(1, )) + with self.assertRaises(TypeError): + h5.VirtualSource(a, maxshape=(None,)) + with self.assertRaises(TypeError): + h5.VirtualSource(a, dtype=int) + + def test_repeated_slice(self): + dataset = h5.VirtualSource('test', 'test', (20, 30, 30)) + sliced = dataset[5:10, :, :] + with self.assertRaises(RuntimeError): + sliced[:, :4] + + +if __name__ == "__main__": + ut.main() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/utils.cpython-311-x86_64-linux-gnu.so b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/utils.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e975bac2ba76fc1e7bd5edaedb0631f842007238 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/utils.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:13e12b607185fe00e03a69bcfcb4cd8507efdfdb0ae808b616d770b1bf7a175d +size 179625 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/version.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/version.py new file mode 100644 index 0000000000000000000000000000000000000000..3eb09f43ec16b0c1b1eb36a55752c388bbdee321 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/h5py/version.py @@ -0,0 +1,65 @@ +# This file is part of h5py, a Python interface to the HDF5 library. +# +# http://www.h5py.org +# +# Copyright 2008-2013 Andrew Collette and contributors +# +# License: Standard 3-clause BSD; see "license.txt" for full license terms +# and contributor agreement. + +""" + Versioning module for h5py. +""" + +from collections import namedtuple +from . import h5 as _h5 +import sys +import numpy + +# All should be integers, except pre, as validating versions is more than is +# needed for our use case +_H5PY_VERSION_CLS = namedtuple("_H5PY_VERSION_CLS", + "major minor bugfix pre post dev") + +hdf5_built_version_tuple = _h5.HDF5_VERSION_COMPILED_AGAINST + +version_tuple = _H5PY_VERSION_CLS(3, 15, 1, None, None, None) + +version = "{0.major:d}.{0.minor:d}.{0.bugfix:d}".format(version_tuple) +if version_tuple.pre is not None: + version += version_tuple.pre +if version_tuple.post is not None: + version += ".post{0.post:d}".format(version_tuple) +if version_tuple.dev is not None: + version += ".dev{0.dev:d}".format(version_tuple) + +hdf5_version_tuple = _h5.get_libversion() +hdf5_version = "%d.%d.%d" % hdf5_version_tuple + +api_version_tuple = (1,8) +api_version = "%d.%d" % api_version_tuple + +info = """\ +Summary of the h5py configuration +--------------------------------- + +h5py %(h5py)s +HDF5 %(hdf5)s +Python %(python)s +sys.platform %(platform)s +sys.maxsize %(maxsize)s +numpy %(numpy)s +cython (built with) %(cython_version)s +numpy (built against) %(numpy_build_version)s +HDF5 (built against) %(hdf5_build_version)s +""" % { + 'h5py': version, + 'hdf5': hdf5_version, + 'python': sys.version, + 'platform': sys.platform, + 'maxsize': sys.maxsize, + 'numpy': numpy.__version__, + 'cython_version': _h5.CYTHON_VERSION_COMPILED_WITH, + 'numpy_build_version': _h5.NUMPY_VERSION_COMPILED_AGAINST, + 'hdf5_build_version': "%d.%d.%d" % hdf5_built_version_tuple, +} diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources-6.5.2.dist-info/LICENSE b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources-6.5.2.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources-6.5.2.dist-info/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/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources-6.5.2.dist-info/METADATA b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources-6.5.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..474de805f5246d56df404f506b3106729e582665 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources-6.5.2.dist-info/METADATA @@ -0,0 +1,103 @@ +Metadata-Version: 2.1 +Name: importlib_resources +Version: 6.5.2 +Summary: Read resources from Python packages +Author-email: Barry Warsaw +Maintainer-email: "Jason R. Coombs" +Project-URL: Source, https://github.com/python/importlib_resources +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: zipp>=3.1.0; python_version < "3.10" +Provides-Extra: test +Requires-Dist: pytest!=8.1.*,>=6; extra == "test" +Requires-Dist: zipp>=3.17; extra == "test" +Requires-Dist: jaraco.test>=5.4; extra == "test" +Provides-Extra: doc +Requires-Dist: sphinx>=3.5; extra == "doc" +Requires-Dist: jaraco.packaging>=9.3; extra == "doc" +Requires-Dist: rst.linker>=1.9; extra == "doc" +Requires-Dist: furo; extra == "doc" +Requires-Dist: sphinx-lint; extra == "doc" +Requires-Dist: jaraco.tidelift>=1.4; extra == "doc" +Provides-Extra: check +Requires-Dist: pytest-checkdocs>=2.4; extra == "check" +Requires-Dist: pytest-ruff>=0.2.1; sys_platform != "cygwin" and extra == "check" +Provides-Extra: cover +Requires-Dist: pytest-cov; extra == "cover" +Provides-Extra: enabler +Requires-Dist: pytest-enabler>=2.2; extra == "enabler" +Provides-Extra: type +Requires-Dist: pytest-mypy; extra == "type" + +.. image:: https://img.shields.io/pypi/v/importlib_resources.svg + :target: https://pypi.org/project/importlib_resources + +.. image:: https://img.shields.io/pypi/pyversions/importlib_resources.svg + +.. image:: https://github.com/python/importlib_resources/actions/workflows/main.yml/badge.svg + :target: https://github.com/python/importlib_resources/actions?query=workflow%3A%22tests%22 + :alt: tests + +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff + +.. image:: https://readthedocs.org/projects/importlib-resources/badge/?version=latest + :target: https://importlib-resources.readthedocs.io/en/latest/?badge=latest + +.. image:: https://img.shields.io/badge/skeleton-2025-informational + :target: https://blog.jaraco.com/skeleton + +.. image:: https://tidelift.com/badges/package/pypi/importlib-resources + :target: https://tidelift.com/subscription/pkg/pypi-importlib-resources?utm_source=pypi-importlib-resources&utm_medium=readme + +``importlib_resources`` is a backport of Python standard library +`importlib.resources +`_ +module for older Pythons. + +The key goal of this module is to replace parts of `pkg_resources +`_ with a +solution in Python's stdlib that relies on well-defined APIs. This makes +reading resources included in packages easier, with more stable and consistent +semantics. + +Compatibility +============= + +New features are introduced in this third-party library and later merged +into CPython. The following table indicates which versions of this library +were contributed to different versions in the standard library: + +.. list-table:: + :header-rows: 1 + + * - importlib_resources + - stdlib + * - 6.0 + - 3.13 + * - 5.12 + - 3.12 + * - 5.7 + - 3.11 + * - 5.0 + - 3.10 + * - 1.3 + - 3.9 + * - 0.5 (?) + - 3.7 + +For Enterprise +============== + +Available as part of the Tidelift Subscription. + +This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. + +`Learn more `_. diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources-6.5.2.dist-info/RECORD b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources-6.5.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..ef28cfb793d7d01aa582e3c1e0963c3058202e7d --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources-6.5.2.dist-info/RECORD @@ -0,0 +1,36 @@ +importlib_resources-6.5.2.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +importlib_resources-6.5.2.dist-info/METADATA,sha256=yglT_7S_PsrSQaVTgZKQYfomaUlD-pV74f_9Ld0RjoY,3947 +importlib_resources-6.5.2.dist-info/RECORD,, +importlib_resources-6.5.2.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91 +importlib_resources-6.5.2.dist-info/top_level.txt,sha256=fHIjHU1GZwAjvcydpmUnUrTnbvdiWjG4OEVZK8by0TQ,20 +importlib_resources/__init__.py,sha256=F6SOMZILiez96lK3h9duE_c5kRTEydzHvI6D7TRcOJE,700 +importlib_resources/_adapters.py,sha256=vprJGbUeHbajX6XCuMP6J3lMrqCi-P_MTlziJUR7jfk,4482 +importlib_resources/_common.py,sha256=Vfmmdk5ICrZ8odgfWEuUHG-P7ZbJ-5x3pRLCVwVk8Tg,5624 +importlib_resources/_functional.py,sha256=nMop9Zc7g1Yhiyk5oqr9ukvfJcOx4vnvqD7nh24hV7Y,2743 +importlib_resources/_itertools.py,sha256=eDisV6RqiNZOogLSXf6LOGHOYc79FGgPrKNLzFLmCrU,1277 +importlib_resources/abc.py,sha256=inhYsYj6LrYHn4kCraZq8zqXFQnDX4stNnLTruhf6NU,5549 +importlib_resources/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_resources/compat/py39.py,sha256=gx5NE25XH1pQrTRJDY7QJUngZpD7OotsK9F6pZy5KjM,151 +importlib_resources/future/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_resources/future/adapters.py,sha256=UFIMxEuLo4PqcVbtoV3e_k9BcxCS-mmG22f8U2Vtkx4,3285 +importlib_resources/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_resources/readers.py,sha256=uHf9X-smA3CtxdB9IHWH0z-O53379wlcEMmzA2UXzqE,6250 +importlib_resources/simple.py,sha256=wJm2qGZ9EMPFhRLiJBa9Em5tVKbD7Q8ibWtt4ZNgWBU,2590 +importlib_resources/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_resources/tests/_path.py,sha256=IK3o6J_4UaN-4DPuwKr0lOb2KWpoUjwIyQkOtGqZWzs,2250 +importlib_resources/tests/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_resources/tests/compat/py312.py,sha256=qcWjpZhQo2oEsdwIlRRQHrsMGDltkFTnETeG7fLdUS8,364 +importlib_resources/tests/compat/py39.py,sha256=nOjut4CZDtRgZEblX9hWhupo9vli_CA1270_JwdQzRo,441 +importlib_resources/tests/test_compatibilty_files.py,sha256=cOLwa5kU6ucxNfiNsAQSpLHCE8asuqAHui6Aw9mxKX8,3313 +importlib_resources/tests/test_contents.py,sha256=r8kVH1k7DHrco2JVTUMCbsWK0JvvjKt0zgrmH56c4Vg,838 +importlib_resources/tests/test_custom.py,sha256=ep5mGT6uT6O1gPdM-b3mXo9HWDnCLD90uc4H1bU68oI,1222 +importlib_resources/tests/test_files.py,sha256=u4vMrXPpaWGJY8DyFJBkgg78lr_l9sfjzatP_7mkn88,5741 +importlib_resources/tests/test_functional.py,sha256=B3cFWFztSkMh4Y58MyOex_lcEooIPR-ezTaA9xzI6Y4,9070 +importlib_resources/tests/test_open.py,sha256=dT-cZmJoGbMMIVVWkNXt8KUxWcQn9Cd0emb85U4CiBA,2682 +importlib_resources/tests/test_path.py,sha256=orETYbmGyYNgXA8Dslj9MM3XjGUDRW8u4dJhIBy0qdU,1986 +importlib_resources/tests/test_read.py,sha256=o3uXJCUTYmUZeaFoQyXeRxTPpwhbjgRz-aALAg_btz8,3046 +importlib_resources/tests/test_reader.py,sha256=1RFB-rJs1hCDSy6qgv2z3LDm42gbQmj2n718CCdn1JY,4655 +importlib_resources/tests/test_resource.py,sha256=ZgpXCuYs4GZpSCElJyhZlMkb8oOfMZX1cnPLoinzis0,7687 +importlib_resources/tests/test_util.py,sha256=VotLNbngOyFg03FKVTzIZKd4Gz4UO-dMEr0G-vHMiuI,1105 +importlib_resources/tests/util.py,sha256=PKybGEyCo53mMu7A-5vC6n0e3nc9R8DS2NtvO-JCyxY,9804 +importlib_resources/tests/zip.py,sha256=nG9D6u_4nu67NrEUFfMt7vzba0qO_-QPyAAWc6W4gP4,577 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources-6.5.2.dist-info/WHEEL b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources-6.5.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ae527e7d64811439e61b93aa375defb30e06edfe --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources-6.5.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.6.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources-6.5.2.dist-info/top_level.txt b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources-6.5.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..58ad1bd333593cb544d1a6516e8e2849f094d09b --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources-6.5.2.dist-info/top_level.txt @@ -0,0 +1 @@ +importlib_resources diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..27d6c7f89307efe0eb4aa5dcca2b0f32c45fca96 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__init__.py @@ -0,0 +1,40 @@ +""" +Read resources contained within a package. + +This codebase is shared between importlib.resources in the stdlib +and importlib_resources in PyPI. See +https://github.com/python/importlib_metadata/wiki/Development-Methodology +for more detail. +""" + +from ._common import ( + Anchor, + Package, + as_file, + files, +) +from ._functional import ( + contents, + is_resource, + open_binary, + open_text, + path, + read_binary, + read_text, +) +from .abc import ResourceReader + +__all__ = [ + 'Package', + 'Anchor', + 'ResourceReader', + 'as_file', + 'files', + 'contents', + 'is_resource', + 'open_binary', + 'open_text', + 'path', + 'read_binary', + 'read_text', +] diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/__init__.cpython-311.pyc b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61fc478e80d9cf43a5f2eed27dd39b23d3386024 Binary files /dev/null and b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/__init__.cpython-311.pyc differ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/_adapters.cpython-311.pyc b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/_adapters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ce82c1b408f9419a42faa04426a0224faa05ce3 Binary files /dev/null and b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/_adapters.cpython-311.pyc differ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/_common.cpython-311.pyc b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/_common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f87c4bb49ea3c9e88779f856e51d2a13ae59024f Binary files /dev/null and b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/_common.cpython-311.pyc differ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/_functional.cpython-311.pyc b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/_functional.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e746f604c9cc3d41cdbb9c6e86855f21c9628c36 Binary files /dev/null and b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/_functional.cpython-311.pyc differ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/_itertools.cpython-311.pyc b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/_itertools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be6b4654b2ffc3b08b2dd0e42f21dd016deb6fa6 Binary files /dev/null and b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/_itertools.cpython-311.pyc differ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/abc.cpython-311.pyc b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/abc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05c9180c9537963dacc232b565a0d674b8ea4975 Binary files /dev/null and b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/abc.cpython-311.pyc differ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/readers.cpython-311.pyc b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/readers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d52436b956ee3e56e8c3e15e760322c253c3bc4 Binary files /dev/null and b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/__pycache__/readers.cpython-311.pyc differ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/_adapters.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..50688fbb666658c5b0569a363a4ea5b75f2fc00d --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/_adapters.py @@ -0,0 +1,168 @@ +from contextlib import suppress +from io import TextIOWrapper + +from . import abc + + +class SpecLoaderAdapter: + """ + Adapt a package spec to adapt the underlying loader. + """ + + def __init__(self, spec, adapter=lambda spec: spec.loader): + self.spec = spec + self.loader = adapter(spec) + + def __getattr__(self, name): + return getattr(self.spec, name) + + +class TraversableResourcesLoader: + """ + Adapt a loader to provide TraversableResources. + """ + + def __init__(self, spec): + self.spec = spec + + def get_resource_reader(self, name): + return CompatibilityFiles(self.spec)._native() + + +def _io_wrapper(file, mode='r', *args, **kwargs): + if mode == 'r': + return TextIOWrapper(file, *args, **kwargs) + elif mode == 'rb': + return file + raise ValueError(f"Invalid mode value '{mode}', only 'r' and 'rb' are supported") + + +class CompatibilityFiles: + """ + Adapter for an existing or non-existent resource reader + to provide a compatibility .files(). + """ + + class SpecPath(abc.Traversable): + """ + Path tied to a module spec. + Can be read and exposes the resource reader children. + """ + + def __init__(self, spec, reader): + self._spec = spec + self._reader = reader + + def iterdir(self): + if not self._reader: + return iter(()) + return iter( + CompatibilityFiles.ChildPath(self._reader, path) + for path in self._reader.contents() + ) + + def is_file(self): + return False + + is_dir = is_file + + def joinpath(self, other): + if not self._reader: + return CompatibilityFiles.OrphanPath(other) + return CompatibilityFiles.ChildPath(self._reader, other) + + @property + def name(self): + return self._spec.name + + def open(self, mode='r', *args, **kwargs): + return _io_wrapper(self._reader.open_resource(None), mode, *args, **kwargs) + + class ChildPath(abc.Traversable): + """ + Path tied to a resource reader child. + Can be read but doesn't expose any meaningful children. + """ + + def __init__(self, reader, name): + self._reader = reader + self._name = name + + def iterdir(self): + return iter(()) + + def is_file(self): + return self._reader.is_resource(self.name) + + def is_dir(self): + return not self.is_file() + + def joinpath(self, other): + return CompatibilityFiles.OrphanPath(self.name, other) + + @property + def name(self): + return self._name + + def open(self, mode='r', *args, **kwargs): + return _io_wrapper( + self._reader.open_resource(self.name), mode, *args, **kwargs + ) + + class OrphanPath(abc.Traversable): + """ + Orphan path, not tied to a module spec or resource reader. + Can't be read and doesn't expose any meaningful children. + """ + + def __init__(self, *path_parts): + if len(path_parts) < 1: + raise ValueError('Need at least one path part to construct a path') + self._path = path_parts + + def iterdir(self): + return iter(()) + + def is_file(self): + return False + + is_dir = is_file + + def joinpath(self, other): + return CompatibilityFiles.OrphanPath(*self._path, other) + + @property + def name(self): + return self._path[-1] + + def open(self, mode='r', *args, **kwargs): + raise FileNotFoundError("Can't open orphan path") + + def __init__(self, spec): + self.spec = spec + + @property + def _reader(self): + with suppress(AttributeError): + return self.spec.loader.get_resource_reader(self.spec.name) + + def _native(self): + """ + Return the native reader if it supports files(). + """ + reader = self._reader + return reader if hasattr(reader, 'files') else self + + def __getattr__(self, attr): + return getattr(self._reader, attr) + + def files(self): + return CompatibilityFiles.SpecPath(self.spec, self._reader) + + +def wrap_spec(package): + """ + Construct a package spec with traversable compatibility + on the spec/loader/reader. + """ + return SpecLoaderAdapter(package.__spec__, TraversableResourcesLoader) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/_common.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..5f41c26528d78a208524c8ef8e9a9ecc46f6ed78 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/_common.py @@ -0,0 +1,211 @@ +import contextlib +import functools +import importlib +import inspect +import itertools +import os +import pathlib +import tempfile +import types +import warnings +from typing import Optional, Union, cast + +from .abc import ResourceReader, Traversable + +Package = Union[types.ModuleType, str] +Anchor = Package + + +def package_to_anchor(func): + """ + Replace 'package' parameter as 'anchor' and warn about the change. + + Other errors should fall through. + + >>> files('a', 'b') + Traceback (most recent call last): + TypeError: files() takes from 0 to 1 positional arguments but 2 were given + + Remove this compatibility in Python 3.14. + """ + undefined = object() + + @functools.wraps(func) + def wrapper(anchor=undefined, package=undefined): + if package is not undefined: + if anchor is not undefined: + return func(anchor, package) + warnings.warn( + "First parameter to files is renamed to 'anchor'", + DeprecationWarning, + stacklevel=2, + ) + return func(package) + elif anchor is undefined: + return func() + return func(anchor) + + return wrapper + + +@package_to_anchor +def files(anchor: Optional[Anchor] = None) -> Traversable: + """ + Get a Traversable resource for an anchor. + """ + return from_package(resolve(anchor)) + + +def get_resource_reader(package: types.ModuleType) -> Optional[ResourceReader]: + """ + Return the package's loader if it's a ResourceReader. + """ + # We can't use + # a issubclass() check here because apparently abc.'s __subclasscheck__() + # hook wants to create a weak reference to the object, but + # zipimport.zipimporter does not support weak references, resulting in a + # TypeError. That seems terrible. + spec = package.__spec__ + reader = getattr(spec.loader, 'get_resource_reader', None) # type: ignore[union-attr] + if reader is None: + return None + return reader(spec.name) # type: ignore[union-attr] + + +@functools.singledispatch +def resolve(cand: Optional[Anchor]) -> types.ModuleType: + return cast(types.ModuleType, cand) + + +@resolve.register +def _(cand: str) -> types.ModuleType: + return importlib.import_module(cand) + + +@resolve.register +def _(cand: None) -> types.ModuleType: + return resolve(_infer_caller().f_globals['__name__']) + + +def _infer_caller(): + """ + Walk the stack and find the frame of the first caller not in this module. + """ + + def is_this_file(frame_info): + return frame_info.filename == stack[0].filename + + def is_wrapper(frame_info): + return frame_info.function == 'wrapper' + + stack = inspect.stack() + not_this_file = itertools.filterfalse(is_this_file, stack) + # also exclude 'wrapper' due to singledispatch in the call stack + callers = itertools.filterfalse(is_wrapper, not_this_file) + return next(callers).frame + + +def from_package(package: types.ModuleType): + """ + Return a Traversable object for the given package. + + """ + # deferred for performance (python/cpython#109829) + from .future.adapters import wrap_spec + + spec = wrap_spec(package) + reader = spec.loader.get_resource_reader(spec.name) + return reader.files() + + +@contextlib.contextmanager +def _tempfile( + reader, + suffix='', + # gh-93353: Keep a reference to call os.remove() in late Python + # finalization. + *, + _os_remove=os.remove, +): + # Not using tempfile.NamedTemporaryFile as it leads to deeper 'try' + # blocks due to the need to close the temporary file to work on Windows + # properly. + fd, raw_path = tempfile.mkstemp(suffix=suffix) + try: + try: + os.write(fd, reader()) + finally: + os.close(fd) + del reader + yield pathlib.Path(raw_path) + finally: + try: + _os_remove(raw_path) + except FileNotFoundError: + pass + + +def _temp_file(path): + return _tempfile(path.read_bytes, suffix=path.name) + + +def _is_present_dir(path: Traversable) -> bool: + """ + Some Traversables implement ``is_dir()`` to raise an + exception (i.e. ``FileNotFoundError``) when the + directory doesn't exist. This function wraps that call + to always return a boolean and only return True + if there's a dir and it exists. + """ + with contextlib.suppress(FileNotFoundError): + return path.is_dir() + return False + + +@functools.singledispatch +def as_file(path): + """ + Given a Traversable object, return that object as a + path on the local file system in a context manager. + """ + return _temp_dir(path) if _is_present_dir(path) else _temp_file(path) + + +@as_file.register(pathlib.Path) +@contextlib.contextmanager +def _(path): + """ + Degenerate behavior for pathlib.Path objects. + """ + yield path + + +@contextlib.contextmanager +def _temp_path(dir: tempfile.TemporaryDirectory): + """ + Wrap tempfile.TemporaryDirectory to return a pathlib object. + """ + with dir as result: + yield pathlib.Path(result) + + +@contextlib.contextmanager +def _temp_dir(path): + """ + Given a traversable dir, recursively replicate the whole tree + to the file system in a context manager. + """ + assert path.is_dir() + with _temp_path(tempfile.TemporaryDirectory()) as temp_dir: + yield _write_contents(temp_dir, path) + + +def _write_contents(target, source): + child = target.joinpath(source.name) + if source.is_dir(): + child.mkdir() + for item in source.iterdir(): + _write_contents(child, item) + else: + child.write_bytes(source.read_bytes()) + return child diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/_functional.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/_functional.py new file mode 100644 index 0000000000000000000000000000000000000000..b08a5c6efe22a234914ed33bdaa1ee0e2432e478 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/_functional.py @@ -0,0 +1,84 @@ +"""Simplified function-based API for importlib.resources""" + +import warnings + +from ._common import as_file, files +from .abc import TraversalError + +_MISSING = object() + + +def open_binary(anchor, *path_names): + """Open for binary reading the *resource* within *package*.""" + return _get_resource(anchor, path_names).open('rb') + + +def open_text(anchor, *path_names, encoding=_MISSING, errors='strict'): + """Open for text reading the *resource* within *package*.""" + encoding = _get_encoding_arg(path_names, encoding) + resource = _get_resource(anchor, path_names) + return resource.open('r', encoding=encoding, errors=errors) + + +def read_binary(anchor, *path_names): + """Read and return contents of *resource* within *package* as bytes.""" + return _get_resource(anchor, path_names).read_bytes() + + +def read_text(anchor, *path_names, encoding=_MISSING, errors='strict'): + """Read and return contents of *resource* within *package* as str.""" + encoding = _get_encoding_arg(path_names, encoding) + resource = _get_resource(anchor, path_names) + return resource.read_text(encoding=encoding, errors=errors) + + +def path(anchor, *path_names): + """Return the path to the *resource* as an actual file system path.""" + return as_file(_get_resource(anchor, path_names)) + + +def is_resource(anchor, *path_names): + """Return ``True`` if there is a resource named *name* in the package, + + Otherwise returns ``False``. + """ + try: + return _get_resource(anchor, path_names).is_file() + except TraversalError: + return False + + +def contents(anchor, *path_names): + """Return an iterable over the named resources within the package. + + The iterable returns :class:`str` resources (e.g. files). + The iterable does not recurse into subdirectories. + """ + warnings.warn( + "importlib.resources.contents is deprecated. " + "Use files(anchor).iterdir() instead.", + DeprecationWarning, + stacklevel=1, + ) + return (resource.name for resource in _get_resource(anchor, path_names).iterdir()) + + +def _get_encoding_arg(path_names, encoding): + # For compatibility with versions where *encoding* was a positional + # argument, it needs to be given explicitly when there are multiple + # *path_names*. + # This limitation can be removed in Python 3.15. + if encoding is _MISSING: + if len(path_names) > 1: + raise TypeError( + "'encoding' argument required with multiple path names", + ) + else: + return 'utf-8' + return encoding + + +def _get_resource(anchor, path_names): + if anchor is None: + raise TypeError("anchor must be module or string, got None") + return files(anchor).joinpath(*path_names) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/_itertools.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/_itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..7b775ef5ae893f2b8061c5f996dc0a15a4c72adb --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/_itertools.py @@ -0,0 +1,38 @@ +# from more_itertools 9.0 +def only(iterable, default=None, too_long=None): + """If *iterable* has only one item, return it. + If it has zero items, return *default*. + If it has more than one item, raise the exception given by *too_long*, + which is ``ValueError`` by default. + >>> only([], default='missing') + 'missing' + >>> only([1]) + 1 + >>> only([1, 2]) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + ValueError: Expected exactly one item in iterable, but got 1, 2, + and perhaps more.' + >>> only([1, 2], too_long=TypeError) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + TypeError + Note that :func:`only` attempts to advance *iterable* twice to ensure there + is only one item. See :func:`spy` or :func:`peekable` to check + iterable contents less destructively. + """ + it = iter(iterable) + first_value = next(it, default) + + try: + second_value = next(it) + except StopIteration: + pass + else: + msg = ( + 'Expected exactly one item in iterable, but got {!r}, {!r}, ' + 'and perhaps more.'.format(first_value, second_value) + ) + raise too_long or ValueError(msg) + + return first_value diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/abc.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..883d332836dedf4b74990f1ce5f3e32d056f8d93 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/abc.py @@ -0,0 +1,193 @@ +import abc +import itertools +import os +import pathlib +from typing import ( + Any, + BinaryIO, + Iterable, + Iterator, + NoReturn, + Literal, + Optional, + Protocol, + Text, + TextIO, + Union, + overload, + runtime_checkable, +) + +StrPath = Union[str, os.PathLike[str]] + +__all__ = ["ResourceReader", "Traversable", "TraversableResources"] + + +class ResourceReader(metaclass=abc.ABCMeta): + """Abstract base class for loaders to provide resource reading support.""" + + @abc.abstractmethod + def open_resource(self, resource: Text) -> BinaryIO: + """Return an opened, file-like object for binary reading. + + The 'resource' argument is expected to represent only a file name. + If the resource cannot be found, FileNotFoundError is raised. + """ + # This deliberately raises FileNotFoundError instead of + # NotImplementedError so that if this method is accidentally called, + # it'll still do the right thing. + raise FileNotFoundError + + @abc.abstractmethod + def resource_path(self, resource: Text) -> Text: + """Return the file system path to the specified resource. + + The 'resource' argument is expected to represent only a file name. + If the resource does not exist on the file system, raise + FileNotFoundError. + """ + # This deliberately raises FileNotFoundError instead of + # NotImplementedError so that if this method is accidentally called, + # it'll still do the right thing. + raise FileNotFoundError + + @abc.abstractmethod + def is_resource(self, path: Text) -> bool: + """Return True if the named 'path' is a resource. + + Files are resources, directories are not. + """ + raise FileNotFoundError + + @abc.abstractmethod + def contents(self) -> Iterable[str]: + """Return an iterable of entries in `package`.""" + raise FileNotFoundError + + +class TraversalError(Exception): + pass + + +@runtime_checkable +class Traversable(Protocol): + """ + An object with a subset of pathlib.Path methods suitable for + traversing directories and opening files. + + Any exceptions that occur when accessing the backing resource + may propagate unaltered. + """ + + @abc.abstractmethod + def iterdir(self) -> Iterator["Traversable"]: + """ + Yield Traversable objects in self + """ + + def read_bytes(self) -> bytes: + """ + Read contents of self as bytes + """ + with self.open('rb') as strm: + return strm.read() + + def read_text( + self, encoding: Optional[str] = None, errors: Optional[str] = None + ) -> str: + """ + Read contents of self as text + """ + with self.open(encoding=encoding, errors=errors) as strm: + return strm.read() + + @abc.abstractmethod + def is_dir(self) -> bool: + """ + Return True if self is a directory + """ + + @abc.abstractmethod + def is_file(self) -> bool: + """ + Return True if self is a file + """ + + def joinpath(self, *descendants: StrPath) -> "Traversable": + """ + Return Traversable resolved with any descendants applied. + + Each descendant should be a path segment relative to self + and each may contain multiple levels separated by + ``posixpath.sep`` (``/``). + """ + if not descendants: + return self + names = itertools.chain.from_iterable( + path.parts for path in map(pathlib.PurePosixPath, descendants) + ) + target = next(names) + matches = ( + traversable for traversable in self.iterdir() if traversable.name == target + ) + try: + match = next(matches) + except StopIteration: + raise TraversalError( + "Target not found during traversal.", target, list(names) + ) + return match.joinpath(*names) + + def __truediv__(self, child: StrPath) -> "Traversable": + """ + Return Traversable child in self + """ + return self.joinpath(child) + + @overload + def open(self, mode: Literal['r'] = 'r', *args: Any, **kwargs: Any) -> TextIO: ... + + @overload + def open(self, mode: Literal['rb'], *args: Any, **kwargs: Any) -> BinaryIO: ... + + @abc.abstractmethod + def open( + self, mode: str = 'r', *args: Any, **kwargs: Any + ) -> Union[TextIO, BinaryIO]: + """ + mode may be 'r' or 'rb' to open as text or binary. Return a handle + suitable for reading (same as pathlib.Path.open). + + When opening as text, accepts encoding parameters such as those + accepted by io.TextIOWrapper. + """ + + @property + @abc.abstractmethod + def name(self) -> str: + """ + The base name of this object without any parent references. + """ + + +class TraversableResources(ResourceReader): + """ + The required interface for providing traversable + resources. + """ + + @abc.abstractmethod + def files(self) -> "Traversable": + """Return a Traversable object for the loaded package.""" + + def open_resource(self, resource: StrPath) -> BinaryIO: + return self.files().joinpath(resource).open('rb') + + def resource_path(self, resource: Any) -> NoReturn: + raise FileNotFoundError(resource) + + def is_resource(self, path: StrPath) -> bool: + return self.files().joinpath(path).is_file() + + def contents(self) -> Iterator[str]: + return (item.name for item in self.files().iterdir()) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/compat/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/compat/__pycache__/__init__.cpython-311.pyc b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/compat/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14e33b5c9d32d238db06177b6e35b2128d5ce894 Binary files /dev/null and b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/compat/__pycache__/__init__.cpython-311.pyc differ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/compat/__pycache__/py39.cpython-311.pyc b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/compat/__pycache__/py39.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1f8daefec8e41a38b0ec04a5f50088f1380ae1c Binary files /dev/null and b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/compat/__pycache__/py39.cpython-311.pyc differ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/compat/py39.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/compat/py39.py new file mode 100644 index 0000000000000000000000000000000000000000..684d3c638311527c24350f29c9bcc93c142b210a --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/compat/py39.py @@ -0,0 +1,9 @@ +import sys + +__all__ = ['ZipPath'] + + +if sys.version_info >= (3, 10): + from zipfile import Path as ZipPath +else: + from zipp import Path as ZipPath diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/future/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/future/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/future/__pycache__/__init__.cpython-311.pyc b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/future/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a3168fe939a84a7c02ac46b49e2b6401218e2ac Binary files /dev/null and b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/future/__pycache__/__init__.cpython-311.pyc differ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/future/__pycache__/adapters.cpython-311.pyc b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/future/__pycache__/adapters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b1ab870bdcd4baabdae6484a6eed7d4a5c7e30c Binary files /dev/null and b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/future/__pycache__/adapters.cpython-311.pyc differ diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/future/adapters.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/future/adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..239e52b795fc45ae614d0f7f641b5b4c3f272740 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/future/adapters.py @@ -0,0 +1,102 @@ +import functools +import pathlib +from contextlib import suppress +from types import SimpleNamespace + +from .. import _adapters, readers + + +def _block_standard(reader_getter): + """ + Wrap _adapters.TraversableResourcesLoader.get_resource_reader + and intercept any standard library readers. + """ + + @functools.wraps(reader_getter) + def wrapper(*args, **kwargs): + """ + If the reader is from the standard library, return None to allow + allow likely newer implementations in this library to take precedence. + """ + try: + reader = reader_getter(*args, **kwargs) + except NotADirectoryError: + # MultiplexedPath may fail on zip subdirectory + return + except ValueError as exc: + # NamespaceReader in stdlib may fail for editable installs + # (python/importlib_resources#311, python/importlib_resources#318) + # Remove after bugfix applied to Python 3.13. + if "not enough values to unpack" not in str(exc): + raise + return + # Python 3.10+ + mod_name = reader.__class__.__module__ + if mod_name.startswith('importlib.') and mod_name.endswith('readers'): + return + # Python 3.8, 3.9 + if isinstance(reader, _adapters.CompatibilityFiles) and ( + reader.spec.loader.__class__.__module__.startswith('zipimport') + or reader.spec.loader.__class__.__module__.startswith( + '_frozen_importlib_external' + ) + ): + return + return reader + + return wrapper + + +def _skip_degenerate(reader): + """ + Mask any degenerate reader. Ref #298. + """ + is_degenerate = ( + isinstance(reader, _adapters.CompatibilityFiles) and not reader._reader + ) + return reader if not is_degenerate else None + + +class TraversableResourcesLoader(_adapters.TraversableResourcesLoader): + """ + Adapt loaders to provide TraversableResources and other + compatibility. + + Ensures the readers from importlib_resources are preferred + over stdlib readers. + """ + + def get_resource_reader(self, name): + return ( + _skip_degenerate(_block_standard(super().get_resource_reader)(name)) + or self._standard_reader() + or super().get_resource_reader(name) + ) + + def _standard_reader(self): + return self._zip_reader() or self._namespace_reader() or self._file_reader() + + def _zip_reader(self): + with suppress(AttributeError): + return readers.ZipReader(self.spec.loader, self.spec.name) + + def _namespace_reader(self): + with suppress(AttributeError, ValueError): + return readers.NamespaceReader(self.spec.submodule_search_locations) + + def _file_reader(self): + try: + path = pathlib.Path(self.spec.origin) + except TypeError: + return None + if path.exists(): + return readers.FileReader(SimpleNamespace(path=path)) + + +def wrap_spec(package): + """ + Override _adapters.wrap_spec to use TraversableResourcesLoader + from above. Ensures that future behavior is always available on older + Pythons. + """ + return _adapters.SpecLoaderAdapter(package.__spec__, TraversableResourcesLoader) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/py.typed b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/readers.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/readers.py new file mode 100644 index 0000000000000000000000000000000000000000..99884b6af93adcac5e91679f30fd4cf082451ada --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/readers.py @@ -0,0 +1,202 @@ +from __future__ import annotations + +import collections +import contextlib +import itertools +import operator +import pathlib +import re +import warnings +from collections.abc import Iterator + +from . import abc +from ._itertools import only +from .compat.py39 import ZipPath + + +def remove_duplicates(items): + return iter(collections.OrderedDict.fromkeys(items)) + + +class FileReader(abc.TraversableResources): + def __init__(self, loader): + self.path = pathlib.Path(loader.path).parent + + def resource_path(self, resource): + """ + Return the file system path to prevent + `resources.path()` from creating a temporary + copy. + """ + return str(self.path.joinpath(resource)) + + def files(self): + return self.path + + +class ZipReader(abc.TraversableResources): + def __init__(self, loader, module): + self.prefix = loader.prefix.replace('\\', '/') + if loader.is_package(module): + _, _, name = module.rpartition('.') + self.prefix += name + '/' + self.archive = loader.archive + + def open_resource(self, resource): + try: + return super().open_resource(resource) + except KeyError as exc: + raise FileNotFoundError(exc.args[0]) + + def is_resource(self, path): + """ + Workaround for `zipfile.Path.is_file` returning true + for non-existent paths. + """ + target = self.files().joinpath(path) + return target.is_file() and target.exists() + + def files(self): + return ZipPath(self.archive, self.prefix) + + +class MultiplexedPath(abc.Traversable): + """ + Given a series of Traversable objects, implement a merged + version of the interface across all objects. Useful for + namespace packages which may be multihomed at a single + name. + """ + + def __init__(self, *paths): + self._paths = list(map(_ensure_traversable, remove_duplicates(paths))) + if not self._paths: + message = 'MultiplexedPath must contain at least one path' + raise FileNotFoundError(message) + if not all(path.is_dir() for path in self._paths): + raise NotADirectoryError('MultiplexedPath only supports directories') + + def iterdir(self): + children = (child for path in self._paths for child in path.iterdir()) + by_name = operator.attrgetter('name') + groups = itertools.groupby(sorted(children, key=by_name), key=by_name) + return map(self._follow, (locs for name, locs in groups)) + + def read_bytes(self): + raise FileNotFoundError(f'{self} is not a file') + + def read_text(self, *args, **kwargs): + raise FileNotFoundError(f'{self} is not a file') + + def is_dir(self): + return True + + def is_file(self): + return False + + def joinpath(self, *descendants): + try: + return super().joinpath(*descendants) + except abc.TraversalError: + # One of the paths did not resolve (a directory does not exist). + # Just return something that will not exist. + return self._paths[0].joinpath(*descendants) + + @classmethod + def _follow(cls, children): + """ + Construct a MultiplexedPath if needed. + + If children contains a sole element, return it. + Otherwise, return a MultiplexedPath of the items. + Unless one of the items is not a Directory, then return the first. + """ + subdirs, one_dir, one_file = itertools.tee(children, 3) + + try: + return only(one_dir) + except ValueError: + try: + return cls(*subdirs) + except NotADirectoryError: + return next(one_file) + + def open(self, *args, **kwargs): + raise FileNotFoundError(f'{self} is not a file') + + @property + def name(self): + return self._paths[0].name + + def __repr__(self): + paths = ', '.join(f"'{path}'" for path in self._paths) + return f'MultiplexedPath({paths})' + + +class NamespaceReader(abc.TraversableResources): + def __init__(self, namespace_path): + if 'NamespacePath' not in str(namespace_path): + raise ValueError('Invalid path') + self.path = MultiplexedPath(*filter(bool, map(self._resolve, namespace_path))) + + @classmethod + def _resolve(cls, path_str) -> abc.Traversable | None: + r""" + Given an item from a namespace path, resolve it to a Traversable. + + path_str might be a directory on the filesystem or a path to a + zipfile plus the path within the zipfile, e.g. ``/foo/bar`` or + ``/foo/baz.zip/inner_dir`` or ``foo\baz.zip\inner_dir\sub``. + + path_str might also be a sentinel used by editable packages to + trigger other behaviors (see python/importlib_resources#311). + In that case, return None. + """ + dirs = (cand for cand in cls._candidate_paths(path_str) if cand.is_dir()) + return next(dirs, None) + + @classmethod + def _candidate_paths(cls, path_str: str) -> Iterator[abc.Traversable]: + yield pathlib.Path(path_str) + yield from cls._resolve_zip_path(path_str) + + @staticmethod + def _resolve_zip_path(path_str: str): + for match in reversed(list(re.finditer(r'[\\/]', path_str))): + with contextlib.suppress( + FileNotFoundError, + IsADirectoryError, + NotADirectoryError, + PermissionError, + ): + inner = path_str[match.end() :].replace('\\', '/') + '/' + yield ZipPath(path_str[: match.start()], inner.lstrip('/')) + + def resource_path(self, resource): + """ + Return the file system path to prevent + `resources.path()` from creating a temporary + copy. + """ + return str(self.path.joinpath(resource)) + + def files(self): + return self.path + + +def _ensure_traversable(path): + """ + Convert deprecated string arguments to traversables (pathlib.Path). + + Remove with Python 3.15. + """ + if not isinstance(path, str): + return path + + warnings.warn( + "String arguments are deprecated. Pass a Traversable instead.", + DeprecationWarning, + stacklevel=3, + ) + + return pathlib.Path(path) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/simple.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/simple.py new file mode 100644 index 0000000000000000000000000000000000000000..2e75299b13aabf3dd11aea5a23e6723d67854fc9 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/simple.py @@ -0,0 +1,106 @@ +""" +Interface adapters for low-level readers. +""" + +import abc +import io +import itertools +from typing import BinaryIO, List + +from .abc import Traversable, TraversableResources + + +class SimpleReader(abc.ABC): + """ + The minimum, low-level interface required from a resource + provider. + """ + + @property + @abc.abstractmethod + def package(self) -> str: + """ + The name of the package for which this reader loads resources. + """ + + @abc.abstractmethod + def children(self) -> List['SimpleReader']: + """ + Obtain an iterable of SimpleReader for available + child containers (e.g. directories). + """ + + @abc.abstractmethod + def resources(self) -> List[str]: + """ + Obtain available named resources for this virtual package. + """ + + @abc.abstractmethod + def open_binary(self, resource: str) -> BinaryIO: + """ + Obtain a File-like for a named resource. + """ + + @property + def name(self): + return self.package.split('.')[-1] + + +class ResourceContainer(Traversable): + """ + Traversable container for a package's resources via its reader. + """ + + def __init__(self, reader: SimpleReader): + self.reader = reader + + def is_dir(self): + return True + + def is_file(self): + return False + + def iterdir(self): + files = (ResourceHandle(self, name) for name in self.reader.resources) + dirs = map(ResourceContainer, self.reader.children()) + return itertools.chain(files, dirs) + + def open(self, *args, **kwargs): + raise IsADirectoryError() + + +class ResourceHandle(Traversable): + """ + Handle to a named resource in a ResourceReader. + """ + + def __init__(self, parent: ResourceContainer, name: str): + self.parent = parent + self.name = name # type: ignore[misc] + + def is_file(self): + return True + + def is_dir(self): + return False + + def open(self, mode='r', *args, **kwargs): + stream = self.parent.reader.open_binary(self.name) + if 'b' not in mode: + stream = io.TextIOWrapper(stream, *args, **kwargs) + return stream + + def joinpath(self, name): + raise RuntimeError("Cannot traverse into a resource") + + +class TraversableReader(TraversableResources, SimpleReader): + """ + A TraversableResources based on SimpleReader. Resource providers + may derive from this class to provide the TraversableResources + interface by supplying the SimpleReader interface. + """ + + def files(self): + return ResourceContainer(self) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/_path.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/_path.py new file mode 100644 index 0000000000000000000000000000000000000000..0033983dc6628682481023ce3e15b64171423ba8 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/_path.py @@ -0,0 +1,90 @@ +import functools +import pathlib +from typing import Dict, Protocol, Union, runtime_checkable + +#### +# from jaraco.path 3.7.1 + + +class Symlink(str): + """ + A string indicating the target of a symlink. + """ + + +FilesSpec = Dict[str, Union[str, bytes, Symlink, 'FilesSpec']] + + +@runtime_checkable +class TreeMaker(Protocol): + def __truediv__(self, *args, **kwargs): ... # pragma: no cover + + def mkdir(self, **kwargs): ... # pragma: no cover + + def write_text(self, content, **kwargs): ... # pragma: no cover + + def write_bytes(self, content): ... # pragma: no cover + + def symlink_to(self, target): ... # pragma: no cover + + +def _ensure_tree_maker(obj: Union[str, TreeMaker]) -> TreeMaker: + return obj if isinstance(obj, TreeMaker) else pathlib.Path(obj) # type: ignore[return-value] + + +def build( + spec: FilesSpec, + prefix: Union[str, TreeMaker] = pathlib.Path(), # type: ignore[assignment] +): + """ + Build a set of files/directories, as described by the spec. + + Each key represents a pathname, and the value represents + the content. Content may be a nested directory. + + >>> spec = { + ... 'README.txt': "A README file", + ... "foo": { + ... "__init__.py": "", + ... "bar": { + ... "__init__.py": "", + ... }, + ... "baz.py": "# Some code", + ... "bar.py": Symlink("baz.py"), + ... }, + ... "bing": Symlink("foo"), + ... } + >>> target = getfixture('tmp_path') + >>> build(spec, target) + >>> target.joinpath('foo/baz.py').read_text(encoding='utf-8') + '# Some code' + >>> target.joinpath('bing/bar.py').read_text(encoding='utf-8') + '# Some code' + """ + for name, contents in spec.items(): + create(contents, _ensure_tree_maker(prefix) / name) + + +@functools.singledispatch +def create(content: Union[str, bytes, FilesSpec], path): + path.mkdir(exist_ok=True) + build(content, prefix=path) # type: ignore[arg-type] + + +@create.register +def _(content: bytes, path): + path.write_bytes(content) + + +@create.register +def _(content: str, path): + path.write_text(content, encoding='utf-8') + + +@create.register +def _(content: Symlink, path): + path.symlink_to(content) + + +# end from jaraco.path +#### diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/compat/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/compat/py312.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/compat/py312.py new file mode 100644 index 0000000000000000000000000000000000000000..ea9a58ba2e5c6bfeac1c5b7ae768d8f4197a29a8 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/compat/py312.py @@ -0,0 +1,18 @@ +import contextlib + +from .py39 import import_helper + + +@contextlib.contextmanager +def isolated_modules(): + """ + Save modules on entry and cleanup on exit. + """ + (saved,) = import_helper.modules_setup() + try: + yield + finally: + import_helper.modules_cleanup(saved) + + +vars(import_helper).setdefault('isolated_modules', isolated_modules) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/compat/py39.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/compat/py39.py new file mode 100644 index 0000000000000000000000000000000000000000..e01d276bd96ef5d823946b84b74d3af2710d26f9 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/compat/py39.py @@ -0,0 +1,13 @@ +""" +Backward-compatability shims to support Python 3.9 and earlier. +""" + +from jaraco.test.cpython import from_test_support, try_import + +import_helper = try_import('import_helper') or from_test_support( + 'modules_setup', 'modules_cleanup', 'DirsOnSysPath' +) +os_helper = try_import('os_helper') or from_test_support('temp_dir') +warnings_helper = try_import('warnings_helper') or from_test_support( + 'ignore_warnings', 'check_warnings' +) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_compatibilty_files.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_compatibilty_files.py new file mode 100644 index 0000000000000000000000000000000000000000..e8aac28415883cff131502da954eab8505da6ec6 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_compatibilty_files.py @@ -0,0 +1,103 @@ +import io +import unittest + +import importlib_resources as resources +from importlib_resources._adapters import ( + CompatibilityFiles, + wrap_spec, +) + +from . import util + + +class CompatibilityFilesTests(unittest.TestCase): + @property + def package(self): + bytes_data = io.BytesIO(b'Hello, world!') + return util.create_package( + file=bytes_data, + path='some_path', + contents=('a', 'b', 'c'), + ) + + @property + def files(self): + return resources.files(self.package) + + def test_spec_path_iter(self): + self.assertEqual( + sorted(path.name for path in self.files.iterdir()), + ['a', 'b', 'c'], + ) + + def test_child_path_iter(self): + self.assertEqual(list((self.files / 'a').iterdir()), []) + + def test_orphan_path_iter(self): + self.assertEqual(list((self.files / 'a' / 'a').iterdir()), []) + self.assertEqual(list((self.files / 'a' / 'a' / 'a').iterdir()), []) + + def test_spec_path_is(self): + self.assertFalse(self.files.is_file()) + self.assertFalse(self.files.is_dir()) + + def test_child_path_is(self): + self.assertTrue((self.files / 'a').is_file()) + self.assertFalse((self.files / 'a').is_dir()) + + def test_orphan_path_is(self): + self.assertFalse((self.files / 'a' / 'a').is_file()) + self.assertFalse((self.files / 'a' / 'a').is_dir()) + self.assertFalse((self.files / 'a' / 'a' / 'a').is_file()) + self.assertFalse((self.files / 'a' / 'a' / 'a').is_dir()) + + def test_spec_path_name(self): + self.assertEqual(self.files.name, 'testingpackage') + + def test_child_path_name(self): + self.assertEqual((self.files / 'a').name, 'a') + + def test_orphan_path_name(self): + self.assertEqual((self.files / 'a' / 'b').name, 'b') + self.assertEqual((self.files / 'a' / 'b' / 'c').name, 'c') + + def test_spec_path_open(self): + self.assertEqual(self.files.read_bytes(), b'Hello, world!') + self.assertEqual(self.files.read_text(encoding='utf-8'), 'Hello, world!') + + def test_child_path_open(self): + self.assertEqual((self.files / 'a').read_bytes(), b'Hello, world!') + self.assertEqual( + (self.files / 'a').read_text(encoding='utf-8'), 'Hello, world!' + ) + + def test_orphan_path_open(self): + with self.assertRaises(FileNotFoundError): + (self.files / 'a' / 'b').read_bytes() + with self.assertRaises(FileNotFoundError): + (self.files / 'a' / 'b' / 'c').read_bytes() + + def test_open_invalid_mode(self): + with self.assertRaises(ValueError): + self.files.open('0') + + def test_orphan_path_invalid(self): + with self.assertRaises(ValueError): + CompatibilityFiles.OrphanPath() + + def test_wrap_spec(self): + spec = wrap_spec(self.package) + self.assertIsInstance(spec.loader.get_resource_reader(None), CompatibilityFiles) + + +class CompatibilityFilesNoReaderTests(unittest.TestCase): + @property + def package(self): + return util.create_package_from_loader(None) + + @property + def files(self): + return resources.files(self.package) + + def test_spec_path_joinpath(self): + self.assertIsInstance(self.files / 'a', CompatibilityFiles.OrphanPath) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_contents.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_contents.py new file mode 100644 index 0000000000000000000000000000000000000000..dcb872ec05fd05a266ee5a4b69e3ade31fa1cc0d --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_contents.py @@ -0,0 +1,39 @@ +import unittest + +import importlib_resources as resources + +from . import util + + +class ContentsTests: + expected = { + '__init__.py', + 'binary.file', + 'subdirectory', + 'utf-16.file', + 'utf-8.file', + } + + def test_contents(self): + contents = {path.name for path in resources.files(self.data).iterdir()} + assert self.expected <= contents + + +class ContentsDiskTests(ContentsTests, util.DiskSetup, unittest.TestCase): + pass + + +class ContentsZipTests(ContentsTests, util.ZipSetup, unittest.TestCase): + pass + + +class ContentsNamespaceTests(ContentsTests, util.DiskSetup, unittest.TestCase): + MODULE = 'namespacedata01' + + expected = { + # no __init__ because of namespace design + 'binary.file', + 'subdirectory', + 'utf-16.file', + 'utf-8.file', + } diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_custom.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_custom.py new file mode 100644 index 0000000000000000000000000000000000000000..25ae0e75784d9021aea6d089206fe87b05ee8831 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_custom.py @@ -0,0 +1,48 @@ +import contextlib +import pathlib +import unittest + +import importlib_resources as resources + +from .. import abc +from ..abc import ResourceReader, TraversableResources +from . import util +from .compat.py39 import os_helper + + +class SimpleLoader: + """ + A simple loader that only implements a resource reader. + """ + + def __init__(self, reader: ResourceReader): + self.reader = reader + + def get_resource_reader(self, package): + return self.reader + + +class MagicResources(TraversableResources): + """ + Magically returns the resources at path. + """ + + def __init__(self, path: pathlib.Path): + self.path = path + + def files(self): + return self.path + + +class CustomTraversableResourcesTests(unittest.TestCase): + def setUp(self): + self.fixtures = contextlib.ExitStack() + self.addCleanup(self.fixtures.close) + + def test_custom_loader(self): + temp_dir = pathlib.Path(self.fixtures.enter_context(os_helper.temp_dir())) + loader = SimpleLoader(MagicResources(temp_dir)) + pkg = util.create_package_from_loader(loader) + files = resources.files(pkg) + assert isinstance(files, abc.Traversable) + assert list(files.iterdir()) == [] diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_files.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_files.py new file mode 100644 index 0000000000000000000000000000000000000000..be20660313029aab66a34800aac12bf65c9c0469 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_files.py @@ -0,0 +1,194 @@ +import contextlib +import importlib +import pathlib +import py_compile +import textwrap +import unittest +import warnings + +import importlib_resources as resources + +from ..abc import Traversable +from . import util +from .compat.py39 import import_helper, os_helper + + +@contextlib.contextmanager +def suppress_known_deprecation(): + with warnings.catch_warnings(record=True) as ctx: + warnings.simplefilter('default', category=DeprecationWarning) + yield ctx + + +class FilesTests: + def test_read_bytes(self): + files = resources.files(self.data) + actual = files.joinpath('utf-8.file').read_bytes() + assert actual == b'Hello, UTF-8 world!\n' + + def test_read_text(self): + files = resources.files(self.data) + actual = files.joinpath('utf-8.file').read_text(encoding='utf-8') + assert actual == 'Hello, UTF-8 world!\n' + + def test_traversable(self): + assert isinstance(resources.files(self.data), Traversable) + + def test_joinpath_with_multiple_args(self): + files = resources.files(self.data) + binfile = files.joinpath('subdirectory', 'binary.file') + self.assertTrue(binfile.is_file()) + + def test_old_parameter(self): + """ + Files used to take a 'package' parameter. Make sure anyone + passing by name is still supported. + """ + with suppress_known_deprecation(): + resources.files(package=self.data) + + +class OpenDiskTests(FilesTests, util.DiskSetup, unittest.TestCase): + pass + + +class OpenZipTests(FilesTests, util.ZipSetup, unittest.TestCase): + pass + + +class OpenNamespaceTests(FilesTests, util.DiskSetup, unittest.TestCase): + MODULE = 'namespacedata01' + + def test_non_paths_in_dunder_path(self): + """ + Non-path items in a namespace package's ``__path__`` are ignored. + + As reported in python/importlib_resources#311, some tools + like Setuptools, when creating editable packages, will inject + non-paths into a namespace package's ``__path__``, a + sentinel like + ``__editable__.sample_namespace-1.0.finder.__path_hook__`` + to cause the ``PathEntryFinder`` to be called when searching + for packages. In that case, resources should still be loadable. + """ + import namespacedata01 # type: ignore[import-not-found] + + namespacedata01.__path__.append( + '__editable__.sample_namespace-1.0.finder.__path_hook__' + ) + + resources.files(namespacedata01) + + +class OpenNamespaceZipTests(FilesTests, util.ZipSetup, unittest.TestCase): + ZIP_MODULE = 'namespacedata01' + + +class DirectSpec: + """ + Override behavior of ModuleSetup to write a full spec directly. + """ + + MODULE = 'unused' + + def load_fixture(self, name): + self.tree_on_path(self.spec) + + +class ModulesFiles: + spec = { + 'mod.py': '', + 'res.txt': 'resources are the best', + } + + def test_module_resources(self): + """ + A module can have resources found adjacent to the module. + """ + import mod # type: ignore[import-not-found] + + actual = resources.files(mod).joinpath('res.txt').read_text(encoding='utf-8') + assert actual == self.spec['res.txt'] + + +class ModuleFilesDiskTests(DirectSpec, util.DiskSetup, ModulesFiles, unittest.TestCase): + pass + + +class ModuleFilesZipTests(DirectSpec, util.ZipSetup, ModulesFiles, unittest.TestCase): + pass + + +class ImplicitContextFiles: + set_val = textwrap.dedent( + f""" + import {resources.__name__} as res + val = res.files().joinpath('res.txt').read_text(encoding='utf-8') + """ + ) + spec = { + 'somepkg': { + '__init__.py': set_val, + 'submod.py': set_val, + 'res.txt': 'resources are the best', + }, + 'frozenpkg': { + '__init__.py': set_val.replace(resources.__name__, 'c_resources'), + 'res.txt': 'resources are the best', + }, + } + + def test_implicit_files_package(self): + """ + Without any parameter, files() will infer the location as the caller. + """ + assert importlib.import_module('somepkg').val == 'resources are the best' + + def test_implicit_files_submodule(self): + """ + Without any parameter, files() will infer the location as the caller. + """ + assert importlib.import_module('somepkg.submod').val == 'resources are the best' + + def _compile_importlib(self): + """ + Make a compiled-only copy of the importlib resources package. + + Currently only code is copied, as importlib resources doesn't itself + have any resources. + """ + bin_site = self.fixtures.enter_context(os_helper.temp_dir()) + c_resources = pathlib.Path(bin_site, 'c_resources') + sources = pathlib.Path(resources.__file__).parent + + for source_path in sources.glob('**/*.py'): + c_path = c_resources.joinpath(source_path.relative_to(sources)).with_suffix( + '.pyc' + ) + py_compile.compile(source_path, c_path) + self.fixtures.enter_context(import_helper.DirsOnSysPath(bin_site)) + + def test_implicit_files_with_compiled_importlib(self): + """ + Caller detection works for compiled-only resources module. + + python/cpython#123085 + """ + self._compile_importlib() + assert importlib.import_module('frozenpkg').val == 'resources are the best' + + +class ImplicitContextFilesDiskTests( + DirectSpec, util.DiskSetup, ImplicitContextFiles, unittest.TestCase +): + pass + + +class ImplicitContextFilesZipTests( + DirectSpec, util.ZipSetup, ImplicitContextFiles, unittest.TestCase +): + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_functional.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_functional.py new file mode 100644 index 0000000000000000000000000000000000000000..9eb2d8153fc78ef208f98209651fd78e77187d80 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_functional.py @@ -0,0 +1,267 @@ +import importlib +import os +import unittest + +import importlib_resources as resources + +from . import util +from .compat.py39 import warnings_helper + + +class StringAnchorMixin: + anchor01 = 'data01' + anchor02 = 'data02' + + +class ModuleAnchorMixin: + @property + def anchor01(self): + return importlib.import_module('data01') + + @property + def anchor02(self): + return importlib.import_module('data02') + + +class FunctionalAPIBase: + def setUp(self): + super().setUp() + self.load_fixture('data02') + + def _gen_resourcetxt_path_parts(self): + """Yield various names of a text file in anchor02, each in a subTest""" + for path_parts in ( + ('subdirectory', 'subsubdir', 'resource.txt'), + ('subdirectory/subsubdir/resource.txt',), + ('subdirectory/subsubdir', 'resource.txt'), + ): + with self.subTest(path_parts=path_parts): + yield path_parts + + def assertEndsWith(self, string, suffix): + """Assert that `string` ends with `suffix`. + + Used to ignore an architecture-specific UTF-16 byte-order mark.""" + self.assertEqual(string[-len(suffix) :], suffix) + + def test_read_text(self): + self.assertEqual( + resources.read_text(self.anchor01, 'utf-8.file'), + 'Hello, UTF-8 world!\n', + ) + self.assertEqual( + resources.read_text( + self.anchor02, + 'subdirectory', + 'subsubdir', + 'resource.txt', + encoding='utf-8', + ), + 'a resource', + ) + for path_parts in self._gen_resourcetxt_path_parts(): + self.assertEqual( + resources.read_text( + self.anchor02, + *path_parts, + encoding='utf-8', + ), + 'a resource', + ) + # Use generic OSError, since e.g. attempting to read a directory can + # fail with PermissionError rather than IsADirectoryError + with self.assertRaises(OSError): + resources.read_text(self.anchor01) + with self.assertRaises((OSError, resources.abc.TraversalError)): + resources.read_text(self.anchor01, 'no-such-file') + with self.assertRaises(UnicodeDecodeError): + resources.read_text(self.anchor01, 'utf-16.file') + self.assertEqual( + resources.read_text( + self.anchor01, + 'binary.file', + encoding='latin1', + ), + '\x00\x01\x02\x03', + ) + self.assertEndsWith( # ignore the BOM + resources.read_text( + self.anchor01, + 'utf-16.file', + errors='backslashreplace', + ), + 'Hello, UTF-16 world!\n'.encode('utf-16-le').decode( + errors='backslashreplace', + ), + ) + + def test_read_binary(self): + self.assertEqual( + resources.read_binary(self.anchor01, 'utf-8.file'), + b'Hello, UTF-8 world!\n', + ) + for path_parts in self._gen_resourcetxt_path_parts(): + self.assertEqual( + resources.read_binary(self.anchor02, *path_parts), + b'a resource', + ) + + def test_open_text(self): + with resources.open_text(self.anchor01, 'utf-8.file') as f: + self.assertEqual(f.read(), 'Hello, UTF-8 world!\n') + for path_parts in self._gen_resourcetxt_path_parts(): + with resources.open_text( + self.anchor02, + *path_parts, + encoding='utf-8', + ) as f: + self.assertEqual(f.read(), 'a resource') + # Use generic OSError, since e.g. attempting to read a directory can + # fail with PermissionError rather than IsADirectoryError + with self.assertRaises(OSError): + resources.open_text(self.anchor01) + with self.assertRaises((OSError, resources.abc.TraversalError)): + resources.open_text(self.anchor01, 'no-such-file') + with resources.open_text(self.anchor01, 'utf-16.file') as f: + with self.assertRaises(UnicodeDecodeError): + f.read() + with resources.open_text( + self.anchor01, + 'binary.file', + encoding='latin1', + ) as f: + self.assertEqual(f.read(), '\x00\x01\x02\x03') + with resources.open_text( + self.anchor01, + 'utf-16.file', + errors='backslashreplace', + ) as f: + self.assertEndsWith( # ignore the BOM + f.read(), + 'Hello, UTF-16 world!\n'.encode('utf-16-le').decode( + errors='backslashreplace', + ), + ) + + def test_open_binary(self): + with resources.open_binary(self.anchor01, 'utf-8.file') as f: + self.assertEqual(f.read(), b'Hello, UTF-8 world!\n') + for path_parts in self._gen_resourcetxt_path_parts(): + with resources.open_binary( + self.anchor02, + *path_parts, + ) as f: + self.assertEqual(f.read(), b'a resource') + + def test_path(self): + with resources.path(self.anchor01, 'utf-8.file') as path: + with open(str(path), encoding='utf-8') as f: + self.assertEqual(f.read(), 'Hello, UTF-8 world!\n') + with resources.path(self.anchor01) as path: + with open(os.path.join(path, 'utf-8.file'), encoding='utf-8') as f: + self.assertEqual(f.read(), 'Hello, UTF-8 world!\n') + + def test_is_resource(self): + is_resource = resources.is_resource + self.assertTrue(is_resource(self.anchor01, 'utf-8.file')) + self.assertFalse(is_resource(self.anchor01, 'no_such_file')) + self.assertFalse(is_resource(self.anchor01)) + self.assertFalse(is_resource(self.anchor01, 'subdirectory')) + for path_parts in self._gen_resourcetxt_path_parts(): + self.assertTrue(is_resource(self.anchor02, *path_parts)) + + def test_contents(self): + with warnings_helper.check_warnings((".*contents.*", DeprecationWarning)): + c = resources.contents(self.anchor01) + self.assertGreaterEqual( + set(c), + {'utf-8.file', 'utf-16.file', 'binary.file', 'subdirectory'}, + ) + with ( + self.assertRaises(OSError), + warnings_helper.check_warnings(( + ".*contents.*", + DeprecationWarning, + )), + ): + list(resources.contents(self.anchor01, 'utf-8.file')) + + for path_parts in self._gen_resourcetxt_path_parts(): + with ( + self.assertRaises((OSError, resources.abc.TraversalError)), + warnings_helper.check_warnings(( + ".*contents.*", + DeprecationWarning, + )), + ): + list(resources.contents(self.anchor01, *path_parts)) + with warnings_helper.check_warnings((".*contents.*", DeprecationWarning)): + c = resources.contents(self.anchor01, 'subdirectory') + self.assertGreaterEqual( + set(c), + {'binary.file'}, + ) + + @warnings_helper.ignore_warnings(category=DeprecationWarning) + def test_common_errors(self): + for func in ( + resources.read_text, + resources.read_binary, + resources.open_text, + resources.open_binary, + resources.path, + resources.is_resource, + resources.contents, + ): + with self.subTest(func=func): + # Rejecting None anchor + with self.assertRaises(TypeError): + func(None) + # Rejecting invalid anchor type + with self.assertRaises((TypeError, AttributeError)): + func(1234) + # Unknown module + with self.assertRaises(ModuleNotFoundError): + func('$missing module$') + + def test_text_errors(self): + for func in ( + resources.read_text, + resources.open_text, + ): + with self.subTest(func=func): + # Multiple path arguments need explicit encoding argument. + with self.assertRaises(TypeError): + func( + self.anchor02, + 'subdirectory', + 'subsubdir', + 'resource.txt', + ) + + +class FunctionalAPITest_StringAnchor_Disk( + StringAnchorMixin, + FunctionalAPIBase, + util.DiskSetup, + unittest.TestCase, +): + pass + + +class FunctionalAPITest_ModuleAnchor_Disk( + ModuleAnchorMixin, + FunctionalAPIBase, + util.DiskSetup, + unittest.TestCase, +): + pass + + +class FunctionalAPITest_StringAnchor_Memory( + StringAnchorMixin, + FunctionalAPIBase, + util.MemorySetup, + unittest.TestCase, +): + pass diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_open.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_open.py new file mode 100644 index 0000000000000000000000000000000000000000..8a4b68e32ccb265c2dbcf6fae937b038d0037c17 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_open.py @@ -0,0 +1,85 @@ +import unittest + +import importlib_resources as resources + +from . import util + + +class CommonBinaryTests(util.CommonTests, unittest.TestCase): + def execute(self, package, path): + target = resources.files(package).joinpath(path) + with target.open('rb'): + pass + + +class CommonTextTests(util.CommonTests, unittest.TestCase): + def execute(self, package, path): + target = resources.files(package).joinpath(path) + with target.open(encoding='utf-8'): + pass + + +class OpenTests: + def test_open_binary(self): + target = resources.files(self.data) / 'binary.file' + with target.open('rb') as fp: + result = fp.read() + self.assertEqual(result, bytes(range(4))) + + def test_open_text_default_encoding(self): + target = resources.files(self.data) / 'utf-8.file' + with target.open(encoding='utf-8') as fp: + result = fp.read() + self.assertEqual(result, 'Hello, UTF-8 world!\n') + + def test_open_text_given_encoding(self): + target = resources.files(self.data) / 'utf-16.file' + with target.open(encoding='utf-16', errors='strict') as fp: + result = fp.read() + self.assertEqual(result, 'Hello, UTF-16 world!\n') + + def test_open_text_with_errors(self): + """ + Raises UnicodeError without the 'errors' argument. + """ + target = resources.files(self.data) / 'utf-16.file' + with target.open(encoding='utf-8', errors='strict') as fp: + self.assertRaises(UnicodeError, fp.read) + with target.open(encoding='utf-8', errors='ignore') as fp: + result = fp.read() + self.assertEqual( + result, + 'H\x00e\x00l\x00l\x00o\x00,\x00 ' + '\x00U\x00T\x00F\x00-\x001\x006\x00 ' + '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00', + ) + + def test_open_binary_FileNotFoundError(self): + target = resources.files(self.data) / 'does-not-exist' + with self.assertRaises(FileNotFoundError): + target.open('rb') + + def test_open_text_FileNotFoundError(self): + target = resources.files(self.data) / 'does-not-exist' + with self.assertRaises(FileNotFoundError): + target.open(encoding='utf-8') + + +class OpenDiskTests(OpenTests, util.DiskSetup, unittest.TestCase): + pass + + +class OpenDiskNamespaceTests(OpenTests, util.DiskSetup, unittest.TestCase): + MODULE = 'namespacedata01' + + +class OpenZipTests(OpenTests, util.ZipSetup, unittest.TestCase): + pass + + +class OpenNamespaceZipTests(OpenTests, util.ZipSetup, unittest.TestCase): + MODULE = 'namespacedata01' + + +if __name__ == '__main__': + unittest.main() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_path.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_path.py new file mode 100644 index 0000000000000000000000000000000000000000..0be673d2b1f1b34be9ffa1e19fbdaa31d2a31b5b --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_path.py @@ -0,0 +1,63 @@ +import io +import pathlib +import unittest + +import importlib_resources as resources + +from . import util + + +class CommonTests(util.CommonTests, unittest.TestCase): + def execute(self, package, path): + with resources.as_file(resources.files(package).joinpath(path)): + pass + + +class PathTests: + def test_reading(self): + """ + Path should be readable and a pathlib.Path instance. + """ + target = resources.files(self.data) / 'utf-8.file' + with resources.as_file(target) as path: + self.assertIsInstance(path, pathlib.Path) + self.assertTrue(path.name.endswith("utf-8.file"), repr(path)) + self.assertEqual('Hello, UTF-8 world!\n', path.read_text(encoding='utf-8')) + + +class PathDiskTests(PathTests, util.DiskSetup, unittest.TestCase): + def test_natural_path(self): + """ + Guarantee the internal implementation detail that + file-system-backed resources do not get the tempdir + treatment. + """ + target = resources.files(self.data) / 'utf-8.file' + with resources.as_file(target) as path: + assert 'data' in str(path) + + +class PathMemoryTests(PathTests, unittest.TestCase): + def setUp(self): + file = io.BytesIO(b'Hello, UTF-8 world!\n') + self.addCleanup(file.close) + self.data = util.create_package( + file=file, path=FileNotFoundError("package exists only in memory") + ) + self.data.__spec__.origin = None + self.data.__spec__.has_location = False + + +class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase): + def test_remove_in_context_manager(self): + """ + It is not an error if the file that was temporarily stashed on the + file system is removed inside the `with` stanza. + """ + target = resources.files(self.data) / 'utf-8.file' + with resources.as_file(target) as path: + path.unlink() + + +if __name__ == '__main__': + unittest.main() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_read.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_read.py new file mode 100644 index 0000000000000000000000000000000000000000..216c8feb1476075556bcd1986f20aa35123417b5 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_read.py @@ -0,0 +1,94 @@ +import unittest +from importlib import import_module + +import importlib_resources as resources + +from . import util + + +class CommonBinaryTests(util.CommonTests, unittest.TestCase): + def execute(self, package, path): + resources.files(package).joinpath(path).read_bytes() + + +class CommonTextTests(util.CommonTests, unittest.TestCase): + def execute(self, package, path): + resources.files(package).joinpath(path).read_text(encoding='utf-8') + + +class ReadTests: + def test_read_bytes(self): + result = resources.files(self.data).joinpath('binary.file').read_bytes() + self.assertEqual(result, bytes(range(4))) + + def test_read_text_default_encoding(self): + result = ( + resources.files(self.data) + .joinpath('utf-8.file') + .read_text(encoding='utf-8') + ) + self.assertEqual(result, 'Hello, UTF-8 world!\n') + + def test_read_text_given_encoding(self): + result = ( + resources.files(self.data) + .joinpath('utf-16.file') + .read_text(encoding='utf-16') + ) + self.assertEqual(result, 'Hello, UTF-16 world!\n') + + def test_read_text_with_errors(self): + """ + Raises UnicodeError without the 'errors' argument. + """ + target = resources.files(self.data) / 'utf-16.file' + self.assertRaises(UnicodeError, target.read_text, encoding='utf-8') + result = target.read_text(encoding='utf-8', errors='ignore') + self.assertEqual( + result, + 'H\x00e\x00l\x00l\x00o\x00,\x00 ' + '\x00U\x00T\x00F\x00-\x001\x006\x00 ' + '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00', + ) + + +class ReadDiskTests(ReadTests, util.DiskSetup, unittest.TestCase): + pass + + +class ReadZipTests(ReadTests, util.ZipSetup, unittest.TestCase): + def test_read_submodule_resource(self): + submodule = import_module('data01.subdirectory') + result = resources.files(submodule).joinpath('binary.file').read_bytes() + self.assertEqual(result, bytes(range(4, 8))) + + def test_read_submodule_resource_by_name(self): + result = ( + resources.files('data01.subdirectory').joinpath('binary.file').read_bytes() + ) + self.assertEqual(result, bytes(range(4, 8))) + + +class ReadNamespaceTests(ReadTests, util.DiskSetup, unittest.TestCase): + MODULE = 'namespacedata01' + + +class ReadNamespaceZipTests(ReadTests, util.ZipSetup, unittest.TestCase): + MODULE = 'namespacedata01' + + def test_read_submodule_resource(self): + submodule = import_module('namespacedata01.subdirectory') + result = resources.files(submodule).joinpath('binary.file').read_bytes() + self.assertEqual(result, bytes(range(12, 16))) + + def test_read_submodule_resource_by_name(self): + result = ( + resources.files('namespacedata01.subdirectory') + .joinpath('binary.file') + .read_bytes() + ) + self.assertEqual(result, bytes(range(12, 16))) + + +if __name__ == '__main__': + unittest.main() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_reader.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..f8cfd8dea0618d62de74ed380731788192d68552 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_reader.py @@ -0,0 +1,137 @@ +import os.path +import pathlib +import unittest +from importlib import import_module + +from importlib_resources.readers import MultiplexedPath, NamespaceReader + +from . import util + + +class MultiplexedPathTest(util.DiskSetup, unittest.TestCase): + MODULE = 'namespacedata01' + + def setUp(self): + super().setUp() + self.folder = pathlib.Path(self.data.__path__[0]) + self.data01 = pathlib.Path(self.load_fixture('data01').__file__).parent + self.data02 = pathlib.Path(self.load_fixture('data02').__file__).parent + + def test_init_no_paths(self): + with self.assertRaises(FileNotFoundError): + MultiplexedPath() + + def test_init_file(self): + with self.assertRaises(NotADirectoryError): + MultiplexedPath(self.folder / 'binary.file') + + def test_iterdir(self): + contents = {path.name for path in MultiplexedPath(self.folder).iterdir()} + try: + contents.remove('__pycache__') + except (KeyError, ValueError): + pass + self.assertEqual( + contents, {'subdirectory', 'binary.file', 'utf-16.file', 'utf-8.file'} + ) + + def test_iterdir_duplicate(self): + contents = { + path.name for path in MultiplexedPath(self.folder, self.data01).iterdir() + } + for remove in ('__pycache__', '__init__.pyc'): + try: + contents.remove(remove) + except (KeyError, ValueError): + pass + self.assertEqual( + contents, + {'__init__.py', 'binary.file', 'subdirectory', 'utf-16.file', 'utf-8.file'}, + ) + + def test_is_dir(self): + self.assertEqual(MultiplexedPath(self.folder).is_dir(), True) + + def test_is_file(self): + self.assertEqual(MultiplexedPath(self.folder).is_file(), False) + + def test_open_file(self): + path = MultiplexedPath(self.folder) + with self.assertRaises(FileNotFoundError): + path.read_bytes() + with self.assertRaises(FileNotFoundError): + path.read_text() + with self.assertRaises(FileNotFoundError): + path.open() + + def test_join_path(self): + prefix = str(self.folder.parent) + path = MultiplexedPath(self.folder, self.data01) + self.assertEqual( + str(path.joinpath('binary.file'))[len(prefix) + 1 :], + os.path.join('namespacedata01', 'binary.file'), + ) + sub = path.joinpath('subdirectory') + assert isinstance(sub, MultiplexedPath) + assert 'namespacedata01' in str(sub) + assert 'data01' in str(sub) + self.assertEqual( + str(path.joinpath('imaginary'))[len(prefix) + 1 :], + os.path.join('namespacedata01', 'imaginary'), + ) + self.assertEqual(path.joinpath(), path) + + def test_join_path_compound(self): + path = MultiplexedPath(self.folder) + assert not path.joinpath('imaginary/foo.py').exists() + + def test_join_path_common_subdir(self): + prefix = str(self.data02.parent) + path = MultiplexedPath(self.data01, self.data02) + self.assertIsInstance(path.joinpath('subdirectory'), MultiplexedPath) + self.assertEqual( + str(path.joinpath('subdirectory', 'subsubdir'))[len(prefix) + 1 :], + os.path.join('data02', 'subdirectory', 'subsubdir'), + ) + + def test_repr(self): + self.assertEqual( + repr(MultiplexedPath(self.folder)), + f"MultiplexedPath('{self.folder}')", + ) + + def test_name(self): + self.assertEqual( + MultiplexedPath(self.folder).name, + os.path.basename(self.folder), + ) + + +class NamespaceReaderTest(util.DiskSetup, unittest.TestCase): + MODULE = 'namespacedata01' + + def test_init_error(self): + with self.assertRaises(ValueError): + NamespaceReader(['path1', 'path2']) + + def test_resource_path(self): + namespacedata01 = import_module('namespacedata01') + reader = NamespaceReader(namespacedata01.__spec__.submodule_search_locations) + + root = self.data.__path__[0] + self.assertEqual( + reader.resource_path('binary.file'), os.path.join(root, 'binary.file') + ) + self.assertEqual( + reader.resource_path('imaginary'), os.path.join(root, 'imaginary') + ) + + def test_files(self): + reader = NamespaceReader(self.data.__spec__.submodule_search_locations) + root = self.data.__path__[0] + self.assertIsInstance(reader.files(), MultiplexedPath) + self.assertEqual(repr(reader.files()), f"MultiplexedPath('{root}')") + + +if __name__ == '__main__': + unittest.main() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_resource.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_resource.py new file mode 100644 index 0000000000000000000000000000000000000000..c80afdc729ec90ac8c3c47aa594533ed8897342f --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_resource.py @@ -0,0 +1,238 @@ +import unittest +from importlib import import_module + +import importlib_resources as resources + +from . import util + + +class ResourceTests: + # Subclasses are expected to set the `data` attribute. + + def test_is_file_exists(self): + target = resources.files(self.data) / 'binary.file' + self.assertTrue(target.is_file()) + + def test_is_file_missing(self): + target = resources.files(self.data) / 'not-a-file' + self.assertFalse(target.is_file()) + + def test_is_dir(self): + target = resources.files(self.data) / 'subdirectory' + self.assertFalse(target.is_file()) + self.assertTrue(target.is_dir()) + + +class ResourceDiskTests(ResourceTests, util.DiskSetup, unittest.TestCase): + pass + + +class ResourceZipTests(ResourceTests, util.ZipSetup, unittest.TestCase): + pass + + +def names(traversable): + return {item.name for item in traversable.iterdir()} + + +class ResourceLoaderTests(util.DiskSetup, unittest.TestCase): + def test_resource_contents(self): + package = util.create_package( + file=self.data, path=self.data.__file__, contents=['A', 'B', 'C'] + ) + self.assertEqual(names(resources.files(package)), {'A', 'B', 'C'}) + + def test_is_file(self): + package = util.create_package( + file=self.data, + path=self.data.__file__, + contents=['A', 'B', 'C', 'D/E', 'D/F'], + ) + self.assertTrue(resources.files(package).joinpath('B').is_file()) + + def test_is_dir(self): + package = util.create_package( + file=self.data, + path=self.data.__file__, + contents=['A', 'B', 'C', 'D/E', 'D/F'], + ) + self.assertTrue(resources.files(package).joinpath('D').is_dir()) + + def test_resource_missing(self): + package = util.create_package( + file=self.data, + path=self.data.__file__, + contents=['A', 'B', 'C', 'D/E', 'D/F'], + ) + self.assertFalse(resources.files(package).joinpath('Z').is_file()) + + +class ResourceCornerCaseTests(util.DiskSetup, unittest.TestCase): + def test_package_has_no_reader_fallback(self): + """ + Test odd ball packages which: + # 1. Do not have a ResourceReader as a loader + # 2. Are not on the file system + # 3. Are not in a zip file + """ + module = util.create_package( + file=self.data, path=self.data.__file__, contents=['A', 'B', 'C'] + ) + # Give the module a dummy loader. + module.__loader__ = object() + # Give the module a dummy origin. + module.__file__ = '/path/which/shall/not/be/named' + module.__spec__.loader = module.__loader__ + module.__spec__.origin = module.__file__ + self.assertFalse(resources.files(module).joinpath('A').is_file()) + + +class ResourceFromZipsTest01(util.ZipSetup, unittest.TestCase): + def test_is_submodule_resource(self): + submodule = import_module('data01.subdirectory') + self.assertTrue(resources.files(submodule).joinpath('binary.file').is_file()) + + def test_read_submodule_resource_by_name(self): + self.assertTrue( + resources.files('data01.subdirectory').joinpath('binary.file').is_file() + ) + + def test_submodule_contents(self): + submodule = import_module('data01.subdirectory') + self.assertEqual( + names(resources.files(submodule)), {'__init__.py', 'binary.file'} + ) + + def test_submodule_contents_by_name(self): + self.assertEqual( + names(resources.files('data01.subdirectory')), + {'__init__.py', 'binary.file'}, + ) + + def test_as_file_directory(self): + with resources.as_file(resources.files('data01')) as data: + assert data.name == 'data01' + assert data.is_dir() + assert data.joinpath('subdirectory').is_dir() + assert len(list(data.iterdir())) + assert not data.parent.exists() + + +class ResourceFromZipsTest02(util.ZipSetup, unittest.TestCase): + MODULE = 'data02' + + def test_unrelated_contents(self): + """ + Test thata zip with two unrelated subpackages return + distinct resources. Ref python/importlib_resources#44. + """ + self.assertEqual( + names(resources.files('data02.one')), + {'__init__.py', 'resource1.txt'}, + ) + self.assertEqual( + names(resources.files('data02.two')), + {'__init__.py', 'resource2.txt'}, + ) + + +class DeletingZipsTest(util.ZipSetup, unittest.TestCase): + """Having accessed resources in a zip file should not keep an open + reference to the zip. + """ + + def test_iterdir_does_not_keep_open(self): + [item.name for item in resources.files('data01').iterdir()] + + def test_is_file_does_not_keep_open(self): + resources.files('data01').joinpath('binary.file').is_file() + + def test_is_file_failure_does_not_keep_open(self): + resources.files('data01').joinpath('not-present').is_file() + + @unittest.skip("Desired but not supported.") + def test_as_file_does_not_keep_open(self): # pragma: no cover + resources.as_file(resources.files('data01') / 'binary.file') + + def test_entered_path_does_not_keep_open(self): + """ + Mimic what certifi does on import to make its bundle + available for the process duration. + """ + resources.as_file(resources.files('data01') / 'binary.file').__enter__() + + def test_read_binary_does_not_keep_open(self): + resources.files('data01').joinpath('binary.file').read_bytes() + + def test_read_text_does_not_keep_open(self): + resources.files('data01').joinpath('utf-8.file').read_text(encoding='utf-8') + + +class ResourceFromNamespaceTests: + def test_is_submodule_resource(self): + self.assertTrue( + resources.files(import_module('namespacedata01')) + .joinpath('binary.file') + .is_file() + ) + + def test_read_submodule_resource_by_name(self): + self.assertTrue( + resources.files('namespacedata01').joinpath('binary.file').is_file() + ) + + def test_submodule_contents(self): + contents = names(resources.files(import_module('namespacedata01'))) + try: + contents.remove('__pycache__') + except KeyError: + pass + self.assertEqual( + contents, {'subdirectory', 'binary.file', 'utf-8.file', 'utf-16.file'} + ) + + def test_submodule_contents_by_name(self): + contents = names(resources.files('namespacedata01')) + try: + contents.remove('__pycache__') + except KeyError: + pass + self.assertEqual( + contents, {'subdirectory', 'binary.file', 'utf-8.file', 'utf-16.file'} + ) + + def test_submodule_sub_contents(self): + contents = names(resources.files(import_module('namespacedata01.subdirectory'))) + try: + contents.remove('__pycache__') + except KeyError: + pass + self.assertEqual(contents, {'binary.file'}) + + def test_submodule_sub_contents_by_name(self): + contents = names(resources.files('namespacedata01.subdirectory')) + try: + contents.remove('__pycache__') + except KeyError: + pass + self.assertEqual(contents, {'binary.file'}) + + +class ResourceFromNamespaceDiskTests( + util.DiskSetup, + ResourceFromNamespaceTests, + unittest.TestCase, +): + MODULE = 'namespacedata01' + + +class ResourceFromNamespaceZipTests( + util.ZipSetup, + ResourceFromNamespaceTests, + unittest.TestCase, +): + MODULE = 'namespacedata01' + + +if __name__ == '__main__': + unittest.main() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_util.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..de304b6f3510a6975f596de99822c1359adc18db --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/test_util.py @@ -0,0 +1,29 @@ +import unittest + +from .util import MemorySetup, Traversable + + +class TestMemoryTraversableImplementation(unittest.TestCase): + def test_concrete_methods_are_not_overridden(self): + """`MemoryTraversable` must not override `Traversable` concrete methods. + + This test is not an attempt to enforce a particular `Traversable` protocol; + it merely catches changes in the `Traversable` abstract/concrete methods + that have not been mirrored in the `MemoryTraversable` subclass. + """ + + traversable_concrete_methods = { + method + for method, value in Traversable.__dict__.items() + if callable(value) and method not in Traversable.__abstractmethods__ + } + memory_traversable_concrete_methods = { + method + for method, value in MemorySetup.MemoryTraversable.__dict__.items() + if callable(value) and not method.startswith("__") + } + overridden_methods = ( + memory_traversable_concrete_methods & traversable_concrete_methods + ) + + assert not overridden_methods diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/util.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/util.py new file mode 100644 index 0000000000000000000000000000000000000000..0340c150f6996a31dbe9513a3609d6260efd68d8 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/util.py @@ -0,0 +1,308 @@ +import abc +import contextlib +import functools +import importlib +import io +import pathlib +import sys +import types +from importlib.machinery import ModuleSpec + +from ..abc import ResourceReader, Traversable, TraversableResources +from . import _path +from . import zip as zip_ +from .compat.py39 import import_helper, os_helper + + +class Reader(ResourceReader): + def __init__(self, **kwargs): + vars(self).update(kwargs) + + def get_resource_reader(self, package): + return self + + def open_resource(self, path): + self._path = path + if isinstance(self.file, Exception): + raise self.file + return self.file + + def resource_path(self, path_): + self._path = path_ + if isinstance(self.path, Exception): + raise self.path + return self.path + + def is_resource(self, path_): + self._path = path_ + if isinstance(self.path, Exception): + raise self.path + + def part(entry): + return entry.split('/') + + return any( + len(parts) == 1 and parts[0] == path_ for parts in map(part, self._contents) + ) + + def contents(self): + if isinstance(self.path, Exception): + raise self.path + yield from self._contents + + +def create_package_from_loader(loader, is_package=True): + name = 'testingpackage' + module = types.ModuleType(name) + spec = ModuleSpec(name, loader, origin='does-not-exist', is_package=is_package) + module.__spec__ = spec + module.__loader__ = loader + return module + + +def create_package(file=None, path=None, is_package=True, contents=()): + return create_package_from_loader( + Reader(file=file, path=path, _contents=contents), + is_package, + ) + + +class CommonTestsBase(metaclass=abc.ABCMeta): + """ + Tests shared by test_open, test_path, and test_read. + """ + + @abc.abstractmethod + def execute(self, package, path): + """ + Call the pertinent legacy API function (e.g. open_text, path) + on package and path. + """ + + def test_package_name(self): + """ + Passing in the package name should succeed. + """ + self.execute(self.data.__name__, 'utf-8.file') + + def test_package_object(self): + """ + Passing in the package itself should succeed. + """ + self.execute(self.data, 'utf-8.file') + + def test_string_path(self): + """ + Passing in a string for the path should succeed. + """ + path = 'utf-8.file' + self.execute(self.data, path) + + def test_pathlib_path(self): + """ + Passing in a pathlib.PurePath object for the path should succeed. + """ + path = pathlib.PurePath('utf-8.file') + self.execute(self.data, path) + + def test_importing_module_as_side_effect(self): + """ + The anchor package can already be imported. + """ + del sys.modules[self.data.__name__] + self.execute(self.data.__name__, 'utf-8.file') + + def test_missing_path(self): + """ + Attempting to open or read or request the path for a + non-existent path should succeed if open_resource + can return a viable data stream. + """ + bytes_data = io.BytesIO(b'Hello, world!') + package = create_package(file=bytes_data, path=FileNotFoundError()) + self.execute(package, 'utf-8.file') + self.assertEqual(package.__loader__._path, 'utf-8.file') + + def test_extant_path(self): + # Attempting to open or read or request the path when the + # path does exist should still succeed. Does not assert + # anything about the result. + bytes_data = io.BytesIO(b'Hello, world!') + # any path that exists + path = __file__ + package = create_package(file=bytes_data, path=path) + self.execute(package, 'utf-8.file') + self.assertEqual(package.__loader__._path, 'utf-8.file') + + def test_useless_loader(self): + package = create_package(file=FileNotFoundError(), path=FileNotFoundError()) + with self.assertRaises(FileNotFoundError): + self.execute(package, 'utf-8.file') + + +fixtures = dict( + data01={ + '__init__.py': '', + 'binary.file': bytes(range(4)), + 'utf-16.file': '\ufeffHello, UTF-16 world!\n'.encode('utf-16-le'), + 'utf-8.file': 'Hello, UTF-8 world!\n'.encode('utf-8'), + 'subdirectory': { + '__init__.py': '', + 'binary.file': bytes(range(4, 8)), + }, + }, + data02={ + '__init__.py': '', + 'one': {'__init__.py': '', 'resource1.txt': 'one resource'}, + 'two': {'__init__.py': '', 'resource2.txt': 'two resource'}, + 'subdirectory': {'subsubdir': {'resource.txt': 'a resource'}}, + }, + namespacedata01={ + 'binary.file': bytes(range(4)), + 'utf-16.file': '\ufeffHello, UTF-16 world!\n'.encode('utf-16-le'), + 'utf-8.file': 'Hello, UTF-8 world!\n'.encode('utf-8'), + 'subdirectory': { + 'binary.file': bytes(range(12, 16)), + }, + }, +) + + +class ModuleSetup: + def setUp(self): + self.fixtures = contextlib.ExitStack() + self.addCleanup(self.fixtures.close) + + self.fixtures.enter_context(import_helper.isolated_modules()) + self.data = self.load_fixture(self.MODULE) + + def load_fixture(self, module): + self.tree_on_path({module: fixtures[module]}) + return importlib.import_module(module) + + +class ZipSetup(ModuleSetup): + MODULE = 'data01' + + def tree_on_path(self, spec): + temp_dir = self.fixtures.enter_context(os_helper.temp_dir()) + modules = pathlib.Path(temp_dir) / 'zipped modules.zip' + self.fixtures.enter_context( + import_helper.DirsOnSysPath(str(zip_.make_zip_file(spec, modules))) + ) + + +class DiskSetup(ModuleSetup): + MODULE = 'data01' + + def tree_on_path(self, spec): + temp_dir = self.fixtures.enter_context(os_helper.temp_dir()) + _path.build(spec, pathlib.Path(temp_dir)) + self.fixtures.enter_context(import_helper.DirsOnSysPath(temp_dir)) + + +class MemorySetup(ModuleSetup): + """Support loading a module in memory.""" + + MODULE = 'data01' + + def load_fixture(self, module): + self.fixtures.enter_context(self.augment_sys_metapath(module)) + return importlib.import_module(module) + + @contextlib.contextmanager + def augment_sys_metapath(self, module): + finder_instance = self.MemoryFinder(module) + sys.meta_path.append(finder_instance) + yield + sys.meta_path.remove(finder_instance) + + class MemoryFinder(importlib.abc.MetaPathFinder): + def __init__(self, module): + self._module = module + + def find_spec(self, fullname, path, target=None): + if fullname != self._module: + return None + + return importlib.machinery.ModuleSpec( + name=fullname, + loader=MemorySetup.MemoryLoader(self._module), + is_package=True, + ) + + class MemoryLoader(importlib.abc.Loader): + def __init__(self, module): + self._module = module + + def exec_module(self, module): + pass + + def get_resource_reader(self, fullname): + return MemorySetup.MemoryTraversableResources(self._module, fullname) + + class MemoryTraversableResources(TraversableResources): + def __init__(self, module, fullname): + self._module = module + self._fullname = fullname + + def files(self): + return MemorySetup.MemoryTraversable(self._module, self._fullname) + + class MemoryTraversable(Traversable): + """Implement only the abstract methods of `Traversable`. + + Besides `.__init__()`, no other methods may be implemented or overridden. + This is critical for validating the concrete `Traversable` implementations. + """ + + def __init__(self, module, fullname): + self._module = module + self._fullname = fullname + + def _resolve(self): + """ + Fully traverse the `fixtures` dictionary. + + This should be wrapped in a `try/except KeyError` + but it is not currently needed and lowers the code coverage numbers. + """ + path = pathlib.PurePosixPath(self._fullname) + return functools.reduce(lambda d, p: d[p], path.parts, fixtures) + + def iterdir(self): + directory = self._resolve() + if not isinstance(directory, dict): + # Filesystem openers raise OSError, and that exception is mirrored here. + raise OSError(f"{self._fullname} is not a directory") + for path in directory: + yield MemorySetup.MemoryTraversable( + self._module, f"{self._fullname}/{path}" + ) + + def is_dir(self) -> bool: + return isinstance(self._resolve(), dict) + + def is_file(self) -> bool: + return not self.is_dir() + + def open(self, mode='r', encoding=None, errors=None, *_, **__): + contents = self._resolve() + if isinstance(contents, dict): + # Filesystem openers raise OSError when attempting to open a directory, + # and that exception is mirrored here. + raise OSError(f"{self._fullname} is a directory") + if isinstance(contents, str): + contents = contents.encode("utf-8") + result = io.BytesIO(contents) + if "b" in mode: + return result + return io.TextIOWrapper(result, encoding=encoding, errors=errors) + + @property + def name(self): + return pathlib.PurePosixPath(self._fullname).name + + +class CommonTests(DiskSetup, CommonTestsBase): + pass diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/zip.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/zip.py new file mode 100644 index 0000000000000000000000000000000000000000..51ee564870c101bd447969c8433148eba597ab26 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/importlib_resources/tests/zip.py @@ -0,0 +1,26 @@ +""" +Generate zip test data files. +""" + +import zipfile + +import zipp + + +def make_zip_file(tree, dst): + """ + Zip the files in tree into a new zipfile at dst. + """ + with zipfile.ZipFile(dst, 'w') as zf: + for name, contents in walk(tree): + zf.writestr(name, contents) + zipp.CompleteDirs.inject(zf) + return dst + + +def walk(tree, prefix=''): + for name, contents in tree.items(): + if isinstance(contents, dict): + yield from walk(contents, prefix=f'{prefix}{name}/') + else: + yield f'{prefix}{name}', contents diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/METADATA b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..fc3c00df97bbf6e38be40ce7bec8e9d136d18214 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/METADATA @@ -0,0 +1,79 @@ +Metadata-Version: 2.4 +Name: iniconfig +Version: 2.3.0 +Summary: brain-dead simple config-ini parsing +Author-email: Ronny Pfannschmidt , Holger Krekel +License-Expression: MIT +Project-URL: Homepage, https://github.com/pytest-dev/iniconfig +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Utilities +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +Dynamic: license-file + +iniconfig: brain-dead simple parsing of ini files +======================================================= + +iniconfig is a small and simple INI-file parser module +having a unique set of features: + +* maintains order of sections and entries +* supports multi-line values with or without line-continuations +* supports "#" comments everywhere +* raises errors with proper line-numbers +* no bells and whistles like automatic substitutions +* iniconfig raises an Error if two sections have the same name. + +If you encounter issues or have feature wishes please report them to: + + https://github.com/RonnyPfannschmidt/iniconfig/issues + +Basic Example +=================================== + +If you have an ini file like this: + +.. code-block:: ini + + # content of example.ini + [section1] # comment + name1=value1 # comment + name1b=value1,value2 # comment + + [section2] + name2= + line1 + line2 + +then you can do: + +.. code-block:: pycon + + >>> import iniconfig + >>> ini = iniconfig.IniConfig("example.ini") + >>> ini['section1']['name1'] # raises KeyError if not exists + 'value1' + >>> ini.get('section1', 'name1b', [], lambda x: x.split(",")) + ['value1', 'value2'] + >>> ini.get('section1', 'notexist', [], lambda x: x.split(",")) + [] + >>> [x.name for x in list(ini)] + ['section1', 'section2'] + >>> list(list(ini)[0].items()) + [('name1', 'value1'), ('name1b', 'value1,value2')] + >>> 'section1' in ini + True + >>> 'inexistendsection' in ini + False diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/RECORD b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..158bf5562cf7e7643faf063db00108fc2adf3123 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/RECORD @@ -0,0 +1,10 @@ +iniconfig-2.3.0.dist-info/METADATA,sha256=QNdz-E5OES9JW79PG-nL0tRWwK6271MR910b8yLyFls,2526 +iniconfig-2.3.0.dist-info/RECORD,, +iniconfig-2.3.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +iniconfig-2.3.0.dist-info/licenses/LICENSE,sha256=NAn6kfes5VeJRjJnZlbjImT-XvdYFTVyXcmiN3RVG9Q,1098 +iniconfig-2.3.0.dist-info/top_level.txt,sha256=7KfM0fugdlToj9UW7enKXk2HYALQD8qHiyKtjhSzgN8,10 +iniconfig/__init__.py,sha256=XL5eqUYj4mskAOorZ5jfRAinJvJzTI-fJxpP4xfXtaw,7497 +iniconfig/_parse.py,sha256=5ncBl7MAQiaPNnpRrs9FR4t6G6DkgOUs458OY_1CR28,5223 +iniconfig/_version.py,sha256=KNFYe-Vtdt7Z-oHyl8jmDAQ9qXoCNMAEXigj6BR1QUI,704 +iniconfig/exceptions.py,sha256=mipQ_aMxD9CvSvFWN1oTXY4QuRnKAMZ1f3sCdmjDTU0,399 +iniconfig/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/WHEEL b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/licenses/LICENSE b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..46f4b2846fd708ecb81b2d665434ce6379aa1101 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2010 - 2023 Holger Krekel and others + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/top_level.txt b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..9dda53692d2f44a97392cae823f8163d55ad4549 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig-2.3.0.dist-info/top_level.txt @@ -0,0 +1 @@ +iniconfig diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b84809f8e9dc0db6fba3505fcc29ca26c3383cce --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig/__init__.py @@ -0,0 +1,249 @@ +"""brain-dead simple parser for ini-style files. +(C) Ronny Pfannschmidt, Holger Krekel -- MIT licensed +""" + +import os +from collections.abc import Callable +from collections.abc import Iterator +from collections.abc import Mapping +from typing import Final +from typing import TypeVar +from typing import overload + +__all__ = ["IniConfig", "ParseError", "COMMENTCHARS", "iscommentline"] + +from . import _parse +from ._parse import COMMENTCHARS +from ._parse import iscommentline +from .exceptions import ParseError + +_D = TypeVar("_D") +_T = TypeVar("_T") + + +class SectionWrapper: + config: Final["IniConfig"] + name: Final[str] + + def __init__(self, config: "IniConfig", name: str) -> None: + self.config = config + self.name = name + + def lineof(self, name: str) -> int | None: + return self.config.lineof(self.name, name) + + @overload + def get(self, key: str) -> str | None: ... + + @overload + def get( + self, + key: str, + convert: Callable[[str], _T], + ) -> _T | None: ... + + @overload + def get( + self, + key: str, + default: None, + convert: Callable[[str], _T], + ) -> _T | None: ... + + @overload + def get(self, key: str, default: _D, convert: None = None) -> str | _D: ... + + @overload + def get( + self, + key: str, + default: _D, + convert: Callable[[str], _T], + ) -> _T | _D: ... + + # TODO: investigate possible mypy bug wrt matching the passed over data + def get( # type: ignore [misc] + self, + key: str, + default: _D | None = None, + convert: Callable[[str], _T] | None = None, + ) -> _D | _T | str | None: + return self.config.get(self.name, key, convert=convert, default=default) + + def __getitem__(self, key: str) -> str: + return self.config.sections[self.name][key] + + def __iter__(self) -> Iterator[str]: + section: Mapping[str, str] = self.config.sections.get(self.name, {}) + + def lineof(key: str) -> int: + return self.config.lineof(self.name, key) # type: ignore[return-value] + + yield from sorted(section, key=lineof) + + def items(self) -> Iterator[tuple[str, str]]: + for name in self: + yield name, self[name] + + +class IniConfig: + path: Final[str] + sections: Final[Mapping[str, Mapping[str, str]]] + _sources: Final[Mapping[tuple[str, str | None], int]] + + def __init__( + self, + path: str | os.PathLike[str], + data: str | None = None, + encoding: str = "utf-8", + *, + _sections: Mapping[str, Mapping[str, str]] | None = None, + _sources: Mapping[tuple[str, str | None], int] | None = None, + ) -> None: + self.path = os.fspath(path) + + # Determine sections and sources + if _sections is not None and _sources is not None: + # Use provided pre-parsed data (called from parse()) + sections_data = _sections + sources = _sources + else: + # Parse the data (backward compatible path) + if data is None: + with open(self.path, encoding=encoding) as fp: + data = fp.read() + + # Use old behavior (no stripping) for backward compatibility + sections_data, sources = _parse.parse_ini_data( + self.path, data, strip_inline_comments=False + ) + + # Assign once to Final attributes + self._sources = sources + self.sections = sections_data + + @classmethod + def parse( + cls, + path: str | os.PathLike[str], + data: str | None = None, + encoding: str = "utf-8", + *, + strip_inline_comments: bool = True, + strip_section_whitespace: bool = False, + ) -> "IniConfig": + """Parse an INI file. + + Args: + path: Path to the INI file (used for error messages) + data: Optional INI content as string. If None, reads from path. + encoding: Encoding to use when reading the file (default: utf-8) + strip_inline_comments: Whether to strip inline comments from values + (default: True). When True, comments starting with # or ; are + removed from values, matching the behavior for section comments. + strip_section_whitespace: Whether to strip whitespace from section and key names + (default: False). When True, strips Unicode whitespace from section and key names, + addressing issue #4. When False, preserves existing behavior for backward compatibility. + + Returns: + IniConfig instance with parsed configuration + + Example: + # With comment stripping (default): + config = IniConfig.parse("setup.cfg") + # value = "foo" instead of "foo # comment" + + # Without comment stripping (old behavior): + config = IniConfig.parse("setup.cfg", strip_inline_comments=False) + # value = "foo # comment" + + # With section name stripping (opt-in for issue #4): + config = IniConfig.parse("setup.cfg", strip_section_whitespace=True) + # section names and keys have Unicode whitespace stripped + """ + fspath = os.fspath(path) + + if data is None: + with open(fspath, encoding=encoding) as fp: + data = fp.read() + + sections_data, sources = _parse.parse_ini_data( + fspath, + data, + strip_inline_comments=strip_inline_comments, + strip_section_whitespace=strip_section_whitespace, + ) + + # Call constructor with pre-parsed sections and sources + return cls(path=fspath, _sections=sections_data, _sources=sources) + + def lineof(self, section: str, name: str | None = None) -> int | None: + lineno = self._sources.get((section, name)) + return None if lineno is None else lineno + 1 + + @overload + def get( + self, + section: str, + name: str, + ) -> str | None: ... + + @overload + def get( + self, + section: str, + name: str, + convert: Callable[[str], _T], + ) -> _T | None: ... + + @overload + def get( + self, + section: str, + name: str, + default: None, + convert: Callable[[str], _T], + ) -> _T | None: ... + + @overload + def get( + self, section: str, name: str, default: _D, convert: None = None + ) -> str | _D: ... + + @overload + def get( + self, + section: str, + name: str, + default: _D, + convert: Callable[[str], _T], + ) -> _T | _D: ... + + def get( # type: ignore + self, + section: str, + name: str, + default: _D | None = None, + convert: Callable[[str], _T] | None = None, + ) -> _D | _T | str | None: + try: + value: str = self.sections[section][name] + except KeyError: + return default + else: + if convert is not None: + return convert(value) + else: + return value + + def __getitem__(self, name: str) -> SectionWrapper: + if name not in self.sections: + raise KeyError(name) + return SectionWrapper(self, name) + + def __iter__(self) -> Iterator[SectionWrapper]: + for name in sorted(self.sections, key=self.lineof): # type: ignore + yield SectionWrapper(self, name) + + def __contains__(self, arg: str) -> bool: + return arg in self.sections diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig/_parse.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig/_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..57b9b44e4cccca635651b8d4380aed1e2ab020a8 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig/_parse.py @@ -0,0 +1,163 @@ +from collections.abc import Mapping +from typing import NamedTuple + +from .exceptions import ParseError + +COMMENTCHARS = "#;" + + +class ParsedLine(NamedTuple): + lineno: int + section: str | None + name: str | None + value: str | None + + +def parse_ini_data( + path: str, + data: str, + *, + strip_inline_comments: bool, + strip_section_whitespace: bool = False, +) -> tuple[Mapping[str, Mapping[str, str]], Mapping[tuple[str, str | None], int]]: + """Parse INI data and return sections and sources mappings. + + Args: + path: Path for error messages + data: INI content as string + strip_inline_comments: Whether to strip inline comments from values + strip_section_whitespace: Whether to strip whitespace from section and key names + (default: False). When True, addresses issue #4 by stripping Unicode whitespace. + + Returns: + Tuple of (sections_data, sources) where: + - sections_data: mapping of section -> {name -> value} + - sources: mapping of (section, name) -> line number + """ + tokens = parse_lines( + path, + data.splitlines(True), + strip_inline_comments=strip_inline_comments, + strip_section_whitespace=strip_section_whitespace, + ) + + sources: dict[tuple[str, str | None], int] = {} + sections_data: dict[str, dict[str, str]] = {} + + for lineno, section, name, value in tokens: + if section is None: + raise ParseError(path, lineno, "no section header defined") + sources[section, name] = lineno + if name is None: + if section in sections_data: + raise ParseError(path, lineno, f"duplicate section {section!r}") + sections_data[section] = {} + else: + if name in sections_data[section]: + raise ParseError(path, lineno, f"duplicate name {name!r}") + assert value is not None + sections_data[section][name] = value + + return sections_data, sources + + +def parse_lines( + path: str, + line_iter: list[str], + *, + strip_inline_comments: bool = False, + strip_section_whitespace: bool = False, +) -> list[ParsedLine]: + result: list[ParsedLine] = [] + section = None + for lineno, line in enumerate(line_iter): + name, data = _parseline( + path, line, lineno, strip_inline_comments, strip_section_whitespace + ) + # new value + if name is not None and data is not None: + result.append(ParsedLine(lineno, section, name, data)) + # new section + elif name is not None and data is None: + if not name: + raise ParseError(path, lineno, "empty section name") + section = name + result.append(ParsedLine(lineno, section, None, None)) + # continuation + elif name is None and data is not None: + if not result: + raise ParseError(path, lineno, "unexpected value continuation") + last = result.pop() + if last.name is None: + raise ParseError(path, lineno, "unexpected value continuation") + + if last.value: + last = last._replace(value=f"{last.value}\n{data}") + else: + last = last._replace(value=data) + result.append(last) + return result + + +def _parseline( + path: str, + line: str, + lineno: int, + strip_inline_comments: bool, + strip_section_whitespace: bool, +) -> tuple[str | None, str | None]: + # blank lines + if iscommentline(line): + line = "" + else: + line = line.rstrip() + if not line: + return None, None + # section + if line[0] == "[": + realline = line + for c in COMMENTCHARS: + line = line.split(c)[0].rstrip() + if line[-1] == "]": + section_name = line[1:-1] + # Optionally strip whitespace from section name (issue #4) + if strip_section_whitespace: + section_name = section_name.strip() + return section_name, None + return None, realline.strip() + # value + elif not line[0].isspace(): + try: + name, value = line.split("=", 1) + if ":" in name: + raise ValueError() + except ValueError: + try: + name, value = line.split(":", 1) + except ValueError: + raise ParseError(path, lineno, f"unexpected line: {line!r}") from None + + # Strip key name (always for backward compatibility, optionally with unicode awareness) + key_name = name.strip() + + # Strip value + value = value.strip() + # Strip inline comments from values if requested (issue #55) + if strip_inline_comments: + for c in COMMENTCHARS: + value = value.split(c)[0].rstrip() + + return key_name, value + # continuation + else: + line = line.strip() + # Strip inline comments from continuations if requested (issue #55) + if strip_inline_comments: + for c in COMMENTCHARS: + line = line.split(c)[0].rstrip() + return None, line + + +def iscommentline(line: str) -> bool: + c = line.lstrip()[:1] + return c in COMMENTCHARS diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig/_version.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..b982b024d8649c68b58ba29198fab080774ddf5f --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig/_version.py @@ -0,0 +1,34 @@ +# file generated by setuptools-scm +# don't change, don't track in version control + +__all__ = [ + "__version__", + "__version_tuple__", + "version", + "version_tuple", + "__commit_id__", + "commit_id", +] + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import Tuple + from typing import Union + + VERSION_TUPLE = Tuple[Union[int, str], ...] + COMMIT_ID = Union[str, None] +else: + VERSION_TUPLE = object + COMMIT_ID = object + +version: str +__version__: str +__version_tuple__: VERSION_TUPLE +version_tuple: VERSION_TUPLE +commit_id: COMMIT_ID +__commit_id__: COMMIT_ID + +__version__ = version = '2.3.0' +__version_tuple__ = version_tuple = (2, 3, 0) + +__commit_id__ = commit_id = None diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig/exceptions.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..d078bc659504cf79d3cedefe66dd828af9a9d9e0 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig/exceptions.py @@ -0,0 +1,16 @@ +from typing import Final + + +class ParseError(Exception): + path: Final[str] + lineno: Final[int] + msg: Final[str] + + def __init__(self, path: str, lineno: int, msg: str) -> None: + super().__init__(path, lineno, msg) + self.path = path + self.lineno = lineno + self.msg = msg + + def __str__(self) -> str: + return f"{self.path}:{self.lineno + 1}: {self.msg}" diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig/py.typed b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/iniconfig/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/isympy.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/isympy.py new file mode 100644 index 0000000000000000000000000000000000000000..f7f4f7cd751f78e7d526aa50a527a914cd07d9af --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/isympy.py @@ -0,0 +1,342 @@ +""" +Python shell for SymPy. + +This is just a normal Python shell (IPython shell if you have the +IPython package installed), that executes the following commands for +the user: + + >>> from __future__ import division + >>> from sympy import * + >>> x, y, z, t = symbols('x y z t') + >>> k, m, n = symbols('k m n', integer=True) + >>> f, g, h = symbols('f g h', cls=Function) + >>> init_printing() + +So starting 'isympy' is equivalent to starting Python (or IPython) and +executing the above commands by hand. It is intended for easy and quick +experimentation with SymPy. isympy is a good way to use SymPy as an +interactive calculator. If you have IPython and Matplotlib installed, then +interactive plotting is enabled by default. + +COMMAND LINE OPTIONS +-------------------- + +-c CONSOLE, --console=CONSOLE + + Use the specified shell (Python or IPython) shell as the console + backend instead of the default one (IPython if present, Python + otherwise), e.g.: + + $isympy -c python + + CONSOLE must be one of 'ipython' or 'python' + +-p PRETTY, --pretty PRETTY + + Setup pretty-printing in SymPy. When pretty-printing is enabled, + expressions can be printed with Unicode or ASCII. The default is + to use pretty-printing (with Unicode if the terminal supports it). + When this option is 'no', expressions will not be pretty-printed + and ASCII will be used: + + $isympy -p no + + PRETTY must be one of 'unicode', 'ascii', or 'no' + +-t TYPES, --types=TYPES + + Setup the ground types for the polys. By default, gmpy ground types + are used if gmpy2 or gmpy is installed, otherwise it falls back to python + ground types, which are a little bit slower. You can manually + choose python ground types even if gmpy is installed (e.g., for + testing purposes): + + $isympy -t python + + TYPES must be one of 'gmpy', 'gmpy1' or 'python' + + Note that the ground type gmpy1 is primarily intended for testing; it + forces the use of gmpy version 1 even if gmpy2 is available. + + This is the same as setting the environment variable + SYMPY_GROUND_TYPES to the given ground type (e.g., + SYMPY_GROUND_TYPES='gmpy') + + The ground types can be determined interactively from the variable + sympy.polys.domains.GROUND_TYPES. + +-o ORDER, --order ORDER + + Setup the ordering of terms for printing. The default is lex, which + orders terms lexicographically (e.g., x**2 + x + 1). You can choose + other orderings, such as rev-lex, which will use reverse + lexicographic ordering (e.g., 1 + x + x**2): + + $isympy -o rev-lex + + ORDER must be one of 'lex', 'rev-lex', 'grlex', 'rev-grlex', + 'grevlex', 'rev-grevlex', 'old', or 'none'. + + Note that for very large expressions, ORDER='none' may speed up + printing considerably but the terms will have no canonical order. + +-q, --quiet + + Print only Python's and SymPy's versions to stdout at startup. + +-d, --doctest + + Use the same format that should be used for doctests. This is + equivalent to -c python -p no. + +-C, --no-cache + + Disable the caching mechanism. Disabling the cache may slow certain + operations down considerably. This is useful for testing the cache, + or for benchmarking, as the cache can result in deceptive timings. + + This is equivalent to setting the environment variable + SYMPY_USE_CACHE to 'no'. + +-a, --auto-symbols (requires at least IPython 0.11) + + Automatically create missing symbols. Normally, typing a name of a + Symbol that has not been instantiated first would raise NameError, + but with this option enabled, any undefined name will be + automatically created as a Symbol. + + Note that this is intended only for interactive, calculator style + usage. In a script that uses SymPy, Symbols should be instantiated + at the top, so that it's clear what they are. + + This will not override any names that are already defined, which + includes the single character letters represented by the mnemonic + QCOSINE (see the "Gotchas and Pitfalls" document in the + documentation). You can delete existing names by executing "del + name". If a name is defined, typing "'name' in dir()" will return True. + + The Symbols that are created using this have default assumptions. + If you want to place assumptions on symbols, you should create them + using symbols() or var(). + + Finally, this only works in the top level namespace. So, for + example, if you define a function in isympy with an undefined + Symbol, it will not work. + + See also the -i and -I options. + +-i, --int-to-Integer (requires at least IPython 0.11) + + Automatically wrap int literals with Integer. This makes it so that + things like 1/2 will come out as Rational(1, 2), rather than 0.5. This + works by preprocessing the source and wrapping all int literals with + Integer. Note that this will not change the behavior of int literals + assigned to variables, and it also won't change the behavior of functions + that return int literals. + + If you want an int, you can wrap the literal in int(), e.g. int(3)/int(2) + gives 1.5 (with division imported from __future__). + +-I, --interactive (requires at least IPython 0.11) + + This is equivalent to --auto-symbols --int-to-Integer. Future options + designed for ease of interactive use may be added to this. + +-D, --debug + + Enable debugging output. This is the same as setting the + environment variable SYMPY_DEBUG to 'True'. The debug status is set + in the variable SYMPY_DEBUG within isympy. + +-- IPython options + + Additionally you can pass command line options directly to the IPython + interpreter (the standard Python shell is not supported). However you + need to add the '--' separator between two types of options, e.g the + startup banner option and the colors option. You need to enter the + options as required by the version of IPython that you are using, too: + + in IPython 0.11, + + $isympy -q -- --colors=NoColor + + or older versions of IPython, + + $isympy -q -- -colors NoColor + +See also isympy --help. +""" + +import os +import sys + +# DO NOT IMPORT SYMPY HERE! Or the setting of the sympy environment variables +# by the command line will break. + +def main() -> None: + from argparse import ArgumentParser, RawDescriptionHelpFormatter + + VERSION = None + if '--version' in sys.argv: + # We cannot import sympy before this is run, because flags like -C and + # -t set environment variables that must be set before SymPy is + # imported. The only thing we need to import it for is to get the + # version, which only matters with the --version flag. + import sympy + VERSION = sympy.__version__ + + usage = 'isympy [options] -- [ipython options]' + parser = ArgumentParser( + usage=usage, + description=__doc__, + formatter_class=RawDescriptionHelpFormatter, + ) + + parser.add_argument('--version', action='version', version=VERSION) + + parser.add_argument( + '-c', '--console', + dest='console', + action='store', + default=None, + choices=['ipython', 'python'], + metavar='CONSOLE', + help='select type of interactive session: ipython | python; defaults ' + 'to ipython if IPython is installed, otherwise python') + + parser.add_argument( + '-p', '--pretty', + dest='pretty', + action='store', + default=None, + metavar='PRETTY', + choices=['unicode', 'ascii', 'no'], + help='setup pretty printing: unicode | ascii | no; defaults to ' + 'unicode printing if the terminal supports it, otherwise ascii') + + parser.add_argument( + '-t', '--types', + dest='types', + action='store', + default=None, + metavar='TYPES', + choices=['gmpy', 'gmpy1', 'python'], + help='setup ground types: gmpy | gmpy1 | python; defaults to gmpy if gmpy2 ' + 'or gmpy is installed, otherwise python') + + parser.add_argument( + '-o', '--order', + dest='order', + action='store', + default=None, + metavar='ORDER', + choices=['lex', 'grlex', 'grevlex', 'rev-lex', 'rev-grlex', 'rev-grevlex', 'old', 'none'], + help='setup ordering of terms: [rev-]lex | [rev-]grlex | [rev-]grevlex | old | none; defaults to lex') + + parser.add_argument( + '-q', '--quiet', + dest='quiet', + action='store_true', + default=False, + help='print only version information at startup') + + parser.add_argument( + '-d', '--doctest', + dest='doctest', + action='store_true', + default=False, + help='use the doctest format for output (you can just copy and paste it)') + + parser.add_argument( + '-C', '--no-cache', + dest='cache', + action='store_false', + default=True, + help='disable caching mechanism') + + parser.add_argument( + '-a', '--auto-symbols', + dest='auto_symbols', + action='store_true', + default=False, + help='automatically construct missing symbols') + + parser.add_argument( + '-i', '--int-to-Integer', + dest='auto_int_to_Integer', + action='store_true', + default=False, + help="automatically wrap int literals with Integer") + + parser.add_argument( + '-I', '--interactive', + dest='interactive', + action='store_true', + default=False, + help="equivalent to -a -i") + + parser.add_argument( + '-D', '--debug', + dest='debug', + action='store_true', + default=False, + help='enable debugging output') + + (options, ipy_args) = parser.parse_known_args() + if '--' in ipy_args: + ipy_args.remove('--') + + if not options.cache: + os.environ['SYMPY_USE_CACHE'] = 'no' + + if options.types: + os.environ['SYMPY_GROUND_TYPES'] = options.types + + if options.debug: + os.environ['SYMPY_DEBUG'] = str(options.debug) + + if options.doctest: + options.pretty = 'no' + options.console = 'python' + + session = options.console + + if session is not None: + ipython = session == 'ipython' + else: + try: + import IPython # noqa: F401 + ipython = True + except ImportError: + if not options.quiet: + from sympy.interactive.session import no_ipython + print(no_ipython) + ipython = False + + args = { + 'pretty_print': True, + 'use_unicode': None, + 'use_latex': None, + 'order': None, + 'argv': ipy_args, + } + + if options.pretty == 'unicode': + args['use_unicode'] = True + elif options.pretty == 'ascii': + args['use_unicode'] = False + elif options.pretty == 'no': + args['pretty_print'] = False + + if options.order is not None: + args['order'] = options.order + + args['quiet'] = options.quiet + args['auto_symbols'] = options.auto_symbols or options.interactive + args['auto_int_to_Integer'] = options.auto_int_to_Integer or options.interactive + + from sympy.interactive import init_session + init_session(ipython, **args) + +if __name__ == "__main__": + main() diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2-3.1.6.dist-info/METADATA b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2-3.1.6.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ffef2ff3bfa0c42b6e6e3eefda700391d181c9a0 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2-3.1.6.dist-info/METADATA @@ -0,0 +1,84 @@ +Metadata-Version: 2.4 +Name: Jinja2 +Version: 3.1.6 +Summary: A very fast and expressive template engine. +Maintainer-email: Pallets +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content +Classifier: Topic :: Text Processing :: Markup :: HTML +Classifier: Typing :: Typed +License-File: LICENSE.txt +Requires-Dist: MarkupSafe>=2.0 +Requires-Dist: Babel>=2.7 ; extra == "i18n" +Project-URL: Changes, https://jinja.palletsprojects.com/changes/ +Project-URL: Chat, https://discord.gg/pallets +Project-URL: Documentation, https://jinja.palletsprojects.com/ +Project-URL: Donate, https://palletsprojects.com/donate +Project-URL: Source, https://github.com/pallets/jinja/ +Provides-Extra: i18n + +# Jinja + +Jinja is a fast, expressive, extensible templating engine. Special +placeholders in the template allow writing code similar to Python +syntax. Then the template is passed data to render the final document. + +It includes: + +- Template inheritance and inclusion. +- Define and import macros within templates. +- HTML templates can use autoescaping to prevent XSS from untrusted + user input. +- A sandboxed environment can safely render untrusted templates. +- AsyncIO support for generating templates and calling async + functions. +- I18N support with Babel. +- Templates are compiled to optimized Python code just-in-time and + cached, or can be compiled ahead-of-time. +- Exceptions point to the correct line in templates to make debugging + easier. +- Extensible filters, tests, functions, and even syntax. + +Jinja's philosophy is that while application logic belongs in Python if +possible, it shouldn't make the template designer's job difficult by +restricting functionality too much. + + +## In A Nutshell + +```jinja +{% extends "base.html" %} +{% block title %}Members{% endblock %} +{% block content %} + +{% endblock %} +``` + +## Donate + +The Pallets organization develops and supports Jinja and other popular +packages. In order to grow the community of contributors and users, and +allow the maintainers to devote more time to the projects, [please +donate today][]. + +[please donate today]: https://palletsprojects.com/donate + +## Contributing + +See our [detailed contributing documentation][contrib] for many ways to +contribute, including reporting issues, requesting features, asking or answering +questions, and making PRs. + +[contrib]: https://palletsprojects.com/contributing/ + diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2-3.1.6.dist-info/RECORD b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2-3.1.6.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..4ea7b93d247fff2f61d0a2c38ccc732ece323df5 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2-3.1.6.dist-info/RECORD @@ -0,0 +1,31 @@ +jinja2-3.1.6.dist-info/METADATA,sha256=aMVUj7Z8QTKhOJjZsx7FDGvqKr3ZFdkh8hQ1XDpkmcg,2871 +jinja2-3.1.6.dist-info/RECORD,, +jinja2-3.1.6.dist-info/WHEEL,sha256=_2ozNFCLWc93bK4WKHCO-eDUENDlo-dgc9cU3qokYO4,82 +jinja2-3.1.6.dist-info/entry_points.txt,sha256=OL85gYU1eD8cuPlikifFngXpeBjaxl6rIJ8KkC_3r-I,58 +jinja2-3.1.6.dist-info/licenses/LICENSE.txt,sha256=O0nc7kEF6ze6wQ-vG-JgQI_oXSUrjp3y4JefweCUQ3s,1475 +jinja2/__init__.py,sha256=xxepO9i7DHsqkQrgBEduLtfoz2QCuT6_gbL4XSN1hbU,1928 +jinja2/_identifier.py,sha256=_zYctNKzRqlk_murTNlzrju1FFJL7Va_Ijqqd7ii2lU,1958 +jinja2/async_utils.py,sha256=vK-PdsuorOMnWSnEkT3iUJRIkTnYgO2T6MnGxDgHI5o,2834 +jinja2/bccache.py,sha256=gh0qs9rulnXo0PhX5jTJy2UHzI8wFnQ63o_vw7nhzRg,14061 +jinja2/compiler.py,sha256=9RpCQl5X88BHllJiPsHPh295Hh0uApvwFJNQuutULeM,74131 +jinja2/constants.py,sha256=GMoFydBF_kdpaRKPoM5cl5MviquVRLVyZtfp5-16jg0,1433 +jinja2/debug.py,sha256=CnHqCDHd-BVGvti_8ZsTolnXNhA3ECsY-6n_2pwU8Hw,6297 +jinja2/defaults.py,sha256=boBcSw78h-lp20YbaXSJsqkAI2uN_mD_TtCydpeq5wU,1267 +jinja2/environment.py,sha256=9nhrP7Ch-NbGX00wvyr4yy-uhNHq2OCc60ggGrni_fk,61513 +jinja2/exceptions.py,sha256=ioHeHrWwCWNaXX1inHmHVblvc4haO7AXsjCp3GfWvx0,5071 +jinja2/ext.py,sha256=5PF5eHfh8mXAIxXHHRB2xXbXohi8pE3nHSOxa66uS7E,31875 +jinja2/filters.py,sha256=PQ_Egd9n9jSgtnGQYyF4K5j2nYwhUIulhPnyimkdr-k,55212 +jinja2/idtracking.py,sha256=-ll5lIp73pML3ErUYiIJj7tdmWxcH_IlDv3yA_hiZYo,10555 +jinja2/lexer.py,sha256=LYiYio6br-Tep9nPcupWXsPEtjluw3p1mU-lNBVRUfk,29786 +jinja2/loaders.py,sha256=wIrnxjvcbqh5VwW28NSkfotiDq8qNCxIOSFbGUiSLB4,24055 +jinja2/meta.py,sha256=OTDPkaFvU2Hgvx-6akz7154F8BIWaRmvJcBFvwopHww,4397 +jinja2/nativetypes.py,sha256=7GIGALVJgdyL80oZJdQUaUfwSt5q2lSSZbXt0dNf_M4,4210 +jinja2/nodes.py,sha256=m1Duzcr6qhZI8JQ6VyJgUNinjAf5bQzijSmDnMsvUx8,34579 +jinja2/optimizer.py,sha256=rJnCRlQ7pZsEEmMhsQDgC_pKyDHxP5TPS6zVPGsgcu8,1651 +jinja2/parser.py,sha256=lLOFy3sEmHc5IaEHRiH1sQVnId2moUQzhyeJZTtdY30,40383 +jinja2/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jinja2/runtime.py,sha256=gDk-GvdriJXqgsGbHgrcKTP0Yp6zPXzhzrIpCFH3jAU,34249 +jinja2/sandbox.py,sha256=Mw2aitlY2I8la7FYhcX2YG9BtUYcLnD0Gh3d29cDWrY,15009 +jinja2/tests.py,sha256=VLsBhVFnWg-PxSBz1MhRnNWgP1ovXk3neO1FLQMeC9Q,5926 +jinja2/utils.py,sha256=rRp3o9e7ZKS4fyrWRbELyLcpuGVTFcnooaOa1qx_FIk,24129 +jinja2/visitor.py,sha256=EcnL1PIwf_4RVCOMxsRNuR8AXHbS1qfAdMOE2ngKJz4,3557 diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2-3.1.6.dist-info/WHEEL b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2-3.1.6.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..23d2d7e9a5d381ef8a375db09f82052144d1fd96 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2-3.1.6.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.11.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2-3.1.6.dist-info/entry_points.txt b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2-3.1.6.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..abc3eae3b3bc573957cf7401711948799b3465c0 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2-3.1.6.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[babel.extractors] +jinja2=jinja2.ext:babel_extract[i18n] + diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2-3.1.6.dist-info/licenses/LICENSE.txt b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2-3.1.6.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..c37cae49ec77ad6ebb25568c1605f1fee5313cfb --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2-3.1.6.dist-info/licenses/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 2007 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/__init__.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1a423a3eac16ac550e8e4008d7f5d79401b50e0f --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/__init__.py @@ -0,0 +1,38 @@ +"""Jinja is a template engine written in pure Python. It provides a +non-XML syntax that supports inline expressions and an optional +sandboxed environment. +""" + +from .bccache import BytecodeCache as BytecodeCache +from .bccache import FileSystemBytecodeCache as FileSystemBytecodeCache +from .bccache import MemcachedBytecodeCache as MemcachedBytecodeCache +from .environment import Environment as Environment +from .environment import Template as Template +from .exceptions import TemplateAssertionError as TemplateAssertionError +from .exceptions import TemplateError as TemplateError +from .exceptions import TemplateNotFound as TemplateNotFound +from .exceptions import TemplateRuntimeError as TemplateRuntimeError +from .exceptions import TemplatesNotFound as TemplatesNotFound +from .exceptions import TemplateSyntaxError as TemplateSyntaxError +from .exceptions import UndefinedError as UndefinedError +from .loaders import BaseLoader as BaseLoader +from .loaders import ChoiceLoader as ChoiceLoader +from .loaders import DictLoader as DictLoader +from .loaders import FileSystemLoader as FileSystemLoader +from .loaders import FunctionLoader as FunctionLoader +from .loaders import ModuleLoader as ModuleLoader +from .loaders import PackageLoader as PackageLoader +from .loaders import PrefixLoader as PrefixLoader +from .runtime import ChainableUndefined as ChainableUndefined +from .runtime import DebugUndefined as DebugUndefined +from .runtime import make_logging_undefined as make_logging_undefined +from .runtime import StrictUndefined as StrictUndefined +from .runtime import Undefined as Undefined +from .utils import clear_caches as clear_caches +from .utils import is_undefined as is_undefined +from .utils import pass_context as pass_context +from .utils import pass_environment as pass_environment +from .utils import pass_eval_context as pass_eval_context +from .utils import select_autoescape as select_autoescape + +__version__ = "3.1.6" diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/_identifier.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/_identifier.py new file mode 100644 index 0000000000000000000000000000000000000000..928c1503c7d414a8a86bbf5a82c68d42cb089bd2 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/_identifier.py @@ -0,0 +1,6 @@ +import re + +# generated by scripts/generate_identifier_pattern.py +pattern = re.compile( + r"[\w·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣ৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఄా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ູົຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪽ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰℘℮⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣠-꣱ꣿꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯︳︴﹍-﹏_𐇽𐋠𐍶-𐍺𐨁-𐨃𐨅𐨆𐨌-𐨏𐨸-𐨿𐨺𐫦𐫥𐴤-𐽆𐴧-𐽐𑀀-𑀂𑀸-𑁆𑁿-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑄴𑅅𑅆𑅳𑆀-𑆂𑆳-𑇀𑇉-𑇌𑈬-𑈷𑈾𑋟-𑋪𑌀-𑌃𑌻𑌼𑌾-𑍄𑍇𑍈𑍋-𑍍𑍗𑍢𑍣𑍦-𑍬𑍰-𑍴𑐵-𑑆𑑞𑒰-𑓃𑖯-𑖵𑖸-𑗀𑗜𑗝𑘰-𑙀𑚫-𑚷𑜝-𑜫𑠬-𑠺𑨁-𑨊𑨳-𑨹𑨻-𑨾𑩇𑩑-𑩛𑪊-𑪙𑰯-𑰶𑰸-𑰿𑲒-𑲧𑲩-𑲶𑴱-𑴶𑴺𑴼𑴽𑴿-𑵅𑵇𑶊-𑶎𑶐𑶑𑶓-𑶗𑻳-𑻶𖫰-𖫴𖬰-𖬶𖽑-𖽾𖾏-𖾒𛲝𛲞𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄𝨀-𝨶𝨻-𝩬𝩵𝪄𝪛-𝪟𝪡-𝪯𞀀-𞀆𞀈-𞀘𞀛-𞀡𞀣𞀤𞀦-𞣐𞀪-𞣖𞥄-𞥊󠄀-󠇯]+" # noqa: B950 +) diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/async_utils.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/async_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f0c140205c50a3df9863ce1ab610b0c62a483f1b --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/async_utils.py @@ -0,0 +1,99 @@ +import inspect +import typing as t +from functools import WRAPPER_ASSIGNMENTS +from functools import wraps + +from .utils import _PassArg +from .utils import pass_eval_context + +if t.TYPE_CHECKING: + import typing_extensions as te + +V = t.TypeVar("V") + + +def async_variant(normal_func): # type: ignore + def decorator(async_func): # type: ignore + pass_arg = _PassArg.from_obj(normal_func) + need_eval_context = pass_arg is None + + if pass_arg is _PassArg.environment: + + def is_async(args: t.Any) -> bool: + return t.cast(bool, args[0].is_async) + + else: + + def is_async(args: t.Any) -> bool: + return t.cast(bool, args[0].environment.is_async) + + # Take the doc and annotations from the sync function, but the + # name from the async function. Pallets-Sphinx-Themes + # build_function_directive expects __wrapped__ to point to the + # sync function. + async_func_attrs = ("__module__", "__name__", "__qualname__") + normal_func_attrs = tuple(set(WRAPPER_ASSIGNMENTS).difference(async_func_attrs)) + + @wraps(normal_func, assigned=normal_func_attrs) + @wraps(async_func, assigned=async_func_attrs, updated=()) + def wrapper(*args, **kwargs): # type: ignore + b = is_async(args) + + if need_eval_context: + args = args[1:] + + if b: + return async_func(*args, **kwargs) + + return normal_func(*args, **kwargs) + + if need_eval_context: + wrapper = pass_eval_context(wrapper) + + wrapper.jinja_async_variant = True # type: ignore[attr-defined] + return wrapper + + return decorator + + +_common_primitives = {int, float, bool, str, list, dict, tuple, type(None)} + + +async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V": + # Avoid a costly call to isawaitable + if type(value) in _common_primitives: + return t.cast("V", value) + + if inspect.isawaitable(value): + return await t.cast("t.Awaitable[V]", value) + + return value + + +class _IteratorToAsyncIterator(t.Generic[V]): + def __init__(self, iterator: "t.Iterator[V]"): + self._iterator = iterator + + def __aiter__(self) -> "te.Self": + return self + + async def __anext__(self) -> V: + try: + return next(self._iterator) + except StopIteration as e: + raise StopAsyncIteration(e.value) from e + + +def auto_aiter( + iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", +) -> "t.AsyncIterator[V]": + if hasattr(iterable, "__aiter__"): + return iterable.__aiter__() + else: + return _IteratorToAsyncIterator(iter(iterable)) + + +async def auto_to_list( + value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", +) -> t.List["V"]: + return [x async for x in auto_aiter(value)] diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/bccache.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/bccache.py new file mode 100644 index 0000000000000000000000000000000000000000..ada8b099ff251ea9c6da4c42e1383f37e359f06a --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/bccache.py @@ -0,0 +1,408 @@ +"""The optional bytecode cache system. This is useful if you have very +complex template situations and the compilation of all those templates +slows down your application too much. + +Situations where this is useful are often forking web applications that +are initialized on the first request. +""" + +import errno +import fnmatch +import marshal +import os +import pickle +import stat +import sys +import tempfile +import typing as t +from hashlib import sha1 +from io import BytesIO +from types import CodeType + +if t.TYPE_CHECKING: + import typing_extensions as te + + from .environment import Environment + + class _MemcachedClient(te.Protocol): + def get(self, key: str) -> bytes: ... + + def set( + self, key: str, value: bytes, timeout: t.Optional[int] = None + ) -> None: ... + + +bc_version = 5 +# Magic bytes to identify Jinja bytecode cache files. Contains the +# Python major and minor version to avoid loading incompatible bytecode +# if a project upgrades its Python version. +bc_magic = ( + b"j2" + + pickle.dumps(bc_version, 2) + + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1], 2) +) + + +class Bucket: + """Buckets are used to store the bytecode for one template. It's created + and initialized by the bytecode cache and passed to the loading functions. + + The buckets get an internal checksum from the cache assigned and use this + to automatically reject outdated cache material. Individual bytecode + cache subclasses don't have to care about cache invalidation. + """ + + def __init__(self, environment: "Environment", key: str, checksum: str) -> None: + self.environment = environment + self.key = key + self.checksum = checksum + self.reset() + + def reset(self) -> None: + """Resets the bucket (unloads the bytecode).""" + self.code: t.Optional[CodeType] = None + + def load_bytecode(self, f: t.BinaryIO) -> None: + """Loads bytecode from a file or file like object.""" + # make sure the magic header is correct + magic = f.read(len(bc_magic)) + if magic != bc_magic: + self.reset() + return + # the source code of the file changed, we need to reload + checksum = pickle.load(f) + if self.checksum != checksum: + self.reset() + return + # if marshal_load fails then we need to reload + try: + self.code = marshal.load(f) + except (EOFError, ValueError, TypeError): + self.reset() + return + + def write_bytecode(self, f: t.IO[bytes]) -> None: + """Dump the bytecode into the file or file like object passed.""" + if self.code is None: + raise TypeError("can't write empty bucket") + f.write(bc_magic) + pickle.dump(self.checksum, f, 2) + marshal.dump(self.code, f) + + def bytecode_from_string(self, string: bytes) -> None: + """Load bytecode from bytes.""" + self.load_bytecode(BytesIO(string)) + + def bytecode_to_string(self) -> bytes: + """Return the bytecode as bytes.""" + out = BytesIO() + self.write_bytecode(out) + return out.getvalue() + + +class BytecodeCache: + """To implement your own bytecode cache you have to subclass this class + and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of + these methods are passed a :class:`~jinja2.bccache.Bucket`. + + A very basic bytecode cache that saves the bytecode on the file system:: + + from os import path + + class MyCache(BytecodeCache): + + def __init__(self, directory): + self.directory = directory + + def load_bytecode(self, bucket): + filename = path.join(self.directory, bucket.key) + if path.exists(filename): + with open(filename, 'rb') as f: + bucket.load_bytecode(f) + + def dump_bytecode(self, bucket): + filename = path.join(self.directory, bucket.key) + with open(filename, 'wb') as f: + bucket.write_bytecode(f) + + A more advanced version of a filesystem based bytecode cache is part of + Jinja. + """ + + def load_bytecode(self, bucket: Bucket) -> None: + """Subclasses have to override this method to load bytecode into a + bucket. If they are not able to find code in the cache for the + bucket, it must not do anything. + """ + raise NotImplementedError() + + def dump_bytecode(self, bucket: Bucket) -> None: + """Subclasses have to override this method to write the bytecode + from a bucket back to the cache. If it unable to do so it must not + fail silently but raise an exception. + """ + raise NotImplementedError() + + def clear(self) -> None: + """Clears the cache. This method is not used by Jinja but should be + implemented to allow applications to clear the bytecode cache used + by a particular environment. + """ + + def get_cache_key( + self, name: str, filename: t.Optional[t.Union[str]] = None + ) -> str: + """Returns the unique hash key for this template name.""" + hash = sha1(name.encode("utf-8")) + + if filename is not None: + hash.update(f"|{filename}".encode()) + + return hash.hexdigest() + + def get_source_checksum(self, source: str) -> str: + """Returns a checksum for the source.""" + return sha1(source.encode("utf-8")).hexdigest() + + def get_bucket( + self, + environment: "Environment", + name: str, + filename: t.Optional[str], + source: str, + ) -> Bucket: + """Return a cache bucket for the given template. All arguments are + mandatory but filename may be `None`. + """ + key = self.get_cache_key(name, filename) + checksum = self.get_source_checksum(source) + bucket = Bucket(environment, key, checksum) + self.load_bytecode(bucket) + return bucket + + def set_bucket(self, bucket: Bucket) -> None: + """Put the bucket into the cache.""" + self.dump_bytecode(bucket) + + +class FileSystemBytecodeCache(BytecodeCache): + """A bytecode cache that stores bytecode on the filesystem. It accepts + two arguments: The directory where the cache items are stored and a + pattern string that is used to build the filename. + + If no directory is specified a default cache directory is selected. On + Windows the user's temp directory is used, on UNIX systems a directory + is created for the user in the system temp directory. + + The pattern can be used to have multiple separate caches operate on the + same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s`` + is replaced with the cache key. + + >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache') + + This bytecode cache supports clearing of the cache using the clear method. + """ + + def __init__( + self, directory: t.Optional[str] = None, pattern: str = "__jinja2_%s.cache" + ) -> None: + if directory is None: + directory = self._get_default_cache_dir() + self.directory = directory + self.pattern = pattern + + def _get_default_cache_dir(self) -> str: + def _unsafe_dir() -> "te.NoReturn": + raise RuntimeError( + "Cannot determine safe temp directory. You " + "need to explicitly provide one." + ) + + tmpdir = tempfile.gettempdir() + + # On windows the temporary directory is used specific unless + # explicitly forced otherwise. We can just use that. + if os.name == "nt": + return tmpdir + if not hasattr(os, "getuid"): + _unsafe_dir() + + dirname = f"_jinja2-cache-{os.getuid()}" + actual_dir = os.path.join(tmpdir, dirname) + + try: + os.mkdir(actual_dir, stat.S_IRWXU) + except OSError as e: + if e.errno != errno.EEXIST: + raise + try: + os.chmod(actual_dir, stat.S_IRWXU) + actual_dir_stat = os.lstat(actual_dir) + if ( + actual_dir_stat.st_uid != os.getuid() + or not stat.S_ISDIR(actual_dir_stat.st_mode) + or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU + ): + _unsafe_dir() + except OSError as e: + if e.errno != errno.EEXIST: + raise + + actual_dir_stat = os.lstat(actual_dir) + if ( + actual_dir_stat.st_uid != os.getuid() + or not stat.S_ISDIR(actual_dir_stat.st_mode) + or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU + ): + _unsafe_dir() + + return actual_dir + + def _get_cache_filename(self, bucket: Bucket) -> str: + return os.path.join(self.directory, self.pattern % (bucket.key,)) + + def load_bytecode(self, bucket: Bucket) -> None: + filename = self._get_cache_filename(bucket) + + # Don't test for existence before opening the file, since the + # file could disappear after the test before the open. + try: + f = open(filename, "rb") + except (FileNotFoundError, IsADirectoryError, PermissionError): + # PermissionError can occur on Windows when an operation is + # in progress, such as calling clear(). + return + + with f: + bucket.load_bytecode(f) + + def dump_bytecode(self, bucket: Bucket) -> None: + # Write to a temporary file, then rename to the real name after + # writing. This avoids another process reading the file before + # it is fully written. + name = self._get_cache_filename(bucket) + f = tempfile.NamedTemporaryFile( + mode="wb", + dir=os.path.dirname(name), + prefix=os.path.basename(name), + suffix=".tmp", + delete=False, + ) + + def remove_silent() -> None: + try: + os.remove(f.name) + except OSError: + # Another process may have called clear(). On Windows, + # another program may be holding the file open. + pass + + try: + with f: + bucket.write_bytecode(f) + except BaseException: + remove_silent() + raise + + try: + os.replace(f.name, name) + except OSError: + # Another process may have called clear(). On Windows, + # another program may be holding the file open. + remove_silent() + except BaseException: + remove_silent() + raise + + def clear(self) -> None: + # imported lazily here because google app-engine doesn't support + # write access on the file system and the function does not exist + # normally. + from os import remove + + files = fnmatch.filter(os.listdir(self.directory), self.pattern % ("*",)) + for filename in files: + try: + remove(os.path.join(self.directory, filename)) + except OSError: + pass + + +class MemcachedBytecodeCache(BytecodeCache): + """This class implements a bytecode cache that uses a memcache cache for + storing the information. It does not enforce a specific memcache library + (tummy's memcache or cmemcache) but will accept any class that provides + the minimal interface required. + + Libraries compatible with this class: + + - `cachelib `_ + - `python-memcached `_ + + (Unfortunately the django cache interface is not compatible because it + does not support storing binary data, only text. You can however pass + the underlying cache client to the bytecode cache which is available + as `django.core.cache.cache._client`.) + + The minimal interface for the client passed to the constructor is this: + + .. class:: MinimalClientInterface + + .. method:: set(key, value[, timeout]) + + Stores the bytecode in the cache. `value` is a string and + `timeout` the timeout of the key. If timeout is not provided + a default timeout or no timeout should be assumed, if it's + provided it's an integer with the number of seconds the cache + item should exist. + + .. method:: get(key) + + Returns the value for the cache key. If the item does not + exist in the cache the return value must be `None`. + + The other arguments to the constructor are the prefix for all keys that + is added before the actual cache key and the timeout for the bytecode in + the cache system. We recommend a high (or no) timeout. + + This bytecode cache does not support clearing of used items in the cache. + The clear method is a no-operation function. + + .. versionadded:: 2.7 + Added support for ignoring memcache errors through the + `ignore_memcache_errors` parameter. + """ + + def __init__( + self, + client: "_MemcachedClient", + prefix: str = "jinja2/bytecode/", + timeout: t.Optional[int] = None, + ignore_memcache_errors: bool = True, + ): + self.client = client + self.prefix = prefix + self.timeout = timeout + self.ignore_memcache_errors = ignore_memcache_errors + + def load_bytecode(self, bucket: Bucket) -> None: + try: + code = self.client.get(self.prefix + bucket.key) + except Exception: + if not self.ignore_memcache_errors: + raise + else: + bucket.bytecode_from_string(code) + + def dump_bytecode(self, bucket: Bucket) -> None: + key = self.prefix + bucket.key + value = bucket.bytecode_to_string() + + try: + if self.timeout is not None: + self.client.set(key, value, self.timeout) + else: + self.client.set(key, value) + except Exception: + if not self.ignore_memcache_errors: + raise diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/compiler.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ff6a1b11af3e1a868d1a74c48d842390259b43 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/compiler.py @@ -0,0 +1,1998 @@ +"""Compiles nodes from the parser into Python code.""" + +import typing as t +from contextlib import contextmanager +from functools import update_wrapper +from io import StringIO +from itertools import chain +from keyword import iskeyword as is_python_keyword + +from markupsafe import escape +from markupsafe import Markup + +from . import nodes +from .exceptions import TemplateAssertionError +from .idtracking import Symbols +from .idtracking import VAR_LOAD_ALIAS +from .idtracking import VAR_LOAD_PARAMETER +from .idtracking import VAR_LOAD_RESOLVE +from .idtracking import VAR_LOAD_UNDEFINED +from .nodes import EvalContext +from .optimizer import Optimizer +from .utils import _PassArg +from .utils import concat +from .visitor import NodeVisitor + +if t.TYPE_CHECKING: + import typing_extensions as te + + from .environment import Environment + +F = t.TypeVar("F", bound=t.Callable[..., t.Any]) + +operators = { + "eq": "==", + "ne": "!=", + "gt": ">", + "gteq": ">=", + "lt": "<", + "lteq": "<=", + "in": "in", + "notin": "not in", +} + + +def optimizeconst(f: F) -> F: + def new_func( + self: "CodeGenerator", node: nodes.Expr, frame: "Frame", **kwargs: t.Any + ) -> t.Any: + # Only optimize if the frame is not volatile + if self.optimizer is not None and not frame.eval_ctx.volatile: + new_node = self.optimizer.visit(node, frame.eval_ctx) + + if new_node != node: + return self.visit(new_node, frame) + + return f(self, node, frame, **kwargs) + + return update_wrapper(new_func, f) # type: ignore[return-value] + + +def _make_binop(op: str) -> t.Callable[["CodeGenerator", nodes.BinExpr, "Frame"], None]: + @optimizeconst + def visitor(self: "CodeGenerator", node: nodes.BinExpr, frame: Frame) -> None: + if ( + self.environment.sandboxed and op in self.environment.intercepted_binops # type: ignore + ): + self.write(f"environment.call_binop(context, {op!r}, ") + self.visit(node.left, frame) + self.write(", ") + self.visit(node.right, frame) + else: + self.write("(") + self.visit(node.left, frame) + self.write(f" {op} ") + self.visit(node.right, frame) + + self.write(")") + + return visitor + + +def _make_unop( + op: str, +) -> t.Callable[["CodeGenerator", nodes.UnaryExpr, "Frame"], None]: + @optimizeconst + def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None: + if ( + self.environment.sandboxed and op in self.environment.intercepted_unops # type: ignore + ): + self.write(f"environment.call_unop(context, {op!r}, ") + self.visit(node.node, frame) + else: + self.write("(" + op) + self.visit(node.node, frame) + + self.write(")") + + return visitor + + +def generate( + node: nodes.Template, + environment: "Environment", + name: t.Optional[str], + filename: t.Optional[str], + stream: t.Optional[t.TextIO] = None, + defer_init: bool = False, + optimized: bool = True, +) -> t.Optional[str]: + """Generate the python source for a node tree.""" + if not isinstance(node, nodes.Template): + raise TypeError("Can't compile non template nodes") + + generator = environment.code_generator_class( + environment, name, filename, stream, defer_init, optimized + ) + generator.visit(node) + + if stream is None: + return generator.stream.getvalue() # type: ignore + + return None + + +def has_safe_repr(value: t.Any) -> bool: + """Does the node have a safe representation?""" + if value is None or value is NotImplemented or value is Ellipsis: + return True + + if type(value) in {bool, int, float, complex, range, str, Markup}: + return True + + if type(value) in {tuple, list, set, frozenset}: + return all(has_safe_repr(v) for v in value) + + if type(value) is dict: # noqa E721 + return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items()) + + return False + + +def find_undeclared( + nodes: t.Iterable[nodes.Node], names: t.Iterable[str] +) -> t.Set[str]: + """Check if the names passed are accessed undeclared. The return value + is a set of all the undeclared names from the sequence of names found. + """ + visitor = UndeclaredNameVisitor(names) + try: + for node in nodes: + visitor.visit(node) + except VisitorExit: + pass + return visitor.undeclared + + +class MacroRef: + def __init__(self, node: t.Union[nodes.Macro, nodes.CallBlock]) -> None: + self.node = node + self.accesses_caller = False + self.accesses_kwargs = False + self.accesses_varargs = False + + +class Frame: + """Holds compile time information for us.""" + + def __init__( + self, + eval_ctx: EvalContext, + parent: t.Optional["Frame"] = None, + level: t.Optional[int] = None, + ) -> None: + self.eval_ctx = eval_ctx + + # the parent of this frame + self.parent = parent + + if parent is None: + self.symbols = Symbols(level=level) + + # in some dynamic inheritance situations the compiler needs to add + # write tests around output statements. + self.require_output_check = False + + # inside some tags we are using a buffer rather than yield statements. + # this for example affects {% filter %} or {% macro %}. If a frame + # is buffered this variable points to the name of the list used as + # buffer. + self.buffer: t.Optional[str] = None + + # the name of the block we're in, otherwise None. + self.block: t.Optional[str] = None + + else: + self.symbols = Symbols(parent.symbols, level=level) + self.require_output_check = parent.require_output_check + self.buffer = parent.buffer + self.block = parent.block + + # a toplevel frame is the root + soft frames such as if conditions. + self.toplevel = False + + # the root frame is basically just the outermost frame, so no if + # conditions. This information is used to optimize inheritance + # situations. + self.rootlevel = False + + # variables set inside of loops and blocks should not affect outer frames, + # but they still needs to be kept track of as part of the active context. + self.loop_frame = False + self.block_frame = False + + # track whether the frame is being used in an if-statement or conditional + # expression as it determines which errors should be raised during runtime + # or compile time. + self.soft_frame = False + + def copy(self) -> "te.Self": + """Create a copy of the current one.""" + rv = object.__new__(self.__class__) + rv.__dict__.update(self.__dict__) + rv.symbols = self.symbols.copy() + return rv + + def inner(self, isolated: bool = False) -> "Frame": + """Return an inner frame.""" + if isolated: + return Frame(self.eval_ctx, level=self.symbols.level + 1) + return Frame(self.eval_ctx, self) + + def soft(self) -> "te.Self": + """Return a soft frame. A soft frame may not be modified as + standalone thing as it shares the resources with the frame it + was created of, but it's not a rootlevel frame any longer. + + This is only used to implement if-statements and conditional + expressions. + """ + rv = self.copy() + rv.rootlevel = False + rv.soft_frame = True + return rv + + __copy__ = copy + + +class VisitorExit(RuntimeError): + """Exception used by the `UndeclaredNameVisitor` to signal a stop.""" + + +class DependencyFinderVisitor(NodeVisitor): + """A visitor that collects filter and test calls.""" + + def __init__(self) -> None: + self.filters: t.Set[str] = set() + self.tests: t.Set[str] = set() + + def visit_Filter(self, node: nodes.Filter) -> None: + self.generic_visit(node) + self.filters.add(node.name) + + def visit_Test(self, node: nodes.Test) -> None: + self.generic_visit(node) + self.tests.add(node.name) + + def visit_Block(self, node: nodes.Block) -> None: + """Stop visiting at blocks.""" + + +class UndeclaredNameVisitor(NodeVisitor): + """A visitor that checks if a name is accessed without being + declared. This is different from the frame visitor as it will + not stop at closure frames. + """ + + def __init__(self, names: t.Iterable[str]) -> None: + self.names = set(names) + self.undeclared: t.Set[str] = set() + + def visit_Name(self, node: nodes.Name) -> None: + if node.ctx == "load" and node.name in self.names: + self.undeclared.add(node.name) + if self.undeclared == self.names: + raise VisitorExit() + else: + self.names.discard(node.name) + + def visit_Block(self, node: nodes.Block) -> None: + """Stop visiting a blocks.""" + + +class CompilerExit(Exception): + """Raised if the compiler encountered a situation where it just + doesn't make sense to further process the code. Any block that + raises such an exception is not further processed. + """ + + +class CodeGenerator(NodeVisitor): + def __init__( + self, + environment: "Environment", + name: t.Optional[str], + filename: t.Optional[str], + stream: t.Optional[t.TextIO] = None, + defer_init: bool = False, + optimized: bool = True, + ) -> None: + if stream is None: + stream = StringIO() + self.environment = environment + self.name = name + self.filename = filename + self.stream = stream + self.created_block_context = False + self.defer_init = defer_init + self.optimizer: t.Optional[Optimizer] = None + + if optimized: + self.optimizer = Optimizer(environment) + + # aliases for imports + self.import_aliases: t.Dict[str, str] = {} + + # a registry for all blocks. Because blocks are moved out + # into the global python scope they are registered here + self.blocks: t.Dict[str, nodes.Block] = {} + + # the number of extends statements so far + self.extends_so_far = 0 + + # some templates have a rootlevel extends. In this case we + # can safely assume that we're a child template and do some + # more optimizations. + self.has_known_extends = False + + # the current line number + self.code_lineno = 1 + + # registry of all filters and tests (global, not block local) + self.tests: t.Dict[str, str] = {} + self.filters: t.Dict[str, str] = {} + + # the debug information + self.debug_info: t.List[t.Tuple[int, int]] = [] + self._write_debug_info: t.Optional[int] = None + + # the number of new lines before the next write() + self._new_lines = 0 + + # the line number of the last written statement + self._last_line = 0 + + # true if nothing was written so far. + self._first_write = True + + # used by the `temporary_identifier` method to get new + # unique, temporary identifier + self._last_identifier = 0 + + # the current indentation + self._indentation = 0 + + # Tracks toplevel assignments + self._assign_stack: t.List[t.Set[str]] = [] + + # Tracks parameter definition blocks + self._param_def_block: t.List[t.Set[str]] = [] + + # Tracks the current context. + self._context_reference_stack = ["context"] + + @property + def optimized(self) -> bool: + return self.optimizer is not None + + # -- Various compilation helpers + + def fail(self, msg: str, lineno: int) -> "te.NoReturn": + """Fail with a :exc:`TemplateAssertionError`.""" + raise TemplateAssertionError(msg, lineno, self.name, self.filename) + + def temporary_identifier(self) -> str: + """Get a new unique identifier.""" + self._last_identifier += 1 + return f"t_{self._last_identifier}" + + def buffer(self, frame: Frame) -> None: + """Enable buffering for the frame from that point onwards.""" + frame.buffer = self.temporary_identifier() + self.writeline(f"{frame.buffer} = []") + + def return_buffer_contents( + self, frame: Frame, force_unescaped: bool = False + ) -> None: + """Return the buffer contents of the frame.""" + if not force_unescaped: + if frame.eval_ctx.volatile: + self.writeline("if context.eval_ctx.autoescape:") + self.indent() + self.writeline(f"return Markup(concat({frame.buffer}))") + self.outdent() + self.writeline("else:") + self.indent() + self.writeline(f"return concat({frame.buffer})") + self.outdent() + return + elif frame.eval_ctx.autoescape: + self.writeline(f"return Markup(concat({frame.buffer}))") + return + self.writeline(f"return concat({frame.buffer})") + + def indent(self) -> None: + """Indent by one.""" + self._indentation += 1 + + def outdent(self, step: int = 1) -> None: + """Outdent by step.""" + self._indentation -= step + + def start_write(self, frame: Frame, node: t.Optional[nodes.Node] = None) -> None: + """Yield or write into the frame buffer.""" + if frame.buffer is None: + self.writeline("yield ", node) + else: + self.writeline(f"{frame.buffer}.append(", node) + + def end_write(self, frame: Frame) -> None: + """End the writing process started by `start_write`.""" + if frame.buffer is not None: + self.write(")") + + def simple_write( + self, s: str, frame: Frame, node: t.Optional[nodes.Node] = None + ) -> None: + """Simple shortcut for start_write + write + end_write.""" + self.start_write(frame, node) + self.write(s) + self.end_write(frame) + + def blockvisit(self, nodes: t.Iterable[nodes.Node], frame: Frame) -> None: + """Visit a list of nodes as block in a frame. If the current frame + is no buffer a dummy ``if 0: yield None`` is written automatically. + """ + try: + self.writeline("pass") + for node in nodes: + self.visit(node, frame) + except CompilerExit: + pass + + def write(self, x: str) -> None: + """Write a string into the output stream.""" + if self._new_lines: + if not self._first_write: + self.stream.write("\n" * self._new_lines) + self.code_lineno += self._new_lines + if self._write_debug_info is not None: + self.debug_info.append((self._write_debug_info, self.code_lineno)) + self._write_debug_info = None + self._first_write = False + self.stream.write(" " * self._indentation) + self._new_lines = 0 + self.stream.write(x) + + def writeline( + self, x: str, node: t.Optional[nodes.Node] = None, extra: int = 0 + ) -> None: + """Combination of newline and write.""" + self.newline(node, extra) + self.write(x) + + def newline(self, node: t.Optional[nodes.Node] = None, extra: int = 0) -> None: + """Add one or more newlines before the next write.""" + self._new_lines = max(self._new_lines, 1 + extra) + if node is not None and node.lineno != self._last_line: + self._write_debug_info = node.lineno + self._last_line = node.lineno + + def signature( + self, + node: t.Union[nodes.Call, nodes.Filter, nodes.Test], + frame: Frame, + extra_kwargs: t.Optional[t.Mapping[str, t.Any]] = None, + ) -> None: + """Writes a function call to the stream for the current node. + A leading comma is added automatically. The extra keyword + arguments may not include python keywords otherwise a syntax + error could occur. The extra keyword arguments should be given + as python dict. + """ + # if any of the given keyword arguments is a python keyword + # we have to make sure that no invalid call is created. + kwarg_workaround = any( + is_python_keyword(t.cast(str, k)) + for k in chain((x.key for x in node.kwargs), extra_kwargs or ()) + ) + + for arg in node.args: + self.write(", ") + self.visit(arg, frame) + + if not kwarg_workaround: + for kwarg in node.kwargs: + self.write(", ") + self.visit(kwarg, frame) + if extra_kwargs is not None: + for key, value in extra_kwargs.items(): + self.write(f", {key}={value}") + if node.dyn_args: + self.write(", *") + self.visit(node.dyn_args, frame) + + if kwarg_workaround: + if node.dyn_kwargs is not None: + self.write(", **dict({") + else: + self.write(", **{") + for kwarg in node.kwargs: + self.write(f"{kwarg.key!r}: ") + self.visit(kwarg.value, frame) + self.write(", ") + if extra_kwargs is not None: + for key, value in extra_kwargs.items(): + self.write(f"{key!r}: {value}, ") + if node.dyn_kwargs is not None: + self.write("}, **") + self.visit(node.dyn_kwargs, frame) + self.write(")") + else: + self.write("}") + + elif node.dyn_kwargs is not None: + self.write(", **") + self.visit(node.dyn_kwargs, frame) + + def pull_dependencies(self, nodes: t.Iterable[nodes.Node]) -> None: + """Find all filter and test names used in the template and + assign them to variables in the compiled namespace. Checking + that the names are registered with the environment is done when + compiling the Filter and Test nodes. If the node is in an If or + CondExpr node, the check is done at runtime instead. + + .. versionchanged:: 3.0 + Filters and tests in If and CondExpr nodes are checked at + runtime instead of compile time. + """ + visitor = DependencyFinderVisitor() + + for node in nodes: + visitor.visit(node) + + for id_map, names, dependency in ( + (self.filters, visitor.filters, "filters"), + ( + self.tests, + visitor.tests, + "tests", + ), + ): + for name in sorted(names): + if name not in id_map: + id_map[name] = self.temporary_identifier() + + # add check during runtime that dependencies used inside of executed + # blocks are defined, as this step may be skipped during compile time + self.writeline("try:") + self.indent() + self.writeline(f"{id_map[name]} = environment.{dependency}[{name!r}]") + self.outdent() + self.writeline("except KeyError:") + self.indent() + self.writeline("@internalcode") + self.writeline(f"def {id_map[name]}(*unused):") + self.indent() + self.writeline( + f'raise TemplateRuntimeError("No {dependency[:-1]}' + f' named {name!r} found.")' + ) + self.outdent() + self.outdent() + + def enter_frame(self, frame: Frame) -> None: + undefs = [] + for target, (action, param) in frame.symbols.loads.items(): + if action == VAR_LOAD_PARAMETER: + pass + elif action == VAR_LOAD_RESOLVE: + self.writeline(f"{target} = {self.get_resolve_func()}({param!r})") + elif action == VAR_LOAD_ALIAS: + self.writeline(f"{target} = {param}") + elif action == VAR_LOAD_UNDEFINED: + undefs.append(target) + else: + raise NotImplementedError("unknown load instruction") + if undefs: + self.writeline(f"{' = '.join(undefs)} = missing") + + def leave_frame(self, frame: Frame, with_python_scope: bool = False) -> None: + if not with_python_scope: + undefs = [] + for target in frame.symbols.loads: + undefs.append(target) + if undefs: + self.writeline(f"{' = '.join(undefs)} = missing") + + def choose_async(self, async_value: str = "async ", sync_value: str = "") -> str: + return async_value if self.environment.is_async else sync_value + + def func(self, name: str) -> str: + return f"{self.choose_async()}def {name}" + + def macro_body( + self, node: t.Union[nodes.Macro, nodes.CallBlock], frame: Frame + ) -> t.Tuple[Frame, MacroRef]: + """Dump the function def of a macro or call block.""" + frame = frame.inner() + frame.symbols.analyze_node(node) + macro_ref = MacroRef(node) + + explicit_caller = None + skip_special_params = set() + args = [] + + for idx, arg in enumerate(node.args): + if arg.name == "caller": + explicit_caller = idx + if arg.name in ("kwargs", "varargs"): + skip_special_params.add(arg.name) + args.append(frame.symbols.ref(arg.name)) + + undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs")) + + if "caller" in undeclared: + # In older Jinja versions there was a bug that allowed caller + # to retain the special behavior even if it was mentioned in + # the argument list. However thankfully this was only really + # working if it was the last argument. So we are explicitly + # checking this now and error out if it is anywhere else in + # the argument list. + if explicit_caller is not None: + try: + node.defaults[explicit_caller - len(node.args)] + except IndexError: + self.fail( + "When defining macros or call blocks the " + 'special "caller" argument must be omitted ' + "or be given a default.", + node.lineno, + ) + else: + args.append(frame.symbols.declare_parameter("caller")) + macro_ref.accesses_caller = True + if "kwargs" in undeclared and "kwargs" not in skip_special_params: + args.append(frame.symbols.declare_parameter("kwargs")) + macro_ref.accesses_kwargs = True + if "varargs" in undeclared and "varargs" not in skip_special_params: + args.append(frame.symbols.declare_parameter("varargs")) + macro_ref.accesses_varargs = True + + # macros are delayed, they never require output checks + frame.require_output_check = False + frame.symbols.analyze_node(node) + self.writeline(f"{self.func('macro')}({', '.join(args)}):", node) + self.indent() + + self.buffer(frame) + self.enter_frame(frame) + + self.push_parameter_definitions(frame) + for idx, arg in enumerate(node.args): + ref = frame.symbols.ref(arg.name) + self.writeline(f"if {ref} is missing:") + self.indent() + try: + default = node.defaults[idx - len(node.args)] + except IndexError: + self.writeline( + f'{ref} = undefined("parameter {arg.name!r} was not provided",' + f" name={arg.name!r})" + ) + else: + self.writeline(f"{ref} = ") + self.visit(default, frame) + self.mark_parameter_stored(ref) + self.outdent() + self.pop_parameter_definitions() + + self.blockvisit(node.body, frame) + self.return_buffer_contents(frame, force_unescaped=True) + self.leave_frame(frame, with_python_scope=True) + self.outdent() + + return frame, macro_ref + + def macro_def(self, macro_ref: MacroRef, frame: Frame) -> None: + """Dump the macro definition for the def created by macro_body.""" + arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args) + name = getattr(macro_ref.node, "name", None) + if len(macro_ref.node.args) == 1: + arg_tuple += "," + self.write( + f"Macro(environment, macro, {name!r}, ({arg_tuple})," + f" {macro_ref.accesses_kwargs!r}, {macro_ref.accesses_varargs!r}," + f" {macro_ref.accesses_caller!r}, context.eval_ctx.autoescape)" + ) + + def position(self, node: nodes.Node) -> str: + """Return a human readable position for the node.""" + rv = f"line {node.lineno}" + if self.name is not None: + rv = f"{rv} in {self.name!r}" + return rv + + def dump_local_context(self, frame: Frame) -> str: + items_kv = ", ".join( + f"{name!r}: {target}" + for name, target in frame.symbols.dump_stores().items() + ) + return f"{{{items_kv}}}" + + def write_commons(self) -> None: + """Writes a common preamble that is used by root and block functions. + Primarily this sets up common local helpers and enforces a generator + through a dead branch. + """ + self.writeline("resolve = context.resolve_or_missing") + self.writeline("undefined = environment.undefined") + self.writeline("concat = environment.concat") + # always use the standard Undefined class for the implicit else of + # conditional expressions + self.writeline("cond_expr_undefined = Undefined") + self.writeline("if 0: yield None") + + def push_parameter_definitions(self, frame: Frame) -> None: + """Pushes all parameter targets from the given frame into a local + stack that permits tracking of yet to be assigned parameters. In + particular this enables the optimization from `visit_Name` to skip + undefined expressions for parameters in macros as macros can reference + otherwise unbound parameters. + """ + self._param_def_block.append(frame.symbols.dump_param_targets()) + + def pop_parameter_definitions(self) -> None: + """Pops the current parameter definitions set.""" + self._param_def_block.pop() + + def mark_parameter_stored(self, target: str) -> None: + """Marks a parameter in the current parameter definitions as stored. + This will skip the enforced undefined checks. + """ + if self._param_def_block: + self._param_def_block[-1].discard(target) + + def push_context_reference(self, target: str) -> None: + self._context_reference_stack.append(target) + + def pop_context_reference(self) -> None: + self._context_reference_stack.pop() + + def get_context_ref(self) -> str: + return self._context_reference_stack[-1] + + def get_resolve_func(self) -> str: + target = self._context_reference_stack[-1] + if target == "context": + return "resolve" + return f"{target}.resolve" + + def derive_context(self, frame: Frame) -> str: + return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})" + + def parameter_is_undeclared(self, target: str) -> bool: + """Checks if a given target is an undeclared parameter.""" + if not self._param_def_block: + return False + return target in self._param_def_block[-1] + + def push_assign_tracking(self) -> None: + """Pushes a new layer for assignment tracking.""" + self._assign_stack.append(set()) + + def pop_assign_tracking(self, frame: Frame) -> None: + """Pops the topmost level for assignment tracking and updates the + context variables if necessary. + """ + vars = self._assign_stack.pop() + if ( + not frame.block_frame + and not frame.loop_frame + and not frame.toplevel + or not vars + ): + return + public_names = [x for x in vars if x[:1] != "_"] + if len(vars) == 1: + name = next(iter(vars)) + ref = frame.symbols.ref(name) + if frame.loop_frame: + self.writeline(f"_loop_vars[{name!r}] = {ref}") + return + if frame.block_frame: + self.writeline(f"_block_vars[{name!r}] = {ref}") + return + self.writeline(f"context.vars[{name!r}] = {ref}") + else: + if frame.loop_frame: + self.writeline("_loop_vars.update({") + elif frame.block_frame: + self.writeline("_block_vars.update({") + else: + self.writeline("context.vars.update({") + for idx, name in enumerate(sorted(vars)): + if idx: + self.write(", ") + ref = frame.symbols.ref(name) + self.write(f"{name!r}: {ref}") + self.write("})") + if not frame.block_frame and not frame.loop_frame and public_names: + if len(public_names) == 1: + self.writeline(f"context.exported_vars.add({public_names[0]!r})") + else: + names_str = ", ".join(map(repr, sorted(public_names))) + self.writeline(f"context.exported_vars.update(({names_str}))") + + # -- Statement Visitors + + def visit_Template( + self, node: nodes.Template, frame: t.Optional[Frame] = None + ) -> None: + assert frame is None, "no root frame allowed" + eval_ctx = EvalContext(self.environment, self.name) + + from .runtime import async_exported + from .runtime import exported + + if self.environment.is_async: + exported_names = sorted(exported + async_exported) + else: + exported_names = sorted(exported) + + self.writeline("from jinja2.runtime import " + ", ".join(exported_names)) + + # if we want a deferred initialization we cannot move the + # environment into a local name + envenv = "" if self.defer_init else ", environment=environment" + + # do we have an extends tag at all? If not, we can save some + # overhead by just not processing any inheritance code. + have_extends = node.find(nodes.Extends) is not None + + # find all blocks + for block in node.find_all(nodes.Block): + if block.name in self.blocks: + self.fail(f"block {block.name!r} defined twice", block.lineno) + self.blocks[block.name] = block + + # find all imports and import them + for import_ in node.find_all(nodes.ImportedName): + if import_.importname not in self.import_aliases: + imp = import_.importname + self.import_aliases[imp] = alias = self.temporary_identifier() + if "." in imp: + module, obj = imp.rsplit(".", 1) + self.writeline(f"from {module} import {obj} as {alias}") + else: + self.writeline(f"import {imp} as {alias}") + + # add the load name + self.writeline(f"name = {self.name!r}") + + # generate the root render function. + self.writeline( + f"{self.func('root')}(context, missing=missing{envenv}):", extra=1 + ) + self.indent() + self.write_commons() + + # process the root + frame = Frame(eval_ctx) + if "self" in find_undeclared(node.body, ("self",)): + ref = frame.symbols.declare_parameter("self") + self.writeline(f"{ref} = TemplateReference(context)") + frame.symbols.analyze_node(node) + frame.toplevel = frame.rootlevel = True + frame.require_output_check = have_extends and not self.has_known_extends + if have_extends: + self.writeline("parent_template = None") + self.enter_frame(frame) + self.pull_dependencies(node.body) + self.blockvisit(node.body, frame) + self.leave_frame(frame, with_python_scope=True) + self.outdent() + + # make sure that the parent root is called. + if have_extends: + if not self.has_known_extends: + self.indent() + self.writeline("if parent_template is not None:") + self.indent() + if not self.environment.is_async: + self.writeline("yield from parent_template.root_render_func(context)") + else: + self.writeline("agen = parent_template.root_render_func(context)") + self.writeline("try:") + self.indent() + self.writeline("async for event in agen:") + self.indent() + self.writeline("yield event") + self.outdent() + self.outdent() + self.writeline("finally: await agen.aclose()") + self.outdent(1 + (not self.has_known_extends)) + + # at this point we now have the blocks collected and can visit them too. + for name, block in self.blocks.items(): + self.writeline( + f"{self.func('block_' + name)}(context, missing=missing{envenv}):", + block, + 1, + ) + self.indent() + self.write_commons() + # It's important that we do not make this frame a child of the + # toplevel template. This would cause a variety of + # interesting issues with identifier tracking. + block_frame = Frame(eval_ctx) + block_frame.block_frame = True + undeclared = find_undeclared(block.body, ("self", "super")) + if "self" in undeclared: + ref = block_frame.symbols.declare_parameter("self") + self.writeline(f"{ref} = TemplateReference(context)") + if "super" in undeclared: + ref = block_frame.symbols.declare_parameter("super") + self.writeline(f"{ref} = context.super({name!r}, block_{name})") + block_frame.symbols.analyze_node(block) + block_frame.block = name + self.writeline("_block_vars = {}") + self.enter_frame(block_frame) + self.pull_dependencies(block.body) + self.blockvisit(block.body, block_frame) + self.leave_frame(block_frame, with_python_scope=True) + self.outdent() + + blocks_kv_str = ", ".join(f"{x!r}: block_{x}" for x in self.blocks) + self.writeline(f"blocks = {{{blocks_kv_str}}}", extra=1) + debug_kv_str = "&".join(f"{k}={v}" for k, v in self.debug_info) + self.writeline(f"debug_info = {debug_kv_str!r}") + + def visit_Block(self, node: nodes.Block, frame: Frame) -> None: + """Call a block and register it for the template.""" + level = 0 + if frame.toplevel: + # if we know that we are a child template, there is no need to + # check if we are one + if self.has_known_extends: + return + if self.extends_so_far > 0: + self.writeline("if parent_template is None:") + self.indent() + level += 1 + + if node.scoped: + context = self.derive_context(frame) + else: + context = self.get_context_ref() + + if node.required: + self.writeline(f"if len(context.blocks[{node.name!r}]) <= 1:", node) + self.indent() + self.writeline( + f'raise TemplateRuntimeError("Required block {node.name!r} not found")', + node, + ) + self.outdent() + + if not self.environment.is_async and frame.buffer is None: + self.writeline( + f"yield from context.blocks[{node.name!r}][0]({context})", node + ) + else: + self.writeline(f"gen = context.blocks[{node.name!r}][0]({context})") + self.writeline("try:") + self.indent() + self.writeline( + f"{self.choose_async()}for event in gen:", + node, + ) + self.indent() + self.simple_write("event", frame) + self.outdent() + self.outdent() + self.writeline( + f"finally: {self.choose_async('await gen.aclose()', 'gen.close()')}" + ) + + self.outdent(level) + + def visit_Extends(self, node: nodes.Extends, frame: Frame) -> None: + """Calls the extender.""" + if not frame.toplevel: + self.fail("cannot use extend from a non top-level scope", node.lineno) + + # if the number of extends statements in general is zero so + # far, we don't have to add a check if something extended + # the template before this one. + if self.extends_so_far > 0: + # if we have a known extends we just add a template runtime + # error into the generated code. We could catch that at compile + # time too, but i welcome it not to confuse users by throwing the + # same error at different times just "because we can". + if not self.has_known_extends: + self.writeline("if parent_template is not None:") + self.indent() + self.writeline('raise TemplateRuntimeError("extended multiple times")') + + # if we have a known extends already we don't need that code here + # as we know that the template execution will end here. + if self.has_known_extends: + raise CompilerExit() + else: + self.outdent() + + self.writeline("parent_template = environment.get_template(", node) + self.visit(node.template, frame) + self.write(f", {self.name!r})") + self.writeline("for name, parent_block in parent_template.blocks.items():") + self.indent() + self.writeline("context.blocks.setdefault(name, []).append(parent_block)") + self.outdent() + + # if this extends statement was in the root level we can take + # advantage of that information and simplify the generated code + # in the top level from this point onwards + if frame.rootlevel: + self.has_known_extends = True + + # and now we have one more + self.extends_so_far += 1 + + def visit_Include(self, node: nodes.Include, frame: Frame) -> None: + """Handles includes.""" + if node.ignore_missing: + self.writeline("try:") + self.indent() + + func_name = "get_or_select_template" + if isinstance(node.template, nodes.Const): + if isinstance(node.template.value, str): + func_name = "get_template" + elif isinstance(node.template.value, (tuple, list)): + func_name = "select_template" + elif isinstance(node.template, (nodes.Tuple, nodes.List)): + func_name = "select_template" + + self.writeline(f"template = environment.{func_name}(", node) + self.visit(node.template, frame) + self.write(f", {self.name!r})") + if node.ignore_missing: + self.outdent() + self.writeline("except TemplateNotFound:") + self.indent() + self.writeline("pass") + self.outdent() + self.writeline("else:") + self.indent() + + def loop_body() -> None: + self.indent() + self.simple_write("event", frame) + self.outdent() + + if node.with_context: + self.writeline( + f"gen = template.root_render_func(" + "template.new_context(context.get_all(), True," + f" {self.dump_local_context(frame)}))" + ) + self.writeline("try:") + self.indent() + self.writeline(f"{self.choose_async()}for event in gen:") + loop_body() + self.outdent() + self.writeline( + f"finally: {self.choose_async('await gen.aclose()', 'gen.close()')}" + ) + elif self.environment.is_async: + self.writeline( + "for event in (await template._get_default_module_async())" + "._body_stream:" + ) + loop_body() + else: + self.writeline("yield from template._get_default_module()._body_stream") + + if node.ignore_missing: + self.outdent() + + def _import_common( + self, node: t.Union[nodes.Import, nodes.FromImport], frame: Frame + ) -> None: + self.write(f"{self.choose_async('await ')}environment.get_template(") + self.visit(node.template, frame) + self.write(f", {self.name!r}).") + + if node.with_context: + f_name = f"make_module{self.choose_async('_async')}" + self.write( + f"{f_name}(context.get_all(), True, {self.dump_local_context(frame)})" + ) + else: + self.write(f"_get_default_module{self.choose_async('_async')}(context)") + + def visit_Import(self, node: nodes.Import, frame: Frame) -> None: + """Visit regular imports.""" + self.writeline(f"{frame.symbols.ref(node.target)} = ", node) + if frame.toplevel: + self.write(f"context.vars[{node.target!r}] = ") + + self._import_common(node, frame) + + if frame.toplevel and not node.target.startswith("_"): + self.writeline(f"context.exported_vars.discard({node.target!r})") + + def visit_FromImport(self, node: nodes.FromImport, frame: Frame) -> None: + """Visit named imports.""" + self.newline(node) + self.write("included_template = ") + self._import_common(node, frame) + var_names = [] + discarded_names = [] + for name in node.names: + if isinstance(name, tuple): + name, alias = name + else: + alias = name + self.writeline( + f"{frame.symbols.ref(alias)} =" + f" getattr(included_template, {name!r}, missing)" + ) + self.writeline(f"if {frame.symbols.ref(alias)} is missing:") + self.indent() + # The position will contain the template name, and will be formatted + # into a string that will be compiled into an f-string. Curly braces + # in the name must be replaced with escapes so that they will not be + # executed as part of the f-string. + position = self.position(node).replace("{", "{{").replace("}", "}}") + message = ( + "the template {included_template.__name__!r}" + f" (imported on {position})" + f" does not export the requested name {name!r}" + ) + self.writeline( + f"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})" + ) + self.outdent() + if frame.toplevel: + var_names.append(alias) + if not alias.startswith("_"): + discarded_names.append(alias) + + if var_names: + if len(var_names) == 1: + name = var_names[0] + self.writeline(f"context.vars[{name!r}] = {frame.symbols.ref(name)}") + else: + names_kv = ", ".join( + f"{name!r}: {frame.symbols.ref(name)}" for name in var_names + ) + self.writeline(f"context.vars.update({{{names_kv}}})") + if discarded_names: + if len(discarded_names) == 1: + self.writeline(f"context.exported_vars.discard({discarded_names[0]!r})") + else: + names_str = ", ".join(map(repr, discarded_names)) + self.writeline( + f"context.exported_vars.difference_update(({names_str}))" + ) + + def visit_For(self, node: nodes.For, frame: Frame) -> None: + loop_frame = frame.inner() + loop_frame.loop_frame = True + test_frame = frame.inner() + else_frame = frame.inner() + + # try to figure out if we have an extended loop. An extended loop + # is necessary if the loop is in recursive mode if the special loop + # variable is accessed in the body if the body is a scoped block. + extended_loop = ( + node.recursive + or "loop" + in find_undeclared(node.iter_child_nodes(only=("body",)), ("loop",)) + or any(block.scoped for block in node.find_all(nodes.Block)) + ) + + loop_ref = None + if extended_loop: + loop_ref = loop_frame.symbols.declare_parameter("loop") + + loop_frame.symbols.analyze_node(node, for_branch="body") + if node.else_: + else_frame.symbols.analyze_node(node, for_branch="else") + + if node.test: + loop_filter_func = self.temporary_identifier() + test_frame.symbols.analyze_node(node, for_branch="test") + self.writeline(f"{self.func(loop_filter_func)}(fiter):", node.test) + self.indent() + self.enter_frame(test_frame) + self.writeline(self.choose_async("async for ", "for ")) + self.visit(node.target, loop_frame) + self.write(" in ") + self.write(self.choose_async("auto_aiter(fiter)", "fiter")) + self.write(":") + self.indent() + self.writeline("if ", node.test) + self.visit(node.test, test_frame) + self.write(":") + self.indent() + self.writeline("yield ") + self.visit(node.target, loop_frame) + self.outdent(3) + self.leave_frame(test_frame, with_python_scope=True) + + # if we don't have an recursive loop we have to find the shadowed + # variables at that point. Because loops can be nested but the loop + # variable is a special one we have to enforce aliasing for it. + if node.recursive: + self.writeline( + f"{self.func('loop')}(reciter, loop_render_func, depth=0):", node + ) + self.indent() + self.buffer(loop_frame) + + # Use the same buffer for the else frame + else_frame.buffer = loop_frame.buffer + + # make sure the loop variable is a special one and raise a template + # assertion error if a loop tries to write to loop + if extended_loop: + self.writeline(f"{loop_ref} = missing") + + for name in node.find_all(nodes.Name): + if name.ctx == "store" and name.name == "loop": + self.fail( + "Can't assign to special loop variable in for-loop target", + name.lineno, + ) + + if node.else_: + iteration_indicator = self.temporary_identifier() + self.writeline(f"{iteration_indicator} = 1") + + self.writeline(self.choose_async("async for ", "for "), node) + self.visit(node.target, loop_frame) + if extended_loop: + self.write(f", {loop_ref} in {self.choose_async('Async')}LoopContext(") + else: + self.write(" in ") + + if node.test: + self.write(f"{loop_filter_func}(") + if node.recursive: + self.write("reciter") + else: + if self.environment.is_async and not extended_loop: + self.write("auto_aiter(") + self.visit(node.iter, frame) + if self.environment.is_async and not extended_loop: + self.write(")") + if node.test: + self.write(")") + + if node.recursive: + self.write(", undefined, loop_render_func, depth):") + else: + self.write(", undefined):" if extended_loop else ":") + + self.indent() + self.enter_frame(loop_frame) + + self.writeline("_loop_vars = {}") + self.blockvisit(node.body, loop_frame) + if node.else_: + self.writeline(f"{iteration_indicator} = 0") + self.outdent() + self.leave_frame( + loop_frame, with_python_scope=node.recursive and not node.else_ + ) + + if node.else_: + self.writeline(f"if {iteration_indicator}:") + self.indent() + self.enter_frame(else_frame) + self.blockvisit(node.else_, else_frame) + self.leave_frame(else_frame) + self.outdent() + + # if the node was recursive we have to return the buffer contents + # and start the iteration code + if node.recursive: + self.return_buffer_contents(loop_frame) + self.outdent() + self.start_write(frame, node) + self.write(f"{self.choose_async('await ')}loop(") + if self.environment.is_async: + self.write("auto_aiter(") + self.visit(node.iter, frame) + if self.environment.is_async: + self.write(")") + self.write(", loop)") + self.end_write(frame) + + # at the end of the iteration, clear any assignments made in the + # loop from the top level + if self._assign_stack: + self._assign_stack[-1].difference_update(loop_frame.symbols.stores) + + def visit_If(self, node: nodes.If, frame: Frame) -> None: + if_frame = frame.soft() + self.writeline("if ", node) + self.visit(node.test, if_frame) + self.write(":") + self.indent() + self.blockvisit(node.body, if_frame) + self.outdent() + for elif_ in node.elif_: + self.writeline("elif ", elif_) + self.visit(elif_.test, if_frame) + self.write(":") + self.indent() + self.blockvisit(elif_.body, if_frame) + self.outdent() + if node.else_: + self.writeline("else:") + self.indent() + self.blockvisit(node.else_, if_frame) + self.outdent() + + def visit_Macro(self, node: nodes.Macro, frame: Frame) -> None: + macro_frame, macro_ref = self.macro_body(node, frame) + self.newline() + if frame.toplevel: + if not node.name.startswith("_"): + self.write(f"context.exported_vars.add({node.name!r})") + self.writeline(f"context.vars[{node.name!r}] = ") + self.write(f"{frame.symbols.ref(node.name)} = ") + self.macro_def(macro_ref, macro_frame) + + def visit_CallBlock(self, node: nodes.CallBlock, frame: Frame) -> None: + call_frame, macro_ref = self.macro_body(node, frame) + self.writeline("caller = ") + self.macro_def(macro_ref, call_frame) + self.start_write(frame, node) + self.visit_Call(node.call, frame, forward_caller=True) + self.end_write(frame) + + def visit_FilterBlock(self, node: nodes.FilterBlock, frame: Frame) -> None: + filter_frame = frame.inner() + filter_frame.symbols.analyze_node(node) + self.enter_frame(filter_frame) + self.buffer(filter_frame) + self.blockvisit(node.body, filter_frame) + self.start_write(frame, node) + self.visit_Filter(node.filter, filter_frame) + self.end_write(frame) + self.leave_frame(filter_frame) + + def visit_With(self, node: nodes.With, frame: Frame) -> None: + with_frame = frame.inner() + with_frame.symbols.analyze_node(node) + self.enter_frame(with_frame) + for target, expr in zip(node.targets, node.values): + self.newline() + self.visit(target, with_frame) + self.write(" = ") + self.visit(expr, frame) + self.blockvisit(node.body, with_frame) + self.leave_frame(with_frame) + + def visit_ExprStmt(self, node: nodes.ExprStmt, frame: Frame) -> None: + self.newline(node) + self.visit(node.node, frame) + + class _FinalizeInfo(t.NamedTuple): + const: t.Optional[t.Callable[..., str]] + src: t.Optional[str] + + @staticmethod + def _default_finalize(value: t.Any) -> t.Any: + """The default finalize function if the environment isn't + configured with one. Or, if the environment has one, this is + called on that function's output for constants. + """ + return str(value) + + _finalize: t.Optional[_FinalizeInfo] = None + + def _make_finalize(self) -> _FinalizeInfo: + """Build the finalize function to be used on constants and at + runtime. Cached so it's only created once for all output nodes. + + Returns a ``namedtuple`` with the following attributes: + + ``const`` + A function to finalize constant data at compile time. + + ``src`` + Source code to output around nodes to be evaluated at + runtime. + """ + if self._finalize is not None: + return self._finalize + + finalize: t.Optional[t.Callable[..., t.Any]] + finalize = default = self._default_finalize + src = None + + if self.environment.finalize: + src = "environment.finalize(" + env_finalize = self.environment.finalize + pass_arg = { + _PassArg.context: "context", + _PassArg.eval_context: "context.eval_ctx", + _PassArg.environment: "environment", + }.get( + _PassArg.from_obj(env_finalize) # type: ignore + ) + finalize = None + + if pass_arg is None: + + def finalize(value: t.Any) -> t.Any: # noqa: F811 + return default(env_finalize(value)) + + else: + src = f"{src}{pass_arg}, " + + if pass_arg == "environment": + + def finalize(value: t.Any) -> t.Any: # noqa: F811 + return default(env_finalize(self.environment, value)) + + self._finalize = self._FinalizeInfo(finalize, src) + return self._finalize + + def _output_const_repr(self, group: t.Iterable[t.Any]) -> str: + """Given a group of constant values converted from ``Output`` + child nodes, produce a string to write to the template module + source. + """ + return repr(concat(group)) + + def _output_child_to_const( + self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo + ) -> str: + """Try to optimize a child of an ``Output`` node by trying to + convert it to constant, finalized data at compile time. + + If :exc:`Impossible` is raised, the node is not constant and + will be evaluated at runtime. Any other exception will also be + evaluated at runtime for easier debugging. + """ + const = node.as_const(frame.eval_ctx) + + if frame.eval_ctx.autoescape: + const = escape(const) + + # Template data doesn't go through finalize. + if isinstance(node, nodes.TemplateData): + return str(const) + + return finalize.const(const) # type: ignore + + def _output_child_pre( + self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo + ) -> None: + """Output extra source code before visiting a child of an + ``Output`` node. + """ + if frame.eval_ctx.volatile: + self.write("(escape if context.eval_ctx.autoescape else str)(") + elif frame.eval_ctx.autoescape: + self.write("escape(") + else: + self.write("str(") + + if finalize.src is not None: + self.write(finalize.src) + + def _output_child_post( + self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo + ) -> None: + """Output extra source code after visiting a child of an + ``Output`` node. + """ + self.write(")") + + if finalize.src is not None: + self.write(")") + + def visit_Output(self, node: nodes.Output, frame: Frame) -> None: + # If an extends is active, don't render outside a block. + if frame.require_output_check: + # A top-level extends is known to exist at compile time. + if self.has_known_extends: + return + + self.writeline("if parent_template is None:") + self.indent() + + finalize = self._make_finalize() + body: t.List[t.Union[t.List[t.Any], nodes.Expr]] = [] + + # Evaluate constants at compile time if possible. Each item in + # body will be either a list of static data or a node to be + # evaluated at runtime. + for child in node.nodes: + try: + if not ( + # If the finalize function requires runtime context, + # constants can't be evaluated at compile time. + finalize.const + # Unless it's basic template data that won't be + # finalized anyway. + or isinstance(child, nodes.TemplateData) + ): + raise nodes.Impossible() + + const = self._output_child_to_const(child, frame, finalize) + except (nodes.Impossible, Exception): + # The node was not constant and needs to be evaluated at + # runtime. Or another error was raised, which is easier + # to debug at runtime. + body.append(child) + continue + + if body and isinstance(body[-1], list): + body[-1].append(const) + else: + body.append([const]) + + if frame.buffer is not None: + if len(body) == 1: + self.writeline(f"{frame.buffer}.append(") + else: + self.writeline(f"{frame.buffer}.extend((") + + self.indent() + + for item in body: + if isinstance(item, list): + # A group of constant data to join and output. + val = self._output_const_repr(item) + + if frame.buffer is None: + self.writeline("yield " + val) + else: + self.writeline(val + ",") + else: + if frame.buffer is None: + self.writeline("yield ", item) + else: + self.newline(item) + + # A node to be evaluated at runtime. + self._output_child_pre(item, frame, finalize) + self.visit(item, frame) + self._output_child_post(item, frame, finalize) + + if frame.buffer is not None: + self.write(",") + + if frame.buffer is not None: + self.outdent() + self.writeline(")" if len(body) == 1 else "))") + + if frame.require_output_check: + self.outdent() + + def visit_Assign(self, node: nodes.Assign, frame: Frame) -> None: + self.push_assign_tracking() + + # ``a.b`` is allowed for assignment, and is parsed as an NSRef. However, + # it is only valid if it references a Namespace object. Emit a check for + # that for each ref here, before assignment code is emitted. This can't + # be done in visit_NSRef as the ref could be in the middle of a tuple. + seen_refs: t.Set[str] = set() + + for nsref in node.find_all(nodes.NSRef): + if nsref.name in seen_refs: + # Only emit the check for each reference once, in case the same + # ref is used multiple times in a tuple, `ns.a, ns.b = c, d`. + continue + + seen_refs.add(nsref.name) + ref = frame.symbols.ref(nsref.name) + self.writeline(f"if not isinstance({ref}, Namespace):") + self.indent() + self.writeline( + "raise TemplateRuntimeError" + '("cannot assign attribute on non-namespace object")' + ) + self.outdent() + + self.newline(node) + self.visit(node.target, frame) + self.write(" = ") + self.visit(node.node, frame) + self.pop_assign_tracking(frame) + + def visit_AssignBlock(self, node: nodes.AssignBlock, frame: Frame) -> None: + self.push_assign_tracking() + block_frame = frame.inner() + # This is a special case. Since a set block always captures we + # will disable output checks. This way one can use set blocks + # toplevel even in extended templates. + block_frame.require_output_check = False + block_frame.symbols.analyze_node(node) + self.enter_frame(block_frame) + self.buffer(block_frame) + self.blockvisit(node.body, block_frame) + self.newline(node) + self.visit(node.target, frame) + self.write(" = (Markup if context.eval_ctx.autoescape else identity)(") + if node.filter is not None: + self.visit_Filter(node.filter, block_frame) + else: + self.write(f"concat({block_frame.buffer})") + self.write(")") + self.pop_assign_tracking(frame) + self.leave_frame(block_frame) + + # -- Expression Visitors + + def visit_Name(self, node: nodes.Name, frame: Frame) -> None: + if node.ctx == "store" and ( + frame.toplevel or frame.loop_frame or frame.block_frame + ): + if self._assign_stack: + self._assign_stack[-1].add(node.name) + ref = frame.symbols.ref(node.name) + + # If we are looking up a variable we might have to deal with the + # case where it's undefined. We can skip that case if the load + # instruction indicates a parameter which are always defined. + if node.ctx == "load": + load = frame.symbols.find_load(ref) + if not ( + load is not None + and load[0] == VAR_LOAD_PARAMETER + and not self.parameter_is_undeclared(ref) + ): + self.write( + f"(undefined(name={node.name!r}) if {ref} is missing else {ref})" + ) + return + + self.write(ref) + + def visit_NSRef(self, node: nodes.NSRef, frame: Frame) -> None: + # NSRef is a dotted assignment target a.b=c, but uses a[b]=c internally. + # visit_Assign emits code to validate that each ref is to a Namespace + # object only. That can't be emitted here as the ref could be in the + # middle of a tuple assignment. + ref = frame.symbols.ref(node.name) + self.writeline(f"{ref}[{node.attr!r}]") + + def visit_Const(self, node: nodes.Const, frame: Frame) -> None: + val = node.as_const(frame.eval_ctx) + if isinstance(val, float): + self.write(str(val)) + else: + self.write(repr(val)) + + def visit_TemplateData(self, node: nodes.TemplateData, frame: Frame) -> None: + try: + self.write(repr(node.as_const(frame.eval_ctx))) + except nodes.Impossible: + self.write( + f"(Markup if context.eval_ctx.autoescape else identity)({node.data!r})" + ) + + def visit_Tuple(self, node: nodes.Tuple, frame: Frame) -> None: + self.write("(") + idx = -1 + for idx, item in enumerate(node.items): + if idx: + self.write(", ") + self.visit(item, frame) + self.write(",)" if idx == 0 else ")") + + def visit_List(self, node: nodes.List, frame: Frame) -> None: + self.write("[") + for idx, item in enumerate(node.items): + if idx: + self.write(", ") + self.visit(item, frame) + self.write("]") + + def visit_Dict(self, node: nodes.Dict, frame: Frame) -> None: + self.write("{") + for idx, item in enumerate(node.items): + if idx: + self.write(", ") + self.visit(item.key, frame) + self.write(": ") + self.visit(item.value, frame) + self.write("}") + + visit_Add = _make_binop("+") + visit_Sub = _make_binop("-") + visit_Mul = _make_binop("*") + visit_Div = _make_binop("/") + visit_FloorDiv = _make_binop("//") + visit_Pow = _make_binop("**") + visit_Mod = _make_binop("%") + visit_And = _make_binop("and") + visit_Or = _make_binop("or") + visit_Pos = _make_unop("+") + visit_Neg = _make_unop("-") + visit_Not = _make_unop("not ") + + @optimizeconst + def visit_Concat(self, node: nodes.Concat, frame: Frame) -> None: + if frame.eval_ctx.volatile: + func_name = "(markup_join if context.eval_ctx.volatile else str_join)" + elif frame.eval_ctx.autoescape: + func_name = "markup_join" + else: + func_name = "str_join" + self.write(f"{func_name}((") + for arg in node.nodes: + self.visit(arg, frame) + self.write(", ") + self.write("))") + + @optimizeconst + def visit_Compare(self, node: nodes.Compare, frame: Frame) -> None: + self.write("(") + self.visit(node.expr, frame) + for op in node.ops: + self.visit(op, frame) + self.write(")") + + def visit_Operand(self, node: nodes.Operand, frame: Frame) -> None: + self.write(f" {operators[node.op]} ") + self.visit(node.expr, frame) + + @optimizeconst + def visit_Getattr(self, node: nodes.Getattr, frame: Frame) -> None: + if self.environment.is_async: + self.write("(await auto_await(") + + self.write("environment.getattr(") + self.visit(node.node, frame) + self.write(f", {node.attr!r})") + + if self.environment.is_async: + self.write("))") + + @optimizeconst + def visit_Getitem(self, node: nodes.Getitem, frame: Frame) -> None: + # slices bypass the environment getitem method. + if isinstance(node.arg, nodes.Slice): + self.visit(node.node, frame) + self.write("[") + self.visit(node.arg, frame) + self.write("]") + else: + if self.environment.is_async: + self.write("(await auto_await(") + + self.write("environment.getitem(") + self.visit(node.node, frame) + self.write(", ") + self.visit(node.arg, frame) + self.write(")") + + if self.environment.is_async: + self.write("))") + + def visit_Slice(self, node: nodes.Slice, frame: Frame) -> None: + if node.start is not None: + self.visit(node.start, frame) + self.write(":") + if node.stop is not None: + self.visit(node.stop, frame) + if node.step is not None: + self.write(":") + self.visit(node.step, frame) + + @contextmanager + def _filter_test_common( + self, node: t.Union[nodes.Filter, nodes.Test], frame: Frame, is_filter: bool + ) -> t.Iterator[None]: + if self.environment.is_async: + self.write("(await auto_await(") + + if is_filter: + self.write(f"{self.filters[node.name]}(") + func = self.environment.filters.get(node.name) + else: + self.write(f"{self.tests[node.name]}(") + func = self.environment.tests.get(node.name) + + # When inside an If or CondExpr frame, allow the filter to be + # undefined at compile time and only raise an error if it's + # actually called at runtime. See pull_dependencies. + if func is None and not frame.soft_frame: + type_name = "filter" if is_filter else "test" + self.fail(f"No {type_name} named {node.name!r}.", node.lineno) + + pass_arg = { + _PassArg.context: "context", + _PassArg.eval_context: "context.eval_ctx", + _PassArg.environment: "environment", + }.get( + _PassArg.from_obj(func) # type: ignore + ) + + if pass_arg is not None: + self.write(f"{pass_arg}, ") + + # Back to the visitor function to handle visiting the target of + # the filter or test. + yield + + self.signature(node, frame) + self.write(")") + + if self.environment.is_async: + self.write("))") + + @optimizeconst + def visit_Filter(self, node: nodes.Filter, frame: Frame) -> None: + with self._filter_test_common(node, frame, True): + # if the filter node is None we are inside a filter block + # and want to write to the current buffer + if node.node is not None: + self.visit(node.node, frame) + elif frame.eval_ctx.volatile: + self.write( + f"(Markup(concat({frame.buffer}))" + f" if context.eval_ctx.autoescape else concat({frame.buffer}))" + ) + elif frame.eval_ctx.autoescape: + self.write(f"Markup(concat({frame.buffer}))") + else: + self.write(f"concat({frame.buffer})") + + @optimizeconst + def visit_Test(self, node: nodes.Test, frame: Frame) -> None: + with self._filter_test_common(node, frame, False): + self.visit(node.node, frame) + + @optimizeconst + def visit_CondExpr(self, node: nodes.CondExpr, frame: Frame) -> None: + frame = frame.soft() + + def write_expr2() -> None: + if node.expr2 is not None: + self.visit(node.expr2, frame) + return + + self.write( + f'cond_expr_undefined("the inline if-expression on' + f" {self.position(node)} evaluated to false and no else" + f' section was defined.")' + ) + + self.write("(") + self.visit(node.expr1, frame) + self.write(" if ") + self.visit(node.test, frame) + self.write(" else ") + write_expr2() + self.write(")") + + @optimizeconst + def visit_Call( + self, node: nodes.Call, frame: Frame, forward_caller: bool = False + ) -> None: + if self.environment.is_async: + self.write("(await auto_await(") + if self.environment.sandboxed: + self.write("environment.call(context, ") + else: + self.write("context.call(") + self.visit(node.node, frame) + extra_kwargs = {"caller": "caller"} if forward_caller else None + loop_kwargs = {"_loop_vars": "_loop_vars"} if frame.loop_frame else {} + block_kwargs = {"_block_vars": "_block_vars"} if frame.block_frame else {} + if extra_kwargs: + extra_kwargs.update(loop_kwargs, **block_kwargs) + elif loop_kwargs or block_kwargs: + extra_kwargs = dict(loop_kwargs, **block_kwargs) + self.signature(node, frame, extra_kwargs) + self.write(")") + if self.environment.is_async: + self.write("))") + + def visit_Keyword(self, node: nodes.Keyword, frame: Frame) -> None: + self.write(node.key + "=") + self.visit(node.value, frame) + + # -- Unused nodes for extensions + + def visit_MarkSafe(self, node: nodes.MarkSafe, frame: Frame) -> None: + self.write("Markup(") + self.visit(node.expr, frame) + self.write(")") + + def visit_MarkSafeIfAutoescape( + self, node: nodes.MarkSafeIfAutoescape, frame: Frame + ) -> None: + self.write("(Markup if context.eval_ctx.autoescape else identity)(") + self.visit(node.expr, frame) + self.write(")") + + def visit_EnvironmentAttribute( + self, node: nodes.EnvironmentAttribute, frame: Frame + ) -> None: + self.write("environment." + node.name) + + def visit_ExtensionAttribute( + self, node: nodes.ExtensionAttribute, frame: Frame + ) -> None: + self.write(f"environment.extensions[{node.identifier!r}].{node.name}") + + def visit_ImportedName(self, node: nodes.ImportedName, frame: Frame) -> None: + self.write(self.import_aliases[node.importname]) + + def visit_InternalName(self, node: nodes.InternalName, frame: Frame) -> None: + self.write(node.name) + + def visit_ContextReference( + self, node: nodes.ContextReference, frame: Frame + ) -> None: + self.write("context") + + def visit_DerivedContextReference( + self, node: nodes.DerivedContextReference, frame: Frame + ) -> None: + self.write(self.derive_context(frame)) + + def visit_Continue(self, node: nodes.Continue, frame: Frame) -> None: + self.writeline("continue", node) + + def visit_Break(self, node: nodes.Break, frame: Frame) -> None: + self.writeline("break", node) + + def visit_Scope(self, node: nodes.Scope, frame: Frame) -> None: + scope_frame = frame.inner() + scope_frame.symbols.analyze_node(node) + self.enter_frame(scope_frame) + self.blockvisit(node.body, scope_frame) + self.leave_frame(scope_frame) + + def visit_OverlayScope(self, node: nodes.OverlayScope, frame: Frame) -> None: + ctx = self.temporary_identifier() + self.writeline(f"{ctx} = {self.derive_context(frame)}") + self.writeline(f"{ctx}.vars = ") + self.visit(node.context, frame) + self.push_context_reference(ctx) + + scope_frame = frame.inner(isolated=True) + scope_frame.symbols.analyze_node(node) + self.enter_frame(scope_frame) + self.blockvisit(node.body, scope_frame) + self.leave_frame(scope_frame) + self.pop_context_reference() + + def visit_EvalContextModifier( + self, node: nodes.EvalContextModifier, frame: Frame + ) -> None: + for keyword in node.options: + self.writeline(f"context.eval_ctx.{keyword.key} = ") + self.visit(keyword.value, frame) + try: + val = keyword.value.as_const(frame.eval_ctx) + except nodes.Impossible: + frame.eval_ctx.volatile = True + else: + setattr(frame.eval_ctx, keyword.key, val) + + def visit_ScopedEvalContextModifier( + self, node: nodes.ScopedEvalContextModifier, frame: Frame + ) -> None: + old_ctx_name = self.temporary_identifier() + saved_ctx = frame.eval_ctx.save() + self.writeline(f"{old_ctx_name} = context.eval_ctx.save()") + self.visit_EvalContextModifier(node, frame) + for child in node.body: + self.visit(child, frame) + frame.eval_ctx.revert(saved_ctx) + self.writeline(f"context.eval_ctx.revert({old_ctx_name})") diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/constants.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..41a1c23b0a7fe134b1f662545876eb65b31b071e --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/constants.py @@ -0,0 +1,20 @@ +#: list of lorem ipsum words used by the lipsum() helper function +LOREM_IPSUM_WORDS = """\ +a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at +auctor augue bibendum blandit class commodo condimentum congue consectetuer +consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus +diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend +elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames +faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac +hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum +justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem +luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie +mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non +nonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque +penatibus per pharetra phasellus placerat platea porta porttitor posuere +potenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus +ridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit +sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor +tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices +ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus +viverra volutpat vulputate""" diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/debug.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..eeeeee78b620f5d0745133b4629647973cd7af87 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/debug.py @@ -0,0 +1,191 @@ +import sys +import typing as t +from types import CodeType +from types import TracebackType + +from .exceptions import TemplateSyntaxError +from .utils import internal_code +from .utils import missing + +if t.TYPE_CHECKING: + from .runtime import Context + + +def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseException: + """Rewrite the current exception to replace any tracebacks from + within compiled template code with tracebacks that look like they + came from the template source. + + This must be called within an ``except`` block. + + :param source: For ``TemplateSyntaxError``, the original source if + known. + :return: The original exception with the rewritten traceback. + """ + _, exc_value, tb = sys.exc_info() + exc_value = t.cast(BaseException, exc_value) + tb = t.cast(TracebackType, tb) + + if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated: + exc_value.translated = True + exc_value.source = source + # Remove the old traceback, otherwise the frames from the + # compiler still show up. + exc_value.with_traceback(None) + # Outside of runtime, so the frame isn't executing template + # code, but it still needs to point at the template. + tb = fake_traceback( + exc_value, None, exc_value.filename or "", exc_value.lineno + ) + else: + # Skip the frame for the render function. + tb = tb.tb_next + + stack = [] + + # Build the stack of traceback object, replacing any in template + # code with the source file and line information. + while tb is not None: + # Skip frames decorated with @internalcode. These are internal + # calls that aren't useful in template debugging output. + if tb.tb_frame.f_code in internal_code: + tb = tb.tb_next + continue + + template = tb.tb_frame.f_globals.get("__jinja_template__") + + if template is not None: + lineno = template.get_corresponding_lineno(tb.tb_lineno) + fake_tb = fake_traceback(exc_value, tb, template.filename, lineno) + stack.append(fake_tb) + else: + stack.append(tb) + + tb = tb.tb_next + + tb_next = None + + # Assign tb_next in reverse to avoid circular references. + for tb in reversed(stack): + tb.tb_next = tb_next + tb_next = tb + + return exc_value.with_traceback(tb_next) + + +def fake_traceback( # type: ignore + exc_value: BaseException, tb: t.Optional[TracebackType], filename: str, lineno: int +) -> TracebackType: + """Produce a new traceback object that looks like it came from the + template source instead of the compiled code. The filename, line + number, and location name will point to the template, and the local + variables will be the current template context. + + :param exc_value: The original exception to be re-raised to create + the new traceback. + :param tb: The original traceback to get the local variables and + code info from. + :param filename: The template filename. + :param lineno: The line number in the template source. + """ + if tb is not None: + # Replace the real locals with the context that would be + # available at that point in the template. + locals = get_template_locals(tb.tb_frame.f_locals) + locals.pop("__jinja_exception__", None) + else: + locals = {} + + globals = { + "__name__": filename, + "__file__": filename, + "__jinja_exception__": exc_value, + } + # Raise an exception at the correct line number. + code: CodeType = compile( + "\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec" + ) + + # Build a new code object that points to the template file and + # replaces the location with a block name. + location = "template" + + if tb is not None: + function = tb.tb_frame.f_code.co_name + + if function == "root": + location = "top-level template code" + elif function.startswith("block_"): + location = f"block {function[6:]!r}" + + if sys.version_info >= (3, 8): + code = code.replace(co_name=location) + else: + code = CodeType( + code.co_argcount, + code.co_kwonlyargcount, + code.co_nlocals, + code.co_stacksize, + code.co_flags, + code.co_code, + code.co_consts, + code.co_names, + code.co_varnames, + code.co_filename, + location, + code.co_firstlineno, + code.co_lnotab, + code.co_freevars, + code.co_cellvars, + ) + + # Execute the new code, which is guaranteed to raise, and return + # the new traceback without this frame. + try: + exec(code, globals, locals) + except BaseException: + return sys.exc_info()[2].tb_next # type: ignore + + +def get_template_locals(real_locals: t.Mapping[str, t.Any]) -> t.Dict[str, t.Any]: + """Based on the runtime locals, get the context that would be + available at that point in the template. + """ + # Start with the current template context. + ctx: t.Optional[Context] = real_locals.get("context") + + if ctx is not None: + data: t.Dict[str, t.Any] = ctx.get_all().copy() + else: + data = {} + + # Might be in a derived context that only sets local variables + # rather than pushing a context. Local variables follow the scheme + # l_depth_name. Find the highest-depth local that has a value for + # each name. + local_overrides: t.Dict[str, t.Tuple[int, t.Any]] = {} + + for name, value in real_locals.items(): + if not name.startswith("l_") or value is missing: + # Not a template variable, or no longer relevant. + continue + + try: + _, depth_str, name = name.split("_", 2) + depth = int(depth_str) + except ValueError: + continue + + cur_depth = local_overrides.get(name, (-1,))[0] + + if cur_depth < depth: + local_overrides[name] = (depth, value) + + # Modify the context with any derived context. + for name, (_, value) in local_overrides.items(): + if value is missing: + data.pop(name, None) + else: + data[name] = value + + return data diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/defaults.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..638cad3d2d8907330bde56e2b76c9b185c523b45 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/defaults.py @@ -0,0 +1,48 @@ +import typing as t + +from .filters import FILTERS as DEFAULT_FILTERS # noqa: F401 +from .tests import TESTS as DEFAULT_TESTS # noqa: F401 +from .utils import Cycler +from .utils import generate_lorem_ipsum +from .utils import Joiner +from .utils import Namespace + +if t.TYPE_CHECKING: + import typing_extensions as te + +# defaults for the parser / lexer +BLOCK_START_STRING = "{%" +BLOCK_END_STRING = "%}" +VARIABLE_START_STRING = "{{" +VARIABLE_END_STRING = "}}" +COMMENT_START_STRING = "{#" +COMMENT_END_STRING = "#}" +LINE_STATEMENT_PREFIX: t.Optional[str] = None +LINE_COMMENT_PREFIX: t.Optional[str] = None +TRIM_BLOCKS = False +LSTRIP_BLOCKS = False +NEWLINE_SEQUENCE: "te.Literal['\\n', '\\r\\n', '\\r']" = "\n" +KEEP_TRAILING_NEWLINE = False + +# default filters, tests and namespace + +DEFAULT_NAMESPACE = { + "range": range, + "dict": dict, + "lipsum": generate_lorem_ipsum, + "cycler": Cycler, + "joiner": Joiner, + "namespace": Namespace, +} + +# default policies +DEFAULT_POLICIES: t.Dict[str, t.Any] = { + "compiler.ascii_str": True, + "urlize.rel": "noopener", + "urlize.target": None, + "urlize.extra_schemes": None, + "truncate.leeway": 5, + "json.dumps_function": None, + "json.dumps_kwargs": {"sort_keys": True}, + "ext.i18n.trimmed": False, +} diff --git a/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/environment.py b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..0fc6e5be87ab8273f6056ddfede07e1be28f1495 --- /dev/null +++ b/pace_revision_1/.venv-pace/lib/python3.11/site-packages/jinja2/environment.py @@ -0,0 +1,1672 @@ +"""Classes for managing templates and their runtime and compile time +options. +""" + +import os +import typing +import typing as t +import weakref +from collections import ChainMap +from functools import lru_cache +from functools import partial +from functools import reduce +from types import CodeType + +from markupsafe import Markup + +from . import nodes +from .compiler import CodeGenerator +from .compiler import generate +from .defaults import BLOCK_END_STRING +from .defaults import BLOCK_START_STRING +from .defaults import COMMENT_END_STRING +from .defaults import COMMENT_START_STRING +from .defaults import DEFAULT_FILTERS # type: ignore[attr-defined] +from .defaults import DEFAULT_NAMESPACE +from .defaults import DEFAULT_POLICIES +from .defaults import DEFAULT_TESTS # type: ignore[attr-defined] +from .defaults import KEEP_TRAILING_NEWLINE +from .defaults import LINE_COMMENT_PREFIX +from .defaults import LINE_STATEMENT_PREFIX +from .defaults import LSTRIP_BLOCKS +from .defaults import NEWLINE_SEQUENCE +from .defaults import TRIM_BLOCKS +from .defaults import VARIABLE_END_STRING +from .defaults import VARIABLE_START_STRING +from .exceptions import TemplateNotFound +from .exceptions import TemplateRuntimeError +from .exceptions import TemplatesNotFound +from .exceptions import TemplateSyntaxError +from .exceptions import UndefinedError +from .lexer import get_lexer +from .lexer import Lexer +from .lexer import TokenStream +from .nodes import EvalContext +from .parser import Parser +from .runtime import Context +from .runtime import new_context +from .runtime import Undefined +from .utils import _PassArg +from .utils import concat +from .utils import consume +from .utils import import_string +from .utils import internalcode +from .utils import LRUCache +from .utils import missing + +if t.TYPE_CHECKING: + import typing_extensions as te + + from .bccache import BytecodeCache + from .ext import Extension + from .loaders import BaseLoader + +_env_bound = t.TypeVar("_env_bound", bound="Environment") + + +# for direct template usage we have up to ten living environments +@lru_cache(maxsize=10) +def get_spontaneous_environment(cls: t.Type[_env_bound], *args: t.Any) -> _env_bound: + """Return a new spontaneous environment. A spontaneous environment + is used for templates created directly rather than through an + existing environment. + + :param cls: Environment class to create. + :param args: Positional arguments passed to environment. + """ + env = cls(*args) + env.shared = True + return env + + +def create_cache( + size: int, +) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]: + """Return the cache class for the given size.""" + if size == 0: + return None + + if size < 0: + return {} + + return LRUCache(size) # type: ignore + + +def copy_cache( + cache: t.Optional[t.MutableMapping[t.Any, t.Any]], +) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]: + """Create an empty copy of the given cache.""" + if cache is None: + return None + + if type(cache) is dict: # noqa E721 + return {} + + return LRUCache(cache.capacity) # type: ignore + + +def load_extensions( + environment: "Environment", + extensions: t.Sequence[t.Union[str, t.Type["Extension"]]], +) -> t.Dict[str, "Extension"]: + """Load the extensions from the list and bind it to the environment. + Returns a dict of instantiated extensions. + """ + result = {} + + for extension in extensions: + if isinstance(extension, str): + extension = t.cast(t.Type["Extension"], import_string(extension)) + + result[extension.identifier] = extension(environment) + + return result + + +def _environment_config_check(environment: _env_bound) -> _env_bound: + """Perform a sanity check on the environment.""" + assert issubclass( + environment.undefined, Undefined + ), "'undefined' must be a subclass of 'jinja2.Undefined'." + assert ( + environment.block_start_string + != environment.variable_start_string + != environment.comment_start_string + ), "block, variable and comment start strings must be different." + assert environment.newline_sequence in { + "\r", + "\r\n", + "\n", + }, "'newline_sequence' must be one of '\\n', '\\r\\n', or '\\r'." + return environment + + +class Environment: + r"""The core component of Jinja is the `Environment`. It contains + important shared variables like configuration, filters, tests, + globals and others. Instances of this class may be modified if + they are not shared and if no template was loaded so far. + Modifications on environments after the first template was loaded + will lead to surprising effects and undefined behavior. + + Here are the possible initialization parameters: + + `block_start_string` + The string marking the beginning of a block. Defaults to ``'{%'``. + + `block_end_string` + The string marking the end of a block. Defaults to ``'%}'``. + + `variable_start_string` + The string marking the beginning of a print statement. + Defaults to ``'{{'``. + + `variable_end_string` + The string marking the end of a print statement. Defaults to + ``'}}'``. + + `comment_start_string` + The string marking the beginning of a comment. Defaults to ``'{#'``. + + `comment_end_string` + The string marking the end of a comment. Defaults to ``'#}'``. + + `line_statement_prefix` + If given and a string, this will be used as prefix for line based + statements. See also :ref:`line-statements`. + + `line_comment_prefix` + If given and a string, this will be used as prefix for line based + comments. See also :ref:`line-statements`. + + .. versionadded:: 2.2 + + `trim_blocks` + If this is set to ``True`` the first newline after a block is + removed (block, not variable tag!). Defaults to `False`. + + `lstrip_blocks` + If this is set to ``True`` leading spaces and tabs are stripped + from the start of a line to a block. Defaults to `False`. + + `newline_sequence` + The sequence that starts a newline. Must be one of ``'\r'``, + ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a + useful default for Linux and OS X systems as well as web + applications. + + `keep_trailing_newline` + Preserve the trailing newline when rendering templates. + The default is ``False``, which causes a single newline, + if present, to be stripped from the end of the template. + + .. versionadded:: 2.7 + + `extensions` + List of Jinja extensions to use. This can either be import paths + as strings or extension classes. For more information have a + look at :ref:`the extensions documentation `. + + `optimized` + should the optimizer be enabled? Default is ``True``. + + `undefined` + :class:`Undefined` or a subclass of it that is used to represent + undefined values in the template. + + `finalize` + A callable that can be used to process the result of a variable + expression before it is output. For example one can convert + ``None`` implicitly into an empty string here. + + `autoescape` + If set to ``True`` the XML/HTML autoescaping feature is enabled by + default. For more details about autoescaping see + :class:`~markupsafe.Markup`. As of Jinja 2.4 this can also + be a callable that is passed the template name and has to + return ``True`` or ``False`` depending on autoescape should be + enabled by default. + + .. versionchanged:: 2.4 + `autoescape` can now be a function + + `loader` + The template loader for this environment. + + `cache_size` + The size of the cache. Per default this is ``400`` which means + that if more than 400 templates are loaded the loader will clean + out the least recently used template. If the cache size is set to + ``0`` templates are recompiled all the time, if the cache size is + ``-1`` the cache will not be cleaned. + + .. versionchanged:: 2.8 + The cache size was increased to 400 from a low 50. + + `auto_reload` + Some loaders load templates from locations where the template + sources may change (ie: file system or database). If + ``auto_reload`` is set to ``True`` (default) every time a template is + requested the loader checks if the source changed and if yes, it + will reload the template. For higher performance it's possible to + disable that. + + `bytecode_cache` + If set to a bytecode cache object, this object will provide a + cache for the internal Jinja bytecode so that templates don't + have to be parsed if they were not changed. + + See :ref:`bytecode-cache` for more information. + + `enable_async` + If set to true this enables async template execution which + allows using async functions and generators. + """ + + #: if this environment is sandboxed. Modifying this variable won't make + #: the environment sandboxed though. For a real sandboxed environment + #: have a look at jinja2.sandbox. This flag alone controls the code + #: generation by the compiler. + sandboxed = False + + #: True if the environment is just an overlay + overlayed = False + + #: the environment this environment is linked to if it is an overlay + linked_to: t.Optional["Environment"] = None + + #: shared environments have this set to `True`. A shared environment + #: must not be modified + shared = False + + #: the class that is used for code generation. See + #: :class:`~jinja2.compiler.CodeGenerator` for more information. + code_generator_class: t.Type["CodeGenerator"] = CodeGenerator + + concat = "".join + + #: the context class that is used for templates. See + #: :class:`~jinja2.runtime.Context` for more information. + context_class: t.Type[Context] = Context + + template_class: t.Type["Template"] + + def __init__( + self, + block_start_string: str = BLOCK_START_STRING, + block_end_string: str = BLOCK_END_STRING, + variable_start_string: str = VARIABLE_START_STRING, + variable_end_string: str = VARIABLE_END_STRING, + comment_start_string: str = COMMENT_START_STRING, + comment_end_string: str = COMMENT_END_STRING, + line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX, + line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX, + trim_blocks: bool = TRIM_BLOCKS, + lstrip_blocks: bool = LSTRIP_BLOCKS, + newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE, + keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE, + extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (), + optimized: bool = True, + undefined: t.Type[Undefined] = Undefined, + finalize: t.Optional[t.Callable[..., t.Any]] = None, + autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False, + loader: t.Optional["BaseLoader"] = None, + cache_size: int = 400, + auto_reload: bool = True, + bytecode_cache: t.Optional["BytecodeCache"] = None, + enable_async: bool = False, + ): + # !!Important notice!! + # The constructor accepts quite a few arguments that should be + # passed by keyword rather than position. However it's important to + # not change the order of arguments because it's used at least + # internally in those cases: + # - spontaneous environments (i18n extension and Template) + # - unittests + # If parameter changes are required only add parameters at the end + # and don't change the arguments (or the defaults!) of the arguments + # existing already. + + # lexer / parser information + self.block_start_string = block_start_string + self.block_end_string = block_end_string + self.variable_start_string = variable_start_string + self.variable_end_string = variable_end_string + self.comment_start_string = comment_start_string + self.comment_end_string = comment_end_string + self.line_statement_prefix = line_statement_prefix + self.line_comment_prefix = line_comment_prefix + self.trim_blocks = trim_blocks + self.lstrip_blocks = lstrip_blocks + self.newline_sequence = newline_sequence + self.keep_trailing_newline = keep_trailing_newline + + # runtime information + self.undefined: t.Type[Undefined] = undefined + self.optimized = optimized + self.finalize = finalize + self.autoescape = autoescape + + # defaults + self.filters = DEFAULT_FILTERS.copy() + self.tests = DEFAULT_TESTS.copy() + self.globals = DEFAULT_NAMESPACE.copy() + + # set the loader provided + self.loader = loader + self.cache = create_cache(cache_size) + self.bytecode_cache = bytecode_cache + self.auto_reload = auto_reload + + # configurable policies + self.policies = DEFAULT_POLICIES.copy() + + # load extensions + self.extensions = load_extensions(self, extensions) + + self.is_async = enable_async + _environment_config_check(self) + + def add_extension(self, extension: t.Union[str, t.Type["Extension"]]) -> None: + """Adds an extension after the environment was created. + + .. versionadded:: 2.5 + """ + self.extensions.update(load_extensions(self, [extension])) + + def extend(self, **attributes: t.Any) -> None: + """Add the items to the instance of the environment if they do not exist + yet. This is used by :ref:`extensions ` to register + callbacks and configuration values without breaking inheritance. + """ + for key, value in attributes.items(): + if not hasattr(self, key): + setattr(self, key, value) + + def overlay( + self, + block_start_string: str = missing, + block_end_string: str = missing, + variable_start_string: str = missing, + variable_end_string: str = missing, + comment_start_string: str = missing, + comment_end_string: str = missing, + line_statement_prefix: t.Optional[str] = missing, + line_comment_prefix: t.Optional[str] = missing, + trim_blocks: bool = missing, + lstrip_blocks: bool = missing, + newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing, + keep_trailing_newline: bool = missing, + extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = missing, + optimized: bool = missing, + undefined: t.Type[Undefined] = missing, + finalize: t.Optional[t.Callable[..., t.Any]] = missing, + autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = missing, + loader: t.Optional["BaseLoader"] = missing, + cache_size: int = missing, + auto_reload: bool = missing, + bytecode_cache: t.Optional["BytecodeCache"] = missing, + enable_async: bool = missing, + ) -> "te.Self": + """Create a new overlay environment that shares all the data with the + current environment except for cache and the overridden attributes. + Extensions cannot be removed for an overlayed environment. An overlayed + environment automatically gets all the extensions of the environment it + is linked to plus optional extra extensions. + + Creating overlays should happen after the initial environment was set + up completely. Not all attributes are truly linked, some are just + copied over so modifications on the original environment may not shine + through. + + .. versionchanged:: 3.1.5 + ``enable_async`` is applied correctly. + + .. versionchanged:: 3.1.2 + Added the ``newline_sequence``, ``keep_trailing_newline``, + and ``enable_async`` parameters to match ``__init__``. + """ + args = dict(locals()) + del args["self"], args["cache_size"], args["extensions"], args["enable_async"] + + rv = object.__new__(self.__class__) + rv.__dict__.update(self.__dict__) + rv.overlayed = True + rv.linked_to = self + + for key, value in args.items(): + if value is not missing: + setattr(rv, key, value) + + if cache_size is not missing: + rv.cache = create_cache(cache_size) + else: + rv.cache = copy_cache(self.cache) + + rv.extensions = {} + for key, value in self.extensions.items(): + rv.extensions[key] = value.bind(rv) + if extensions is not missing: + rv.extensions.update(load_extensions(rv, extensions)) + + if enable_async is not missing: + rv.is_async = enable_async + + return _environment_config_check(rv) + + @property + def lexer(self) -> Lexer: + """The lexer for this environment.""" + return get_lexer(self) + + def iter_extensions(self) -> t.Iterator["Extension"]: + """Iterates over the extensions by priority.""" + return iter(sorted(self.extensions.values(), key=lambda x: x.priority)) + + def getitem( + self, obj: t.Any, argument: t.Union[str, t.Any] + ) -> t.Union[t.Any, Undefined]: + """Get an item or attribute of an object but prefer the item.""" + try: + return obj[argument] + except (AttributeError, TypeError, LookupError): + if isinstance(argument, str): + try: + attr = str(argument) + except Exception: + pass + else: + try: + return getattr(obj, attr) + except AttributeError: + pass + return self.undefined(obj=obj, name=argument) + + def getattr(self, obj: t.Any, attribute: str) -> t.Any: + """Get an item or attribute of an object but prefer the attribute. + Unlike :meth:`getitem` the attribute *must* be a string. + """ + try: + return getattr(obj, attribute) + except AttributeError: + pass + try: + return obj[attribute] + except (TypeError, LookupError, AttributeError): + return self.undefined(obj=obj, name=attribute) + + def _filter_test_common( + self, + name: t.Union[str, Undefined], + value: t.Any, + args: t.Optional[t.Sequence[t.Any]], + kwargs: t.Optional[t.Mapping[str, t.Any]], + context: t.Optional[Context], + eval_ctx: t.Optional[EvalContext], + is_filter: bool, + ) -> t.Any: + if is_filter: + env_map = self.filters + type_name = "filter" + else: + env_map = self.tests + type_name = "test" + + func = env_map.get(name) # type: ignore + + if func is None: + msg = f"No {type_name} named {name!r}." + + if isinstance(name, Undefined): + try: + name._fail_with_undefined_error() + except Exception as e: + msg = f"{msg} ({e}; did you forget to quote the callable name?)" + + raise TemplateRuntimeError(msg) + + args = [value, *(args if args is not None else ())] + kwargs = kwargs if kwargs is not None else {} + pass_arg = _PassArg.from_obj(func) + + if pass_arg is _PassArg.context: + if context is None: + raise TemplateRuntimeError( + f"Attempted to invoke a context {type_name} without context." + ) + + args.insert(0, context) + elif pass_arg is _PassArg.eval_context: + if eval_ctx is None: + if context is not None: + eval_ctx = context.eval_ctx + else: + eval_ctx = EvalContext(self) + + args.insert(0, eval_ctx) + elif pass_arg is _PassArg.environment: + args.insert(0, self) + + return func(*args, **kwargs) + + def call_filter( + self, + name: str, + value: t.Any, + args: t.Optional[t.Sequence[t.Any]] = None, + kwargs: t.Optional[t.Mapping[str, t.Any]] = None, + context: t.Optional[Context] = None, + eval_ctx: t.Optional[EvalContext] = None, + ) -> t.Any: + """Invoke a filter on a value the same way the compiler does. + + This might return a coroutine if the filter is running from an + environment in async mode and the filter supports async + execution. It's your responsibility to await this if needed. + + .. versionadded:: 2.7 + """ + return self._filter_test_common( + name, value, args, kwargs, context, eval_ctx, True + ) + + def call_test( + self, + name: str, + value: t.Any, + args: t.Optional[t.Sequence[t.Any]] = None, + kwargs: t.Optional[t.Mapping[str, t.Any]] = None, + context: t.Optional[Context] = None, + eval_ctx: t.Optional[EvalContext] = None, + ) -> t.Any: + """Invoke a test on a value the same way the compiler does. + + This might return a coroutine if the test is running from an + environment in async mode and the test supports async execution. + It's your responsibility to await this if needed. + + .. versionchanged:: 3.0 + Tests support ``@pass_context``, etc. decorators. Added + the ``context`` and ``eval_ctx`` parameters. + + .. versionadded:: 2.7 + """ + return self._filter_test_common( + name, value, args, kwargs, context, eval_ctx, False + ) + + @internalcode + def parse( + self, + source: str, + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + ) -> nodes.Template: + """Parse the sourcecode and return the abstract syntax tree. This + tree of nodes is used by the compiler to convert the template into + executable source- or bytecode. This is useful for debugging or to + extract information from templates. + + If you are :ref:`developing Jinja extensions ` + this gives you a good overview of the node tree generated. + """ + try: + return self._parse(source, name, filename) + except TemplateSyntaxError: + self.handle_exception(source=source) + + def _parse( + self, source: str, name: t.Optional[str], filename: t.Optional[str] + ) -> nodes.Template: + """Internal parsing function used by `parse` and `compile`.""" + return Parser(self, source, name, filename).parse() + + def lex( + self, + source: str, + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + ) -> t.Iterator[t.Tuple[int, str, str]]: + """Lex the given sourcecode and return a generator that yields + tokens as tuples in the form ``(lineno, token_type, value)``. + This can be useful for :ref:`extension development ` + and debugging templates. + + This does not perform preprocessing. If you want the preprocessing + of the extensions to be applied you have to filter source through + the :meth:`preprocess` method. + """ + source = str(source) + try: + return self.lexer.tokeniter(source, name, filename) + except TemplateSyntaxError: + self.handle_exception(source=source) + + def preprocess( + self, + source: str, + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + ) -> str: + """Preprocesses the source with all extensions. This is automatically + called for all parsing and compiling methods but *not* for :meth:`lex` + because there you usually only want the actual source tokenized. + """ + return reduce( + lambda s, e: e.preprocess(s, name, filename), + self.iter_extensions(), + str(source), + ) + + def _tokenize( + self, + source: str, + name: t.Optional[str], + filename: t.Optional[str] = None, + state: t.Optional[str] = None, + ) -> TokenStream: + """Called by the parser to do the preprocessing and filtering + for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. + """ + source = self.preprocess(source, name, filename) + stream = self.lexer.tokenize(source, name, filename, state) + + for ext in self.iter_extensions(): + stream = ext.filter_stream(stream) # type: ignore + + if not isinstance(stream, TokenStream): + stream = TokenStream(stream, name, filename) + + return stream + + def _generate( + self, + source: nodes.Template, + name: t.Optional[str], + filename: t.Optional[str], + defer_init: bool = False, + ) -> str: + """Internal hook that can be overridden to hook a different generate + method in. + + .. versionadded:: 2.5 + """ + return generate( # type: ignore + source, + self, + name, + filename, + defer_init=defer_init, + optimized=self.optimized, + ) + + def _compile(self, source: str, filename: str) -> CodeType: + """Internal hook that can be overridden to hook a different compile + method in. + + .. versionadded:: 2.5 + """ + return compile(source, filename, "exec") + + @typing.overload + def compile( + self, + source: t.Union[str, nodes.Template], + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + raw: "te.Literal[False]" = False, + defer_init: bool = False, + ) -> CodeType: ... + + @typing.overload + def compile( + self, + source: t.Union[str, nodes.Template], + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + raw: "te.Literal[True]" = ..., + defer_init: bool = False, + ) -> str: ... + + @internalcode + def compile( + self, + source: t.Union[str, nodes.Template], + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + raw: bool = False, + defer_init: bool = False, + ) -> t.Union[str, CodeType]: + """Compile a node or template source code. The `name` parameter is + the load name of the template after it was joined using + :meth:`join_path` if necessary, not the filename on the file system. + the `filename` parameter is the estimated filename of the template on + the file system. If the template came from a database or memory this + can be omitted. + + The return value of this method is a python code object. If the `raw` + parameter is `True` the return value will be a string with python + code equivalent to the bytecode returned otherwise. This method is + mainly used internally. + + `defer_init` is use internally to aid the module code generator. This + causes the generated code to be able to import without the global + environment variable to be set. + + .. versionadded:: 2.4 + `defer_init` parameter added. + """ + source_hint = None + try: + if isinstance(source, str): + source_hint = source + source = self._parse(source, name, filename) + source = self._generate(source, name, filename, defer_init=defer_init) + if raw: + return source + if filename is None: + filename = "