diff --git a/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/INSTALLER b/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/LICENSE b/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2f1b8e15e5627d92f0521605c9870bc8e5505cb4 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2017-2021 Ingy döt Net +Copyright (c) 2006-2016 Kirill Simonov + +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/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/METADATA b/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..c8905983e369893f68879f4cdfb7290d54d5f822 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/METADATA @@ -0,0 +1,46 @@ +Metadata-Version: 2.1 +Name: PyYAML +Version: 6.0.1 +Summary: YAML parser and emitter for Python +Home-page: https://pyyaml.org/ +Download-URL: https://pypi.org/project/PyYAML/ +Author: Kirill Simonov +Author-email: xi@resolvent.net +License: MIT +Project-URL: Bug Tracker, https://github.com/yaml/pyyaml/issues +Project-URL: CI, https://github.com/yaml/pyyaml/actions +Project-URL: Documentation, https://pyyaml.org/wiki/PyYAMLDocumentation +Project-URL: Mailing lists, http://lists.sourceforge.net/lists/listinfo/yaml-core +Project-URL: Source Code, https://github.com/yaml/pyyaml +Platform: Any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Cython +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Text Processing :: Markup +Requires-Python: >=3.6 +License-File: LICENSE + +YAML is a data serialization format designed for human readability +and interaction with scripting languages. PyYAML is a YAML parser +and emitter for Python. + +PyYAML features a complete YAML 1.1 parser, Unicode support, pickle +support, capable extension API, and sensible error messages. PyYAML +supports standard YAML tags and provides Python-specific tags that +allow to represent an arbitrary Python object. + +PyYAML is applicable for a broad range of tasks from complex +configuration files to object serialization and persistence. diff --git a/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/RECORD b/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..90aeed85f892d7de7ae8ffad5477859e10a5cde1 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/RECORD @@ -0,0 +1,43 @@ +PyYAML-6.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +PyYAML-6.0.1.dist-info/LICENSE,sha256=jTko-dxEkP1jVwfLiOsmvXZBAqcoKVQwfT5RZ6V36KQ,1101 +PyYAML-6.0.1.dist-info/METADATA,sha256=UNNF8-SzzwOKXVo-kV5lXUGH2_wDWMBmGxqISpp5HQk,2058 +PyYAML-6.0.1.dist-info/RECORD,, +PyYAML-6.0.1.dist-info/WHEEL,sha256=iZaXX0Td62Nww8bojl0E84uJHjT41csHPKZmbUBbJPs,152 +PyYAML-6.0.1.dist-info/top_level.txt,sha256=rpj0IVMTisAjh_1vG3Ccf9v5jpCQwAz6cD1IVU5ZdhQ,11 +_yaml/__init__.py,sha256=04Ae_5osxahpJHa3XBZUAf4wi6XX32gR8D6X6p64GEA,1402 +_yaml/__pycache__/__init__.cpython-310.pyc,, +yaml/__init__.py,sha256=bhl05qSeO-1ZxlSRjGrvl2m9nrXb1n9-GQatTN0Mrqc,12311 +yaml/__pycache__/__init__.cpython-310.pyc,, +yaml/__pycache__/composer.cpython-310.pyc,, +yaml/__pycache__/constructor.cpython-310.pyc,, +yaml/__pycache__/cyaml.cpython-310.pyc,, +yaml/__pycache__/dumper.cpython-310.pyc,, +yaml/__pycache__/emitter.cpython-310.pyc,, +yaml/__pycache__/error.cpython-310.pyc,, +yaml/__pycache__/events.cpython-310.pyc,, +yaml/__pycache__/loader.cpython-310.pyc,, +yaml/__pycache__/nodes.cpython-310.pyc,, +yaml/__pycache__/parser.cpython-310.pyc,, +yaml/__pycache__/reader.cpython-310.pyc,, +yaml/__pycache__/representer.cpython-310.pyc,, +yaml/__pycache__/resolver.cpython-310.pyc,, +yaml/__pycache__/scanner.cpython-310.pyc,, +yaml/__pycache__/serializer.cpython-310.pyc,, +yaml/__pycache__/tokens.cpython-310.pyc,, +yaml/_yaml.cpython-310-x86_64-linux-gnu.so,sha256=_9iVrASatQgQSFXlKeCe2uK2TyKwk9nd61Cs_-fqAHM,2226000 +yaml/composer.py,sha256=_Ko30Wr6eDWUeUpauUGT3Lcg9QPBnOPVlTnIMRGJ9FM,4883 +yaml/constructor.py,sha256=kNgkfaeLUkwQYY_Q6Ff1Tz2XVw_pG1xVE9Ak7z-viLA,28639 +yaml/cyaml.py,sha256=6ZrAG9fAYvdVe2FK_w0hmXoG7ZYsoYUwapG8CiC72H0,3851 +yaml/dumper.py,sha256=PLctZlYwZLp7XmeUdwRuv4nYOZ2UBnDIUy8-lKfLF-o,2837 +yaml/emitter.py,sha256=jghtaU7eFwg31bG0B7RZea_29Adi9CKmXq_QjgQpCkQ,43006 +yaml/error.py,sha256=Ah9z-toHJUbE9j-M8YpxgSRM5CgLCcwVzJgLLRF2Fxo,2533 +yaml/events.py,sha256=50_TksgQiE4up-lKo_V-nBy-tAIxkIPQxY5qDhKCeHw,2445 +yaml/loader.py,sha256=UVa-zIqmkFSCIYq_PgSGm4NSJttHY2Rf_zQ4_b1fHN0,2061 +yaml/nodes.py,sha256=gPKNj8pKCdh2d4gr3gIYINnPOaOxGhJAUiYhGRnPE84,1440 +yaml/parser.py,sha256=ilWp5vvgoHFGzvOZDItFoGjD6D42nhlZrZyjAwa0oJo,25495 +yaml/reader.py,sha256=0dmzirOiDG4Xo41RnuQS7K9rkY3xjHiVasfDMNTqCNw,6794 +yaml/representer.py,sha256=IuWP-cAW9sHKEnS0gCqSa894k1Bg4cgTxaDwIcbRQ-Y,14190 +yaml/resolver.py,sha256=9L-VYfm4mWHxUD1Vg4X7rjDRK_7VZd6b92wzq7Y2IKY,9004 +yaml/scanner.py,sha256=YEM3iLZSaQwXcQRg2l2R4MdT0zGP2F9eHkKGKnHyWQY,51279 +yaml/serializer.py,sha256=ChuFgmhU01hj4xgI8GaKv6vfM2Bujwa9i7d2FAHj7cA,4165 +yaml/tokens.py,sha256=lTQIzSVw8Mg9wv459-TjiOQe6wVziqaRlqX2_89rp54,2573 diff --git a/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/WHEEL b/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..2d1b4b87130cdd6e713250ed45eec87c87d0405f --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.40.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 + diff --git a/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/top_level.txt b/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..e6475e911f628412049bc4090d86f23ac403adde --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/PyYAML-6.0.1.dist-info/top_level.txt @@ -0,0 +1,2 @@ +_yaml +yaml diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/common.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f23bd48eb991f728f7ba2afeeeccecc562e1f626 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/common.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_cloudpickle_wrapper.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_cloudpickle_wrapper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45d82d7c900fb881b63b48a10d07e9786d074db3 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_cloudpickle_wrapper.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_disk.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_disk.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58866d4931a0081070077f23f72b77f8e1857097 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_disk.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_hashing.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_hashing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..373457383831ec5efc37c417a66025a27fa0d0b4 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_hashing.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_init.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_init.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30dae79db6188cd6007216c01057129505cb1388 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_init.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_memmapping.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_memmapping.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6edbfc99b0e49f1647e3c4875c90bb1e5b2d885a Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_memmapping.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_memory.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_memory.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0fa4719d641e2b7270e21db1b5de765d182b246 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_memory.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_missing_multiprocessing.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_missing_multiprocessing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc8920e522f6db355b9386da029e447d7c9b1462 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_missing_multiprocessing.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_testing.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_testing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7666020ed1435191cafcf0d4a304d16930af5d0 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/test_testing.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/testutils.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/testutils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67d9e2bee3b28d43633c68b758fc6f145a42bd6d Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/__pycache__/testutils.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/__init__.py b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..406a018e3ed5825f75bacd30589841c86408d7b3 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/__pycache__/create_numpy_pickle.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/__pycache__/create_numpy_pickle.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..228d4bffc08c9e3728becbd98f0eff8e5e51d2b6 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/__pycache__/create_numpy_pickle.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py33_np18.gz b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py33_np18.gz new file mode 100644 index 0000000000000000000000000000000000000000..7cd1fcc9dc7a04d7ac251d3b1bbf973609b947b8 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_compressed_pickle_py33_np18.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9e215780f978ce693e48110ead23652e1c6de1c2189172232690198f7088788 +size 792 diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.gzip b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.gzip new file mode 100644 index 0000000000000000000000000000000000000000..266b2592d66c98c72534e6b9c69ed0627f81dc04 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.gzip differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl new file mode 100644 index 0000000000000000000000000000000000000000..d6cf697b1c1c752d4d8a78d702a70042ad047ce9 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e064c2eecfdc58d552844467da7bd56eca596098322bfd266a7e1312abdd5735 +size 1068 diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.gzip b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.gzip new file mode 100644 index 0000000000000000000000000000000000000000..02f62ecf2db32e01f029eae612de0f12f26a466f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.gzip differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.lzma b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.lzma new file mode 100644 index 0000000000000000000000000000000000000000..4280387fc5e542d3b022be43ab8ab8c05ea2e953 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.lzma differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.gzip b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.gzip new file mode 100644 index 0000000000000000000000000000000000000000..02b16b8ebaa36c61da9c0c4cba6ceae88049cb43 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.gzip differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.lzma b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.lzma new file mode 100644 index 0000000000000000000000000000000000000000..add975b005d9c6fdab5c24c369edb0c7c4cf397c Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.lzma differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.bz2 b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.bz2 new file mode 100644 index 0000000000000000000000000000000000000000..06e8395437874c25cfdf6a6783eab12a6c178f90 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.bz2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6a1a9b884be654e2e3fc9a48251ecf0c6920e255c3f2ee5dd71d8252a694606 +size 1005 diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.lzma b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.lzma new file mode 100644 index 0000000000000000000000000000000000000000..6664c1772e85fa930dc330550f2cb237ac042328 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.lzma differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.bz2 b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.bz2 new file mode 100644 index 0000000000000000000000000000000000000000..895dd324d574d9b2298833317a76f3794209bbb3 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.bz2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc8db259be742ca2ff36067277f5e4a03e6d78883ddee238da65a7c7d79ef804 +size 991 diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.gzip b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.gzip new file mode 100644 index 0000000000000000000000000000000000000000..bffa94bc1e200b7a2cb7aa1b200364bd80455477 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.gzip differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.lzma b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.lzma new file mode 100644 index 0000000000000000000000000000000000000000..2090b534faf3b514544244d70112af74769ee247 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.lzma differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_01.npy b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_01.npy new file mode 100644 index 0000000000000000000000000000000000000000..15574a4193ad4ad724b2b8053c701a82efa78fd5 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_01.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0efbd7d9ce7eec3a6e0a0db41e795e0396cca3d6b037dad6c61b464843d28809 +size 120 diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl new file mode 100644 index 0000000000000000000000000000000000000000..976cba8c28be9a3dd0075efe5a6b3ce704319161 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f29d7f1d2ceca07f10df172c0e826ef08163a14b12c6ef3fa80ec53a5fcdc3c +size 670 diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_03.npy b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_03.npy new file mode 100644 index 0000000000000000000000000000000000000000..73976395be90d4b2b2d955c79a90721e16cebc82 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_03.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ede9a64a52b25d7db30950956c978ec0b3932b7d14acd5abc63216e64babde7 +size 307 diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl new file mode 100644 index 0000000000000000000000000000000000000000..19b2b0b8ee910063dcc1b24a87b1f387604c3706 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a538100e6ae94b16f2ab0f7d92d4d7e7a622be2dfcc0f6b0b73b623bc513ae2 +size 691 diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_01.npy b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_01.npy new file mode 100644 index 0000000000000000000000000000000000000000..15574a4193ad4ad724b2b8053c701a82efa78fd5 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_01.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0efbd7d9ce7eec3a6e0a0db41e795e0396cca3d6b037dad6c61b464843d28809 +size 120 diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz_01.npy.z b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz_01.npy.z new file mode 100644 index 0000000000000000000000000000000000000000..bba0f811dfe9a8f33665b7c31837eab72ce8499e Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz_01.npy.z differ diff --git a/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz_03.npy.z b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz_03.npy.z new file mode 100644 index 0000000000000000000000000000000000000000..669602e0a880d308cbea22eed2fda74cea225a9f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz_03.npy.z differ diff --git a/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/INSTALLER b/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/License.txt b/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/License.txt new file mode 100644 index 0000000000000000000000000000000000000000..b491c70e0aef319022ded661e111ddbd45b8a17f --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/License.txt @@ -0,0 +1,1568 @@ +End User License Agreement +-------------------------- + + +Preface +------- + +The Software License Agreement in Chapter 1 and the Supplement +in Chapter 2 contain license terms and conditions that govern +the use of NVIDIA software. By accepting this agreement, you +agree to comply with all the terms and conditions applicable +to the product(s) included herein. + + +NVIDIA Driver + + +Description + +This package contains the operating system driver and +fundamental system software components for NVIDIA GPUs. + + +NVIDIA CUDA Toolkit + + +Description + +The NVIDIA CUDA Toolkit provides command-line and graphical +tools for building, debugging and optimizing the performance +of applications accelerated by NVIDIA GPUs, runtime and math +libraries, and documentation including programming guides, +user manuals, and API references. + + +Default Install Location of CUDA Toolkit + +Windows platform: + +%ProgramFiles%\NVIDIA GPU Computing Toolkit\CUDA\v#.# + +Linux platform: + +/usr/local/cuda-#.# + +Mac platform: + +/Developer/NVIDIA/CUDA-#.# + + +NVIDIA CUDA Samples + + +Description + +This package includes over 100+ CUDA examples that demonstrate +various CUDA programming principles, and efficient CUDA +implementation of algorithms in specific application domains. + + +Default Install Location of CUDA Samples + +Windows platform: + +%ProgramData%\NVIDIA Corporation\CUDA Samples\v#.# + +Linux platform: + +/usr/local/cuda-#.#/samples + +and + +$HOME/NVIDIA_CUDA-#.#_Samples + +Mac platform: + +/Developer/NVIDIA/CUDA-#.#/samples + + +NVIDIA Nsight Visual Studio Edition (Windows only) + + +Description + +NVIDIA Nsight Development Platform, Visual Studio Edition is a +development environment integrated into Microsoft Visual +Studio that provides tools for debugging, profiling, analyzing +and optimizing your GPU computing and graphics applications. + + +Default Install Location of Nsight Visual Studio Edition + +Windows platform: + +%ProgramFiles(x86)%\NVIDIA Corporation\Nsight Visual Studio Edition #.# + + +1. License Agreement for NVIDIA Software Development Kits +--------------------------------------------------------- + + +Release Date: July 26, 2018 +--------------------------- + + +Important NoticeRead before downloading, installing, +copying or using the licensed software: +------------------------------------------------------- + +This license agreement, including exhibits attached +("Agreement”) is a legal agreement between you and NVIDIA +Corporation ("NVIDIA") and governs your use of a NVIDIA +software development kit (“SDK”). + +Each SDK has its own set of software and materials, but here +is a description of the types of items that may be included in +a SDK: source code, header files, APIs, data sets and assets +(examples include images, textures, models, scenes, videos, +native API input/output files), binary software, sample code, +libraries, utility programs, programming code and +documentation. + +This Agreement can be accepted only by an adult of legal age +of majority in the country in which the SDK is used. + +If you are entering into this Agreement on behalf of a company +or other legal entity, you represent that you have the legal +authority to bind the entity to this Agreement, in which case +“you” will mean the entity you represent. + +If you don’t have the required age or authority to accept +this Agreement, or if you don’t accept all the terms and +conditions of this Agreement, do not download, install or use +the SDK. + +You agree to use the SDK only for purposes that are permitted +by (a) this Agreement, and (b) any applicable law, regulation +or generally accepted practices or guidelines in the relevant +jurisdictions. + + +1.1. License + + +1.1.1. License Grant + +Subject to the terms of this Agreement, NVIDIA hereby grants +you a non-exclusive, non-transferable license, without the +right to sublicense (except as expressly provided in this +Agreement) to: + + 1. Install and use the SDK, + + 2. Modify and create derivative works of sample source code + delivered in the SDK, and + + 3. Distribute those portions of the SDK that are identified + in this Agreement as distributable, as incorporated in + object code format into a software application that meets + the distribution requirements indicated in this Agreement. + + +1.1.2. Distribution Requirements + +These are the distribution requirements for you to exercise +the distribution grant: + + 1. Your application must have material additional + functionality, beyond the included portions of the SDK. + + 2. The distributable portions of the SDK shall only be + accessed by your application. + + 3. The following notice shall be included in modifications + and derivative works of sample source code distributed: + “This software contains source code provided by NVIDIA + Corporation.” + + 4. Unless a developer tool is identified in this Agreement + as distributable, it is delivered for your internal use + only. + + 5. The terms under which you distribute your application + must be consistent with the terms of this Agreement, + including (without limitation) terms relating to the + license grant and license restrictions and protection of + NVIDIA’s intellectual property rights. Additionally, you + agree that you will protect the privacy, security and + legal rights of your application users. + + 6. You agree to notify NVIDIA in writing of any known or + suspected distribution or use of the SDK not in compliance + with the requirements of this Agreement, and to enforce + the terms of your agreements with respect to distributed + SDK. + + +1.1.3. Authorized Users + +You may allow employees and contractors of your entity or of +your subsidiary(ies) to access and use the SDK from your +secure network to perform work on your behalf. + +If you are an academic institution you may allow users +enrolled or employed by the academic institution to access and +use the SDK from your secure network. + +You are responsible for the compliance with the terms of this +Agreement by your authorized users. If you become aware that +your authorized users didn’t follow the terms of this +Agreement, you agree to take reasonable steps to resolve the +non-compliance and prevent new occurrences. + + +1.1.4. Pre-Release SDK + +The SDK versions identified as alpha, beta, preview or +otherwise as pre-release, may not be fully functional, may +contain errors or design flaws, and may have reduced or +different security, privacy, accessibility, availability, and +reliability standards relative to commercial versions of +NVIDIA software and materials. Use of a pre-release SDK may +result in unexpected results, loss of data, project delays or +other unpredictable damage or loss. + +You may use a pre-release SDK at your own risk, understanding +that pre-release SDKs are not intended for use in production +or business-critical systems. + +NVIDIA may choose not to make available a commercial version +of any pre-release SDK. NVIDIA may also choose to abandon +development and terminate the availability of a pre-release +SDK at any time without liability. + + +1.1.5. Updates + +NVIDIA may, at its option, make available patches, workarounds +or other updates to this SDK. Unless the updates are provided +with their separate governing terms, they are deemed part of +the SDK licensed to you as provided in this Agreement. You +agree that the form and content of the SDK that NVIDIA +provides may change without prior notice to you. While NVIDIA +generally maintains compatibility between versions, NVIDIA may +in some cases make changes that introduce incompatibilities in +future versions of the SDK. + + +1.1.6. Third Party Licenses + +The SDK may come bundled with, or otherwise include or be +distributed with, third party software licensed by a NVIDIA +supplier and/or open source software provided under an open +source license. Use of third party software is subject to the +third-party license terms, or in the absence of third party +terms, the terms of this Agreement. Copyright to third party +software is held by the copyright holders indicated in the +third-party software or license. + + +1.1.7. Reservation of Rights + +NVIDIA reserves all rights, title, and interest in and to the +SDK, not expressly granted to you under this Agreement. + + +1.2. Limitations + +The following license limitations apply to your use of the +SDK: + + 1. You may not reverse engineer, decompile or disassemble, + or remove copyright or other proprietary notices from any + portion of the SDK or copies of the SDK. + + 2. Except as expressly provided in this Agreement, you may + not copy, sell, rent, sublicense, transfer, distribute, + modify, or create derivative works of any portion of the + SDK. For clarity, you may not distribute or sublicense the + SDK as a stand-alone product. + + 3. Unless you have an agreement with NVIDIA for this + purpose, you may not indicate that an application created + with the SDK is sponsored or endorsed by NVIDIA. + + 4. You may not bypass, disable, or circumvent any + encryption, security, digital rights management or + authentication mechanism in the SDK. + + 5. You may not use the SDK in any manner that would cause it + to become subject to an open source software license. As + examples, licenses that require as a condition of use, + modification, and/or distribution that the SDK be: + + a. Disclosed or distributed in source code form; + + b. Licensed for the purpose of making derivative works; + or + + c. Redistributable at no charge. + + 6. Unless you have an agreement with NVIDIA for this + purpose, you may not use the SDK with any system or + application where the use or failure of the system or + application can reasonably be expected to threaten or + result in personal injury, death, or catastrophic loss. + Examples include use in avionics, navigation, military, + medical, life support or other life critical applications. + NVIDIA does not design, test or manufacture the SDK for + these critical uses and NVIDIA shall not be liable to you + or any third party, in whole or in part, for any claims or + damages arising from such uses. + + 7. You agree to defend, indemnify and hold harmless NVIDIA + and its affiliates, and their respective employees, + contractors, agents, officers and directors, from and + against any and all claims, damages, obligations, losses, + liabilities, costs or debt, fines, restitutions and + expenses (including but not limited to attorney’s fees + and costs incident to establishing the right of + indemnification) arising out of or related to your use of + the SDK outside of the scope of this Agreement, or not in + compliance with its terms. + + +1.3. Ownership + + 1. NVIDIA or its licensors hold all rights, title and + interest in and to the SDK and its modifications and + derivative works, including their respective intellectual + property rights, subject to your rights described in this + section. This SDK may include software and materials from + NVIDIA’s licensors, and these licensors are intended + third party beneficiaries that may enforce this Agreement + with respect to their intellectual property rights. + + 2. You hold all rights, title and interest in and to your + applications and your derivative works of the sample + source code delivered in the SDK, including their + respective intellectual property rights, subject to + NVIDIA’s rights described in this section. + + 3. You may, but don’t have to, provide to NVIDIA + suggestions, feature requests or other feedback regarding + the SDK, including possible enhancements or modifications + to the SDK. For any feedback that you voluntarily provide, + you hereby grant NVIDIA and its affiliates a perpetual, + non-exclusive, worldwide, irrevocable license to use, + reproduce, modify, license, sublicense (through multiple + tiers of sublicensees), and distribute (through multiple + tiers of distributors) it without the payment of any + royalties or fees to you. NVIDIA will use feedback at its + choice. NVIDIA is constantly looking for ways to improve + its products, so you may send feedback to NVIDIA through + the developer portal at https://developer.nvidia.com. + + +1.4. No Warranties + +THE SDK IS PROVIDED BY NVIDIA “AS IS” AND “WITH ALL +FAULTS.” TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND +ITS AFFILIATES EXPRESSLY DISCLAIM ALL WARRANTIES OF ANY KIND +OR NATURE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, +BUT NOT LIMITED TO, ANY WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, OR THE +ABSENCE OF ANY DEFECTS THEREIN, WHETHER LATENT OR PATENT. NO +WARRANTY IS MADE ON THE BASIS OF TRADE USAGE, COURSE OF +DEALING OR COURSE OF TRADE. + + +1.5. Limitation of Liability + +TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND ITS +AFFILIATES SHALL NOT BE LIABLE FOR ANY SPECIAL, INCIDENTAL, +PUNITIVE OR CONSEQUENTIAL DAMAGES, OR ANY LOST PROFITS, LOSS +OF USE, LOSS OF DATA OR LOSS OF GOODWILL, OR THE COSTS OF +PROCURING SUBSTITUTE PRODUCTS, ARISING OUT OF OR IN CONNECTION +WITH THIS AGREEMENT OR THE USE OR PERFORMANCE OF THE SDK, +WHETHER SUCH LIABILITY ARISES FROM ANY CLAIM BASED UPON BREACH +OF CONTRACT, BREACH OF WARRANTY, TORT (INCLUDING NEGLIGENCE), +PRODUCT LIABILITY OR ANY OTHER CAUSE OF ACTION OR THEORY OF +LIABILITY. IN NO EVENT WILL NVIDIA’S AND ITS AFFILIATES +TOTAL CUMULATIVE LIABILITY UNDER OR ARISING OUT OF THIS +AGREEMENT EXCEED US$10.00. THE NATURE OF THE LIABILITY OR THE +NUMBER OF CLAIMS OR SUITS SHALL NOT ENLARGE OR EXTEND THIS +LIMIT. + +These exclusions and limitations of liability shall apply +regardless if NVIDIA or its affiliates have been advised of +the possibility of such damages, and regardless of whether a +remedy fails its essential purpose. These exclusions and +limitations of liability form an essential basis of the +bargain between the parties, and, absent any of these +exclusions or limitations of liability, the provisions of this +Agreement, including, without limitation, the economic terms, +would be substantially different. + + +1.6. Termination + + 1. This Agreement will continue to apply until terminated by + either you or NVIDIA as described below. + + 2. If you want to terminate this Agreement, you may do so by + stopping to use the SDK. + + 3. NVIDIA may, at any time, terminate this Agreement if: + + a. (i) you fail to comply with any term of this + Agreement and the non-compliance is not fixed within + thirty (30) days following notice from NVIDIA (or + immediately if you violate NVIDIA’s intellectual + property rights); + + b. (ii) you commence or participate in any legal + proceeding against NVIDIA with respect to the SDK; or + + c. (iii) NVIDIA decides to no longer provide the SDK in + a country or, in NVIDIA’s sole discretion, the + continued use of it is no longer commercially viable. + + 4. Upon any termination of this Agreement, you agree to + promptly discontinue use of the SDK and destroy all copies + in your possession or control. Your prior distributions in + accordance with this Agreement are not affected by the + termination of this Agreement. Upon written request, you + will certify in writing that you have complied with your + commitments under this section. Upon any termination of + this Agreement all provisions survive except for the + license grant provisions. + + +1.7. General + +If you wish to assign this Agreement or your rights and +obligations, including by merger, consolidation, dissolution +or operation of law, contact NVIDIA to ask for permission. Any +attempted assignment not approved by NVIDIA in writing shall +be void and of no effect. NVIDIA may assign, delegate or +transfer this Agreement and its rights and obligations, and if +to a non-affiliate you will be notified. + +You agree to cooperate with NVIDIA and provide reasonably +requested information to verify your compliance with this +Agreement. + +This Agreement will be governed in all respects by the laws of +the United States and of the State of Delaware as those laws +are applied to contracts entered into and performed entirely +within Delaware by Delaware residents, without regard to the +conflicts of laws principles. The United Nations Convention on +Contracts for the International Sale of Goods is specifically +disclaimed. You agree to all terms of this Agreement in the +English language. + +The state or federal courts residing in Santa Clara County, +California shall have exclusive jurisdiction over any dispute +or claim arising out of this Agreement. Notwithstanding this, +you agree that NVIDIA shall still be allowed to apply for +injunctive remedies or an equivalent type of urgent legal +relief in any jurisdiction. + +If any court of competent jurisdiction determines that any +provision of this Agreement is illegal, invalid or +unenforceable, such provision will be construed as limited to +the extent necessary to be consistent with and fully +enforceable under the law and the remaining provisions will +remain in full force and effect. Unless otherwise specified, +remedies are cumulative. + +Each party acknowledges and agrees that the other is an +independent contractor in the performance of this Agreement. + +The SDK has been developed entirely at private expense and is +“commercial items” consisting of “commercial computer +software” and “commercial computer software +documentation” provided with RESTRICTED RIGHTS. Use, +duplication or disclosure by the U.S. Government or a U.S. +Government subcontractor is subject to the restrictions in +this Agreement pursuant to DFARS 227.7202-3(a) or as set forth +in subparagraphs (c)(1) and (2) of the Commercial Computer +Software - Restricted Rights clause at FAR 52.227-19, as +applicable. Contractor/manufacturer is NVIDIA, 2788 San Tomas +Expressway, Santa Clara, CA 95051. + +The SDK is subject to United States export laws and +regulations. You agree that you will not ship, transfer or +export the SDK into any country, or use the SDK in any manner, +prohibited by the United States Bureau of Industry and +Security or economic sanctions regulations administered by the +U.S. Department of Treasury’s Office of Foreign Assets +Control (OFAC), or any applicable export laws, restrictions or +regulations. These laws include restrictions on destinations, +end users and end use. By accepting this Agreement, you +confirm that you are not a resident or citizen of any country +currently embargoed by the U.S. and that you are not otherwise +prohibited from receiving the SDK. + +Any notice delivered by NVIDIA to you under this Agreement +will be delivered via mail, email or fax. You agree that any +notices that NVIDIA sends you electronically will satisfy any +legal communication requirements. Please direct your legal +notices or other correspondence to NVIDIA Corporation, 2788 +San Tomas Expressway, Santa Clara, California 95051, United +States of America, Attention: Legal Department. + +This Agreement and any exhibits incorporated into this +Agreement constitute the entire agreement of the parties with +respect to the subject matter of this Agreement and supersede +all prior negotiations or documentation exchanged between the +parties relating to this SDK license. Any additional and/or +conflicting terms on documents issued by you are null, void, +and invalid. Any amendment or waiver under this Agreement +shall be in writing and signed by representatives of both +parties. + + +2. CUDA Toolkit Supplement to Software License Agreement for +NVIDIA Software Development Kits +------------------------------------------------------------ + + +Release date: August 16, 2018 +----------------------------- + +The terms in this supplement govern your use of the NVIDIA +CUDA Toolkit SDK under the terms of your license agreement +(“Agreement”) as modified by this supplement. Capitalized +terms used but not defined below have the meaning assigned to +them in the Agreement. + +This supplement is an exhibit to the Agreement and is +incorporated as an integral part of the Agreement. In the +event of conflict between the terms in this supplement and the +terms in the Agreement, the terms in this supplement govern. + + +2.1. License Scope + +The SDK is licensed for you to develop applications only for +use in systems with NVIDIA GPUs. + + +2.2. Distribution + +The portions of the SDK that are distributable under the +Agreement are listed in Attachment A. + + +2.3. Operating Systems + +Those portions of the SDK designed exclusively for use on the +Linux or FreeBSD operating systems, or other operating systems +derived from the source code to these operating systems, may +be copied and redistributed for use in accordance with this +Agreement, provided that the object code files are not +modified in any way (except for unzipping of compressed +files). + + +2.4. Audio and Video Encoders and Decoders + +You acknowledge and agree that it is your sole responsibility +to obtain any additional third-party licenses required to +make, have made, use, have used, sell, import, and offer for +sale your products or services that include or incorporate any +third-party software and content relating to audio and/or +video encoders and decoders from, including but not limited +to, Microsoft, Thomson, Fraunhofer IIS, Sisvel S.p.A., +MPEG-LA, and Coding Technologies. NVIDIA does not grant to you +under this Agreement any necessary patent or other rights with +respect to any audio and/or video encoders and decoders. + + +2.5. Licensing + +If the distribution terms in this Agreement are not suitable +for your organization, or for any questions regarding this +Agreement, please contact NVIDIA at +nvidia-compute-license-questions@nvidia.com. + + +2.6. Attachment A + +The following portions of the SDK are distributable under the +Agreement: + +Component + +CUDA Runtime + +Windows + +cudart.dll, cudart_static.lib, cudadevrt.lib + +Mac OSX + +libcudart.dylib, libcudart_static.a, libcudadevrt.a + +Linux + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Android + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Component + +CUDA FFT Library + +Windows + +cufft.dll, cufftw.dll, cufft.lib, cufftw.lib + +Mac OSX + +libcufft.dylib, libcufft_static.a, libcufftw.dylib, +libcufftw_static.a + +Linux + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Android + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Component + +CUDA BLAS Library + +Windows + +cublas.dll, cublasLt.dll + +Mac OSX + +libcublas.dylib, libcublasLt.dylib, libcublas_static.a, +libcublasLt_static.a + +Linux + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Android + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Component + +NVIDIA "Drop-in" BLAS Library + +Windows + +nvblas.dll + +Mac OSX + +libnvblas.dylib + +Linux + +libnvblas.so + +Component + +CUDA Sparse Matrix Library + +Windows + +cusparse.dll, cusparse.lib + +Mac OSX + +libcusparse.dylib, libcusparse_static.a + +Linux + +libcusparse.so, libcusparse_static.a + +Android + +libcusparse.so, libcusparse_static.a + +Component + +CUDA Linear Solver Library + +Windows + +cusolver.dll, cusolver.lib + +Mac OSX + +libcusolver.dylib, libcusolver_static.a + +Linux + +libcusolver.so, libcusolver_static.a + +Android + +libcusolver.so, libcusolver_static.a + +Component + +CUDA Random Number Generation Library + +Windows + +curand.dll, curand.lib + +Mac OSX + +libcurand.dylib, libcurand_static.a + +Linux + +libcurand.so, libcurand_static.a + +Android + +libcurand.so, libcurand_static.a + +Component + +CUDA Accelerated Graph Library + +Component + +NVIDIA Performance Primitives Library + +Windows + +nppc.dll, nppc.lib, nppial.dll, nppial.lib, nppicc.dll, +nppicc.lib, nppicom.dll, nppicom.lib, nppidei.dll, +nppidei.lib, nppif.dll, nppif.lib, nppig.dll, nppig.lib, +nppim.dll, nppim.lib, nppist.dll, nppist.lib, nppisu.dll, +nppisu.lib, nppitc.dll, nppitc.lib, npps.dll, npps.lib + +Mac OSX + +libnppc.dylib, libnppc_static.a, libnppial.dylib, +libnppial_static.a, libnppicc.dylib, libnppicc_static.a, +libnppicom.dylib, libnppicom_static.a, libnppidei.dylib, +libnppidei_static.a, libnppif.dylib, libnppif_static.a, +libnppig.dylib, libnppig_static.a, libnppim.dylib, +libnppisu_static.a, libnppitc.dylib, libnppitc_static.a, +libnpps.dylib, libnpps_static.a + +Linux + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Android + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Component + +NVIDIA JPEG Library + +Linux + +libnvjpeg.so, libnvjpeg_static.a + +Component + +Internal common library required for statically linking to +cuBLAS, cuSPARSE, cuFFT, cuRAND, nvJPEG and NPP + +Mac OSX + +libculibos.a + +Linux + +libculibos.a + +Component + +NVIDIA Runtime Compilation Library and Header + +All + +nvrtc.h + +Windows + +nvrtc.dll, nvrtc-builtins.dll + +Mac OSX + +libnvrtc.dylib, libnvrtc-builtins.dylib + +Linux + +libnvrtc.so, libnvrtc-builtins.so + +Component + +NVIDIA Optimizing Compiler Library + +Windows + +nvvm.dll + +Mac OSX + +libnvvm.dylib + +Linux + +libnvvm.so + +Component + +NVIDIA Common Device Math Functions Library + +Windows + +libdevice.10.bc + +Mac OSX + +libdevice.10.bc + +Linux + +libdevice.10.bc + +Component + +CUDA Occupancy Calculation Header Library + +All + +cuda_occupancy.h + +Component + +CUDA Half Precision Headers + +All + +cuda_fp16.h, cuda_fp16.hpp + +Component + +CUDA Profiling Tools Interface (CUPTI) Library + +Windows + +cupti.dll + +Mac OSX + +libcupti.dylib + +Linux + +libcupti.so + +Component + +NVIDIA Tools Extension Library + +Windows + +nvToolsExt.dll, nvToolsExt.lib + +Mac OSX + +libnvToolsExt.dylib + +Linux + +libnvToolsExt.so + +Component + +NVIDIA CUDA Driver Libraries + +Linux + +libcuda.so, libnvidia-fatbinaryloader.so, +libnvidia-ptxjitcompiler.so + +The NVIDIA CUDA Driver Libraries are only distributable in +applications that meet this criteria: + + 1. The application was developed starting from a NVIDIA CUDA + container obtained from Docker Hub or the NVIDIA GPU + Cloud, and + + 2. The resulting application is packaged as a Docker + container and distributed to users on Docker Hub or the + NVIDIA GPU Cloud only. + + +2.7. Attachment B + + +Additional Licensing Obligations + +The following third party components included in the SOFTWARE +are licensed to Licensee pursuant to the following terms and +conditions: + + 1. Licensee's use of the GDB third party component is + subject to the terms and conditions of GNU GPL v3: + + This product includes copyrighted third-party software licensed + under the terms of the GNU General Public License v3 ("GPL v3"). + All third-party software packages are copyright by their respective + authors. GPL v3 terms and conditions are hereby incorporated into + the Agreement by this reference: http://www.gnu.org/licenses/gpl.txt + + Consistent with these licensing requirements, the software + listed below is provided under the terms of the specified + open source software licenses. To obtain source code for + software provided under licenses that require + redistribution of source code, including the GNU General + Public License (GPL) and GNU Lesser General Public License + (LGPL), contact oss-requests@nvidia.com. This offer is + valid for a period of three (3) years from the date of the + distribution of this product by NVIDIA CORPORATION. + + Component License + CUDA-GDB GPL v3 + + 2. Licensee represents and warrants that any and all third + party licensing and/or royalty payment obligations in + connection with Licensee's use of the H.264 video codecs + are solely the responsibility of Licensee. + + 3. Licensee's use of the Thrust library is subject to the + terms and conditions of the Apache License Version 2.0. + All third-party software packages are copyright by their + respective authors. Apache License Version 2.0 terms and + conditions are hereby incorporated into the Agreement by + this reference. + http://www.apache.org/licenses/LICENSE-2.0.html + + In addition, Licensee acknowledges the following notice: + Thrust includes source code from the Boost Iterator, + Tuple, System, and Random Number libraries. + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + 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, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 4. Licensee's use of the LLVM third party component is + subject to the following terms and conditions: + + ====================================================== + LLVM Release License + ====================================================== + University of Illinois/NCSA + Open Source License + + Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign. + All rights reserved. + + Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal with 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: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at Urbana- + Champaign, nor the names of its contributors may be used to endorse or + promote products derived from this Software without specific prior + written permission. + + 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 CONTRIBUTORS 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 WITH THE SOFTWARE. + + 5. Licensee's use (e.g. nvprof) of the PCRE third party + component is subject to the following terms and + conditions: + + ------------ + PCRE LICENCE + ------------ + PCRE is a library of functions to support regular expressions whose syntax + and semantics are as close as possible to those of the Perl 5 language. + Release 8 of PCRE is distributed under the terms of the "BSD" licence, as + specified below. The documentation for PCRE, supplied in the "doc" + directory, is distributed under the same terms as the software itself. The + basic library functions are written in C and are freestanding. Also + included in the distribution is a set of C++ wrapper functions, and a just- + in-time compiler that can be used to optimize pattern matching. These are + both optional features that can be omitted when the library is built. + + THE BASIC LIBRARY FUNCTIONS + --------------------------- + Written by: Philip Hazel + Email local part: ph10 + Email domain: cam.ac.uk + University of Cambridge Computing Service, + Cambridge, England. + Copyright (c) 1997-2012 University of Cambridge + All rights reserved. + + PCRE JUST-IN-TIME COMPILATION SUPPORT + ------------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2010-2012 Zoltan Herczeg + All rights reserved. + + STACK-LESS JUST-IN-TIME COMPILER + -------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2009-2012 Zoltan Herczeg + All rights reserved. + + THE C++ WRAPPER FUNCTIONS + ------------------------- + Contributed by: Google Inc. + Copyright (c) 2007-2012, Google Inc. + All rights reserved. + + THE "BSD" LICENCE + ----------------- + 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 University of Cambridge nor the name of Google + Inc. nor the names of their 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. + + 6. Some of the cuBLAS library routines were written by or + derived from code written by Vasily Volkov and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2007-2009, Regents of the University of California + + 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 University of California, Berkeley 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 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. + + 7. Some of the cuBLAS library routines were written by or + derived from code written by Davide Barbieri and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2008-2009 Davide Barbieri @ University of Rome Tor Vergata. + + 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. + * The name of the author may not 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. + + 8. Some of the cuBLAS library routines were derived from + code developed by the University of Tennessee and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2010 The University of Tennessee. + + 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 listed in this license in the documentation and/or + other materials provided with the distribution. + * Neither the name of the copyright holders 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. + + 9. Some of the cuBLAS library routines were written by or + derived from code written by Jonathan Hogg and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2012, The Science and Technology Facilities Council (STFC). + + 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 STFC 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 STFC 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. + + 10. Some of the cuBLAS library routines were written by or + derived from code written by Ahmad M. Abdelfattah, David + Keyes, and Hatem Ltaief, and are subject to the Apache + License, Version 2.0, as follows: + + -- (C) Copyright 2013 King Abdullah University of Science and Technology + Authors: + Ahmad Abdelfattah (ahmad.ahmad@kaust.edu.sa) + David Keyes (david.keyes@kaust.edu.sa) + Hatem Ltaief (hatem.ltaief@kaust.edu.sa) + + 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 King Abdullah University of Science and + Technology 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 + HOLDERS 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 + + 11. Some of the cuSPARSE library routines were written by or + derived from code written by Li-Wen Chang and are subject + to the NCSA Open Source License as follows: + + Copyright (c) 2012, University of Illinois. + + All rights reserved. + + Developed by: IMPACT Group, University of Illinois, http://impact.crhc.illinois.edu + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal with 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: + * 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 + disclaimers in the documentation and/or other materials provided + with the distribution. + * Neither the names of IMPACT Group, University of Illinois, nor + the names of its contributors may be used to endorse or promote + products derived from this Software without specific prior + written permission. + + 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 CONTRIBUTORS 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 WITH THE + SOFTWARE. + + 12. Some of the cuRAND library routines were written by or + derived from code written by Mutsuo Saito and Makoto + Matsumoto and are subject to the following license: + + Copyright (c) 2009, 2010 Mutsuo Saito, Makoto Matsumoto and Hiroshima + University. All rights reserved. + + Copyright (c) 2011 Mutsuo Saito, Makoto Matsumoto, Hiroshima + University and University of Tokyo. 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 Hiroshima University 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. + + 13. Some of the cuRAND library routines were derived from + code developed by D. E. Shaw Research and are subject to + the following license: + + Copyright 2010-2011, D. E. Shaw Research. + + 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 D. E. Shaw Research 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. + + 14. Some of the Math library routines were written by or + derived from code developed by Norbert Juffa and are + subject to the following license: + + Copyright (c) 2015-2017, Norbert Juffa + 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. + + 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. + + 15. Licensee's use of the lz4 third party component is + subject to the following terms and conditions: + + Copyright (C) 2011-2013, Yann Collet. + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + 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. + + 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. + + 16. The NPP library uses code from the Boost Math Toolkit, + and is subject to the following license: + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + 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, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 17. Portions of the Nsight Eclipse Edition is subject to the + following license: + + The Eclipse Foundation makes available all content in this plug-in + ("Content"). Unless otherwise indicated below, the Content is provided + to you under the terms and conditions of the Eclipse Public License + Version 1.0 ("EPL"). A copy of the EPL is available at http:// + www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" + will mean the Content. + + If you did not receive this Content directly from the Eclipse + Foundation, the Content is being redistributed by another party + ("Redistributor") and different terms and conditions may apply to your + use of any object code in the Content. Check the Redistributor's + license that was provided with the Content. If no such license exists, + contact the Redistributor. Unless otherwise indicated below, the terms + and conditions of the EPL still apply to any source code in the + Content and such source code may be obtained at http://www.eclipse.org. + + 18. Some of the cuBLAS library routines uses code from + OpenAI, which is subject to the following license: + + License URL + https://github.com/openai/openai-gemm/blob/master/LICENSE + + License Text + The MIT License + + Copyright (c) 2016 OpenAI (http://openai.com), 2016 Google Inc. + + 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. + + 19. Licensee's use of the Visual Studio Setup Configuration + Samples is subject to the following license: + + The MIT License (MIT) + Copyright (C) Microsoft Corporation. All rights reserved. + + 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. + + 20. Licensee's use of linmath.h header for CPU functions for + GL vector/matrix operations from lunarG is subject to the + Apache License Version 2.0. + + 21. The DX12-CUDA sample uses the d3dx12.h header, which is + subject to the MIT license . + +----------------- diff --git a/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/METADATA b/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..206a34d1cf86ef26fa280f9d99bcb4cb08a9fe0a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/METADATA @@ -0,0 +1,35 @@ +Metadata-Version: 2.1 +Name: nvidia-cublas-cu12 +Version: 12.1.3.1 +Summary: CUBLAS native runtime libraries +Home-page: https://developer.nvidia.com/cuda-zone +Author: Nvidia CUDA Installer Team +Author-email: cuda_installer@nvidia.com +License: NVIDIA Proprietary Software +Keywords: cuda,nvidia,runtime,machine learning,deep learning +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: Other/Proprietary License +Classifier: Natural Language :: English +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Requires-Python: >=3 +License-File: License.txt + +CUBLAS native runtime libraries diff --git a/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/RECORD b/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..1b93b48ffe06df35d1edba24e191636d722566b7 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/RECORD @@ -0,0 +1,23 @@ +nvidia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/__pycache__/__init__.cpython-310.pyc,, +nvidia/cublas/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cublas/__pycache__/__init__.cpython-310.pyc,, +nvidia/cublas/include/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cublas/include/__pycache__/__init__.cpython-310.pyc,, +nvidia/cublas/include/cublas.h,sha256=a0lLqy-k47NuwyDjuueC3W0Mpc908MTU7o5sMJqE-1w,41246 +nvidia/cublas/include/cublasLt.h,sha256=Qadag9UccOwt6czAl1q89MMJZkddB2U9z0KUXoitoLc,76626 +nvidia/cublas/include/cublasXt.h,sha256=CW9dyXYGSUW1wEXrVVyhU6OxBK1PUvMoYdVGlQT7L9A,37380 +nvidia/cublas/include/cublas_api.h,sha256=hV93oe_IH7Y7nvEwDNw37ASJUKDkdgsTAQr0szvJinA,364749 +nvidia/cublas/include/cublas_v2.h,sha256=qxMdB5jb97luEfw61LEAB-Wlr8A9DLBvO4rRypDCNKw,15460 +nvidia/cublas/include/nvblas.h,sha256=dXCLR-2oUiJFzLsDtIAK09m42ct4G0HWdYzBUuDPXpc,23341 +nvidia/cublas/lib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cublas/lib/__pycache__/__init__.cpython-310.pyc,, +nvidia/cublas/lib/libcublas.so.12,sha256=N9EUERHWuTWqhBVq1h_TV1NQytjWnQkW6dt9N-75uBY,107473968 +nvidia/cublas/lib/libcublasLt.so.12,sha256=-Xv8LPddxA2mUOuXr_Y9PhlfUAzGI8dPP-M84s4rcfQ,515090264 +nvidia/cublas/lib/libnvblas.so.12,sha256=-F6UXvUxzDZgOYkEFZTzu3GhriKr17JYveDEgTrrxWE,737048 +nvidia_cublas_cu12-12.1.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +nvidia_cublas_cu12-12.1.3.1.dist-info/License.txt,sha256=rW9YU_ugyg0VnQ9Y1JrkmDDC-Mk_epJki5zpCttMbM0,59262 +nvidia_cublas_cu12-12.1.3.1.dist-info/METADATA,sha256=88crLgU_Dos_nCVea8NfW27kik3GFl4N92xUelGbPkw,1505 +nvidia_cublas_cu12-12.1.3.1.dist-info/RECORD,, +nvidia_cublas_cu12-12.1.3.1.dist-info/WHEEL,sha256=-kQi_VMfvRQozZJT7HUPMfY-5vLo0LVTmAylNJ3Ft98,106 +nvidia_cublas_cu12-12.1.3.1.dist-info/top_level.txt,sha256=fTkAtiFuL16nUrB9ytDDtpytz2t0B4NvYTnRzwAhO14,7 diff --git a/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/WHEEL b/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..06e355fe0e3ed7077903f119ae6928a17da8eb6f --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.37.1) +Root-Is-Purelib: true +Tag: py3-none-manylinux1_x86_64 + diff --git a/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/top_level.txt b/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..862f7abf232cdfbb928609856247292e81c9decb --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/nvidia_cublas_cu12-12.1.3.1.dist-info/top_level.txt @@ -0,0 +1 @@ +nvidia diff --git a/env-llmeval/lib/python3.10/site-packages/scipy.libs/libquadmath-96973f99.so.0.0.0 b/env-llmeval/lib/python3.10/site-packages/scipy.libs/libquadmath-96973f99.so.0.0.0 new file mode 100644 index 0000000000000000000000000000000000000000..05e193bdd18b0edbec3774904c97407a4ff0afbe Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy.libs/libquadmath-96973f99.so.0.0.0 differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/__init__.py b/env-llmeval/lib/python3.10/site-packages/sympy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..91e1a325dc7ba81076b523ec4f283b8247f6c122 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/__init__.py @@ -0,0 +1,535 @@ +""" +SymPy is a Python library for symbolic mathematics. It aims to become a +full-featured computer algebra system (CAS) while keeping the code as simple +as possible in order to be comprehensible and easily extensible. SymPy is +written entirely in Python. It depends on mpmath, and other external libraries +may be optionally for things like plotting support. + +See the webpage for more information and documentation: + + https://sympy.org + +""" + + +import sys +if sys.version_info < (3, 8): + raise ImportError("Python version 3.8 or above is required for SymPy.") +del sys + + +try: + import mpmath +except ImportError: + raise ImportError("SymPy now depends on mpmath as an external library. " + "See https://docs.sympy.org/latest/install.html#mpmath for more information.") + +del mpmath + +from sympy.release import __version__ +from sympy.core.cache import lazy_function + +if 'dev' in __version__: + def enable_warnings(): + import warnings + warnings.filterwarnings('default', '.*', DeprecationWarning, module='sympy.*') + del warnings + enable_warnings() + del enable_warnings + + +def __sympy_debug(): + # helper function so we don't import os globally + import os + debug_str = os.getenv('SYMPY_DEBUG', 'False') + if debug_str in ('True', 'False'): + return eval(debug_str) + else: + raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" % + debug_str) +SYMPY_DEBUG = __sympy_debug() # type: bool + +from .core import (sympify, SympifyError, cacheit, Basic, Atom, + preorder_traversal, S, Expr, AtomicExpr, UnevaluatedExpr, Symbol, + Wild, Dummy, symbols, var, Number, Float, Rational, Integer, + NumberSymbol, RealNumber, igcd, ilcm, seterr, E, I, nan, oo, pi, zoo, + AlgebraicNumber, comp, mod_inverse, Pow, integer_nthroot, integer_log, + Mul, prod, Add, Mod, Rel, Eq, Ne, Lt, Le, Gt, Ge, Equality, + GreaterThan, LessThan, Unequality, StrictGreaterThan, StrictLessThan, + vectorize, Lambda, WildFunction, Derivative, diff, FunctionClass, + Function, Subs, expand, PoleError, count_ops, expand_mul, expand_log, + expand_func, expand_trig, expand_complex, expand_multinomial, nfloat, + expand_power_base, expand_power_exp, arity, PrecisionExhausted, N, + evalf, Tuple, Dict, gcd_terms, factor_terms, factor_nc, evaluate, + Catalan, EulerGamma, GoldenRatio, TribonacciConstant, bottom_up, use, + postorder_traversal, default_sort_key, ordered) + +from .logic import (to_cnf, to_dnf, to_nnf, And, Or, Not, Xor, Nand, Nor, + Implies, Equivalent, ITE, POSform, SOPform, simplify_logic, bool_map, + true, false, satisfiable) + +from .assumptions import (AppliedPredicate, Predicate, AssumptionsContext, + assuming, Q, ask, register_handler, remove_handler, refine) + +from .polys import (Poly, PurePoly, poly_from_expr, parallel_poly_from_expr, + degree, total_degree, degree_list, LC, LM, LT, pdiv, prem, pquo, + pexquo, div, rem, quo, exquo, half_gcdex, gcdex, invert, + subresultants, resultant, discriminant, cofactors, gcd_list, gcd, + lcm_list, lcm, terms_gcd, trunc, monic, content, primitive, compose, + decompose, sturm, gff_list, gff, sqf_norm, sqf_part, sqf_list, sqf, + factor_list, factor, intervals, refine_root, count_roots, real_roots, + nroots, ground_roots, nth_power_roots_poly, cancel, reduced, groebner, + is_zero_dimensional, GroebnerBasis, poly, symmetrize, horner, + interpolate, rational_interpolate, viete, together, + BasePolynomialError, ExactQuotientFailed, PolynomialDivisionFailed, + OperationNotSupported, HeuristicGCDFailed, HomomorphismFailed, + IsomorphismFailed, ExtraneousFactors, EvaluationFailed, + RefinementFailed, CoercionFailed, NotInvertible, NotReversible, + NotAlgebraic, DomainError, PolynomialError, UnificationFailed, + GeneratorsError, GeneratorsNeeded, ComputationFailed, + UnivariatePolynomialError, MultivariatePolynomialError, + PolificationFailed, OptionError, FlagError, minpoly, + minimal_polynomial, primitive_element, field_isomorphism, + to_number_field, isolate, round_two, prime_decomp, prime_valuation, + galois_group, itermonomials, Monomial, lex, grlex, + grevlex, ilex, igrlex, igrevlex, CRootOf, rootof, RootOf, + ComplexRootOf, RootSum, roots, Domain, FiniteField, IntegerRing, + RationalField, RealField, ComplexField, PythonFiniteField, + GMPYFiniteField, PythonIntegerRing, GMPYIntegerRing, PythonRational, + GMPYRationalField, AlgebraicField, PolynomialRing, FractionField, + ExpressionDomain, FF_python, FF_gmpy, ZZ_python, ZZ_gmpy, QQ_python, + QQ_gmpy, GF, FF, ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX, EXRAW, + construct_domain, swinnerton_dyer_poly, cyclotomic_poly, + symmetric_poly, random_poly, interpolating_poly, jacobi_poly, + chebyshevt_poly, chebyshevu_poly, hermite_poly, hermite_prob_poly, + legendre_poly, laguerre_poly, apart, apart_list, assemble_partfrac_list, + Options, ring, xring, vring, sring, field, xfield, vfield, sfield) + +from .series import (Order, O, limit, Limit, gruntz, series, approximants, + residue, EmptySequence, SeqPer, SeqFormula, sequence, SeqAdd, SeqMul, + fourier_series, fps, difference_delta, limit_seq) + +from .functions import (factorial, factorial2, rf, ff, binomial, + RisingFactorial, FallingFactorial, subfactorial, carmichael, + fibonacci, lucas, motzkin, tribonacci, harmonic, bernoulli, bell, euler, + catalan, genocchi, andre, partition, sqrt, root, Min, Max, Id, + real_root, Rem, cbrt, re, im, sign, Abs, conjugate, arg, polar_lift, + periodic_argument, unbranched_argument, principal_branch, transpose, + adjoint, polarify, unpolarify, sin, cos, tan, sec, csc, cot, sinc, + asin, acos, atan, asec, acsc, acot, atan2, exp_polar, exp, ln, log, + LambertW, sinh, cosh, tanh, coth, sech, csch, asinh, acosh, atanh, + acoth, asech, acsch, floor, ceiling, frac, Piecewise, piecewise_fold, + piecewise_exclusive, erf, erfc, erfi, erf2, erfinv, erfcinv, erf2inv, + Ei, expint, E1, li, Li, Si, Ci, Shi, Chi, fresnels, fresnelc, gamma, + lowergamma, uppergamma, polygamma, loggamma, digamma, trigamma, + multigamma, dirichlet_eta, zeta, lerchphi, polylog, stieltjes, Eijk, + LeviCivita, KroneckerDelta, SingularityFunction, DiracDelta, Heaviside, + bspline_basis, bspline_basis_set, interpolating_spline, besselj, + bessely, besseli, besselk, hankel1, hankel2, jn, yn, jn_zeros, hn1, + hn2, airyai, airybi, airyaiprime, airybiprime, marcumq, hyper, + meijerg, appellf1, legendre, assoc_legendre, hermite, hermite_prob, + chebyshevt, chebyshevu, chebyshevu_root, chebyshevt_root, laguerre, + assoc_laguerre, gegenbauer, jacobi, jacobi_normalized, Ynm, Ynm_c, + Znm, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, beta, mathieus, + mathieuc, mathieusprime, mathieucprime, riemann_xi, betainc, betainc_regularized) + +from .ntheory import (nextprime, prevprime, prime, primepi, primerange, + randprime, Sieve, sieve, primorial, cycle_length, composite, + compositepi, isprime, divisors, proper_divisors, factorint, + multiplicity, perfect_power, pollard_pm1, pollard_rho, primefactors, + totient, trailing, divisor_count, proper_divisor_count, divisor_sigma, + factorrat, reduced_totient, primenu, primeomega, + mersenne_prime_exponent, is_perfect, is_mersenne_prime, is_abundant, + is_deficient, is_amicable, abundance, npartitions, is_primitive_root, + is_quad_residue, legendre_symbol, jacobi_symbol, n_order, sqrt_mod, + quadratic_residues, primitive_root, nthroot_mod, is_nthpow_residue, + sqrt_mod_iter, mobius, discrete_log, quadratic_congruence, + binomial_coefficients, binomial_coefficients_list, + multinomial_coefficients, continued_fraction_periodic, + continued_fraction_iterator, continued_fraction_reduce, + continued_fraction_convergents, continued_fraction, egyptian_fraction) + +from .concrete import product, Product, summation, Sum + +from .discrete import (fft, ifft, ntt, intt, fwht, ifwht, mobius_transform, + inverse_mobius_transform, convolution, covering_product, + intersecting_product) + +from .simplify import (simplify, hypersimp, hypersimilar, logcombine, + separatevars, posify, besselsimp, kroneckersimp, signsimp, + nsimplify, FU, fu, sqrtdenest, cse, epath, EPath, hyperexpand, + collect, rcollect, radsimp, collect_const, fraction, numer, denom, + trigsimp, exptrigsimp, powsimp, powdenest, combsimp, gammasimp, + ratsimp, ratsimpmodprime) + +from .sets import (Set, Interval, Union, EmptySet, FiniteSet, ProductSet, + Intersection, DisjointUnion, imageset, Complement, SymmetricDifference, ImageSet, + Range, ComplexRegion, Complexes, Reals, Contains, ConditionSet, Ordinal, + OmegaPower, ord0, PowerSet, Naturals, Naturals0, UniversalSet, + Integers, Rationals) + +from .solvers import (solve, solve_linear_system, solve_linear_system_LU, + solve_undetermined_coeffs, nsolve, solve_linear, checksol, det_quick, + inv_quick, check_assumptions, failing_assumptions, diophantine, + rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper, checkodesol, + classify_ode, dsolve, homogeneous_order, solve_poly_system, + solve_triangulated, pde_separate, pde_separate_add, pde_separate_mul, + pdsolve, classify_pde, checkpdesol, ode_order, reduce_inequalities, + reduce_abs_inequality, reduce_abs_inequalities, solve_poly_inequality, + solve_rational_inequalities, solve_univariate_inequality, decompogen, + solveset, linsolve, linear_eq_to_matrix, nonlinsolve, substitution) + +from .matrices import (ShapeError, NonSquareMatrixError, GramSchmidt, + casoratian, diag, eye, hessian, jordan_cell, list2numpy, matrix2numpy, + matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2, + rot_axis3, symarray, wronskian, zeros, MutableDenseMatrix, + DeferredVector, MatrixBase, Matrix, MutableMatrix, + MutableSparseMatrix, banded, ImmutableDenseMatrix, + ImmutableSparseMatrix, ImmutableMatrix, SparseMatrix, MatrixSlice, + BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity, Inverse, + MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace, Transpose, + ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols, + Adjoint, hadamard_product, HadamardProduct, HadamardPower, + Determinant, det, diagonalize_vector, DiagMatrix, DiagonalMatrix, + DiagonalOf, trace, DotProduct, kronecker_product, KroneckerProduct, + PermutationMatrix, MatrixPermute, Permanent, per, rot_ccw_axis1, + rot_ccw_axis2, rot_ccw_axis3, rot_givens) + +from .geometry import (Point, Point2D, Point3D, Line, Ray, Segment, Line2D, + Segment2D, Ray2D, Line3D, Segment3D, Ray3D, Plane, Ellipse, Circle, + Polygon, RegularPolygon, Triangle, rad, deg, are_similar, centroid, + convex_hull, idiff, intersection, closest_points, farthest_points, + GeometryError, Curve, Parabola) + +from .utilities import (flatten, group, take, subsets, variations, + numbered_symbols, cartes, capture, dict_merge, prefixes, postfixes, + sift, topological_sort, unflatten, has_dups, has_variety, reshape, + rotations, filldedent, lambdify, + threaded, xthreaded, public, memoize_property, timed) + +from .integrals import (integrate, Integral, line_integrate, mellin_transform, + inverse_mellin_transform, MellinTransform, InverseMellinTransform, + laplace_transform, inverse_laplace_transform, LaplaceTransform, + InverseLaplaceTransform, fourier_transform, inverse_fourier_transform, + FourierTransform, InverseFourierTransform, sine_transform, + inverse_sine_transform, SineTransform, InverseSineTransform, + cosine_transform, inverse_cosine_transform, CosineTransform, + InverseCosineTransform, hankel_transform, inverse_hankel_transform, + HankelTransform, InverseHankelTransform, singularityintegrate) + +from .tensor import (IndexedBase, Idx, Indexed, get_contraction_structure, + get_indices, shape, MutableDenseNDimArray, ImmutableDenseNDimArray, + MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray, + tensorproduct, tensorcontraction, tensordiagonal, derive_by_array, + permutedims, Array, DenseNDimArray, SparseNDimArray) + +from .parsing import parse_expr + +from .calculus import (euler_equations, singularities, is_increasing, + is_strictly_increasing, is_decreasing, is_strictly_decreasing, + is_monotonic, finite_diff_weights, apply_finite_diff, + differentiate_finite, periodicity, not_empty_in, AccumBounds, + is_convex, stationary_points, minimum, maximum) + +from .algebras import Quaternion + +from .printing import (pager_print, pretty, pretty_print, pprint, + pprint_use_unicode, pprint_try_use_unicode, latex, print_latex, + multiline_latex, mathml, print_mathml, python, print_python, pycode, + ccode, print_ccode, smtlib_code, glsl_code, print_glsl, cxxcode, fcode, + print_fcode, rcode, print_rcode, jscode, print_jscode, julia_code, + mathematica_code, octave_code, rust_code, print_gtk, preview, srepr, + print_tree, StrPrinter, sstr, sstrrepr, TableForm, dotprint, + maple_code, print_maple_code) + +test = lazy_function('sympy.testing.runtests', 'test') +doctest = lazy_function('sympy.testing.runtests', 'doctest') + +# This module causes conflicts with other modules: +# from .stats import * +# Adds about .04-.05 seconds of import time +# from combinatorics import * +# This module is slow to import: +#from physics import units +from .plotting import plot, textplot, plot_backends, plot_implicit, plot_parametric +from .interactive import init_session, init_printing, interactive_traversal + +evalf._create_evalf_table() + +__all__ = [ + '__version__', + + # sympy.core + 'sympify', 'SympifyError', 'cacheit', 'Basic', 'Atom', + 'preorder_traversal', 'S', 'Expr', 'AtomicExpr', 'UnevaluatedExpr', + 'Symbol', 'Wild', 'Dummy', 'symbols', 'var', 'Number', 'Float', + 'Rational', 'Integer', 'NumberSymbol', 'RealNumber', 'igcd', 'ilcm', + 'seterr', 'E', 'I', 'nan', 'oo', 'pi', 'zoo', 'AlgebraicNumber', 'comp', + 'mod_inverse', 'Pow', 'integer_nthroot', 'integer_log', 'Mul', 'prod', + 'Add', 'Mod', 'Rel', 'Eq', 'Ne', 'Lt', 'Le', 'Gt', 'Ge', 'Equality', + 'GreaterThan', 'LessThan', 'Unequality', 'StrictGreaterThan', + 'StrictLessThan', 'vectorize', 'Lambda', 'WildFunction', 'Derivative', + 'diff', 'FunctionClass', 'Function', 'Subs', 'expand', 'PoleError', + 'count_ops', 'expand_mul', 'expand_log', 'expand_func', 'expand_trig', + 'expand_complex', 'expand_multinomial', 'nfloat', 'expand_power_base', + 'expand_power_exp', 'arity', 'PrecisionExhausted', 'N', 'evalf', 'Tuple', + 'Dict', 'gcd_terms', 'factor_terms', 'factor_nc', 'evaluate', 'Catalan', + 'EulerGamma', 'GoldenRatio', 'TribonacciConstant', 'bottom_up', 'use', + 'postorder_traversal', 'default_sort_key', 'ordered', + + # sympy.logic + 'to_cnf', 'to_dnf', 'to_nnf', 'And', 'Or', 'Not', 'Xor', 'Nand', 'Nor', + 'Implies', 'Equivalent', 'ITE', 'POSform', 'SOPform', 'simplify_logic', + 'bool_map', 'true', 'false', 'satisfiable', + + # sympy.assumptions + 'AppliedPredicate', 'Predicate', 'AssumptionsContext', 'assuming', 'Q', + 'ask', 'register_handler', 'remove_handler', 'refine', + + # sympy.polys + 'Poly', 'PurePoly', 'poly_from_expr', 'parallel_poly_from_expr', 'degree', + 'total_degree', 'degree_list', 'LC', 'LM', 'LT', 'pdiv', 'prem', 'pquo', + 'pexquo', 'div', 'rem', 'quo', 'exquo', 'half_gcdex', 'gcdex', 'invert', + 'subresultants', 'resultant', 'discriminant', 'cofactors', 'gcd_list', + 'gcd', 'lcm_list', 'lcm', 'terms_gcd', 'trunc', 'monic', 'content', + 'primitive', 'compose', 'decompose', 'sturm', 'gff_list', 'gff', + 'sqf_norm', 'sqf_part', 'sqf_list', 'sqf', 'factor_list', 'factor', + 'intervals', 'refine_root', 'count_roots', 'real_roots', 'nroots', + 'ground_roots', 'nth_power_roots_poly', 'cancel', 'reduced', 'groebner', + 'is_zero_dimensional', 'GroebnerBasis', 'poly', 'symmetrize', 'horner', + 'interpolate', 'rational_interpolate', 'viete', 'together', + 'BasePolynomialError', 'ExactQuotientFailed', 'PolynomialDivisionFailed', + 'OperationNotSupported', 'HeuristicGCDFailed', 'HomomorphismFailed', + 'IsomorphismFailed', 'ExtraneousFactors', 'EvaluationFailed', + 'RefinementFailed', 'CoercionFailed', 'NotInvertible', 'NotReversible', + 'NotAlgebraic', 'DomainError', 'PolynomialError', 'UnificationFailed', + 'GeneratorsError', 'GeneratorsNeeded', 'ComputationFailed', + 'UnivariatePolynomialError', 'MultivariatePolynomialError', + 'PolificationFailed', 'OptionError', 'FlagError', 'minpoly', + 'minimal_polynomial', 'primitive_element', 'field_isomorphism', + 'to_number_field', 'isolate', 'round_two', 'prime_decomp', + 'prime_valuation', 'galois_group', 'itermonomials', 'Monomial', 'lex', 'grlex', + 'grevlex', 'ilex', 'igrlex', 'igrevlex', 'CRootOf', 'rootof', 'RootOf', + 'ComplexRootOf', 'RootSum', 'roots', 'Domain', 'FiniteField', + 'IntegerRing', 'RationalField', 'RealField', 'ComplexField', + 'PythonFiniteField', 'GMPYFiniteField', 'PythonIntegerRing', + 'GMPYIntegerRing', 'PythonRational', 'GMPYRationalField', + 'AlgebraicField', 'PolynomialRing', 'FractionField', 'ExpressionDomain', + 'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', 'QQ_python', 'QQ_gmpy', + 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', 'EXRAW', + 'construct_domain', 'swinnerton_dyer_poly', 'cyclotomic_poly', + 'symmetric_poly', 'random_poly', 'interpolating_poly', 'jacobi_poly', + 'chebyshevt_poly', 'chebyshevu_poly', 'hermite_poly', 'hermite_prob_poly', + 'legendre_poly', 'laguerre_poly', 'apart', 'apart_list', 'assemble_partfrac_list', + 'Options', 'ring', 'xring', 'vring', 'sring', 'field', 'xfield', 'vfield', + 'sfield', + + # sympy.series + 'Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants', + 'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence', 'SeqAdd', + 'SeqMul', 'fourier_series', 'fps', 'difference_delta', 'limit_seq', + + # sympy.functions + 'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial', + 'FallingFactorial', 'subfactorial', 'carmichael', 'fibonacci', 'lucas', + 'motzkin', 'tribonacci', 'harmonic', 'bernoulli', 'bell', 'euler', 'catalan', + 'genocchi', 'andre', 'partition', 'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root', + 'Rem', 'cbrt', 're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift', + 'periodic_argument', 'unbranched_argument', 'principal_branch', + 'transpose', 'adjoint', 'polarify', 'unpolarify', 'sin', 'cos', 'tan', + 'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan', 'asec', 'acsc', + 'acot', 'atan2', 'exp_polar', 'exp', 'ln', 'log', 'LambertW', 'sinh', + 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh', + 'acoth', 'asech', 'acsch', 'floor', 'ceiling', 'frac', 'Piecewise', + 'piecewise_fold', 'piecewise_exclusive', 'erf', 'erfc', 'erfi', 'erf2', + 'erfinv', 'erfcinv', 'erf2inv', 'Ei', 'expint', 'E1', 'li', 'Li', 'Si', + 'Ci', 'Shi', 'Chi', 'fresnels', 'fresnelc', 'gamma', 'lowergamma', + 'uppergamma', 'polygamma', 'loggamma', 'digamma', 'trigamma', 'multigamma', + 'dirichlet_eta', 'zeta', 'lerchphi', 'polylog', 'stieltjes', 'Eijk', 'LeviCivita', + 'KroneckerDelta', 'SingularityFunction', 'DiracDelta', 'Heaviside', + 'bspline_basis', 'bspline_basis_set', 'interpolating_spline', 'besselj', + 'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn', 'yn', + 'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime', + 'airybiprime', 'marcumq', 'hyper', 'meijerg', 'appellf1', 'legendre', + 'assoc_legendre', 'hermite', 'hermite_prob', 'chebyshevt', 'chebyshevu', + 'chebyshevu_root', 'chebyshevt_root', 'laguerre', 'assoc_laguerre', + 'gegenbauer', 'jacobi', 'jacobi_normalized', 'Ynm', 'Ynm_c', 'Znm', + 'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi', 'beta', + 'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime', 'riemann_xi','betainc', + 'betainc_regularized', + + # sympy.ntheory + 'nextprime', 'prevprime', 'prime', 'primepi', 'primerange', 'randprime', + 'Sieve', 'sieve', 'primorial', 'cycle_length', 'composite', 'compositepi', + 'isprime', 'divisors', 'proper_divisors', 'factorint', 'multiplicity', + 'perfect_power', 'pollard_pm1', 'pollard_rho', 'primefactors', 'totient', + 'trailing', 'divisor_count', 'proper_divisor_count', 'divisor_sigma', + 'factorrat', 'reduced_totient', 'primenu', 'primeomega', + 'mersenne_prime_exponent', 'is_perfect', 'is_mersenne_prime', + 'is_abundant', 'is_deficient', 'is_amicable', 'abundance', 'npartitions', + 'is_primitive_root', 'is_quad_residue', 'legendre_symbol', + 'jacobi_symbol', 'n_order', 'sqrt_mod', 'quadratic_residues', + 'primitive_root', 'nthroot_mod', 'is_nthpow_residue', 'sqrt_mod_iter', + 'mobius', 'discrete_log', 'quadratic_congruence', 'binomial_coefficients', + 'binomial_coefficients_list', 'multinomial_coefficients', + 'continued_fraction_periodic', 'continued_fraction_iterator', + 'continued_fraction_reduce', 'continued_fraction_convergents', + 'continued_fraction', 'egyptian_fraction', + + # sympy.concrete + 'product', 'Product', 'summation', 'Sum', + + # sympy.discrete + 'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform', + 'inverse_mobius_transform', 'convolution', 'covering_product', + 'intersecting_product', + + # sympy.simplify + 'simplify', 'hypersimp', 'hypersimilar', 'logcombine', 'separatevars', + 'posify', 'besselsimp', 'kroneckersimp', 'signsimp', + 'nsimplify', 'FU', 'fu', 'sqrtdenest', 'cse', 'epath', 'EPath', + 'hyperexpand', 'collect', 'rcollect', 'radsimp', 'collect_const', + 'fraction', 'numer', 'denom', 'trigsimp', 'exptrigsimp', 'powsimp', + 'powdenest', 'combsimp', 'gammasimp', 'ratsimp', 'ratsimpmodprime', + + # sympy.sets + 'Set', 'Interval', 'Union', 'EmptySet', 'FiniteSet', 'ProductSet', + 'Intersection', 'imageset', 'DisjointUnion', 'Complement', 'SymmetricDifference', + 'ImageSet', 'Range', 'ComplexRegion', 'Reals', 'Contains', 'ConditionSet', + 'Ordinal', 'OmegaPower', 'ord0', 'PowerSet', 'Naturals', + 'Naturals0', 'UniversalSet', 'Integers', 'Rationals', 'Complexes', + + # sympy.solvers + 'solve', 'solve_linear_system', 'solve_linear_system_LU', + 'solve_undetermined_coeffs', 'nsolve', 'solve_linear', 'checksol', + 'det_quick', 'inv_quick', 'check_assumptions', 'failing_assumptions', + 'diophantine', 'rsolve', 'rsolve_poly', 'rsolve_ratio', 'rsolve_hyper', + 'checkodesol', 'classify_ode', 'dsolve', 'homogeneous_order', + 'solve_poly_system', 'solve_triangulated', 'pde_separate', + 'pde_separate_add', 'pde_separate_mul', 'pdsolve', 'classify_pde', + 'checkpdesol', 'ode_order', 'reduce_inequalities', + 'reduce_abs_inequality', 'reduce_abs_inequalities', + 'solve_poly_inequality', 'solve_rational_inequalities', + 'solve_univariate_inequality', 'decompogen', 'solveset', 'linsolve', + 'linear_eq_to_matrix', 'nonlinsolve', 'substitution', + + # sympy.matrices + 'ShapeError', 'NonSquareMatrixError', 'GramSchmidt', 'casoratian', 'diag', + 'eye', 'hessian', 'jordan_cell', 'list2numpy', 'matrix2numpy', + 'matrix_multiply_elementwise', 'ones', 'randMatrix', 'rot_axis1', + 'rot_axis2', 'rot_axis3', 'symarray', 'wronskian', 'zeros', + 'MutableDenseMatrix', 'DeferredVector', 'MatrixBase', 'Matrix', + 'MutableMatrix', 'MutableSparseMatrix', 'banded', 'ImmutableDenseMatrix', + 'ImmutableSparseMatrix', 'ImmutableMatrix', 'SparseMatrix', 'MatrixSlice', + 'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix', 'Identity', 'Inverse', + 'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr', 'MatrixSymbol', 'Trace', + 'Transpose', 'ZeroMatrix', 'OneMatrix', 'blockcut', 'block_collapse', + 'matrix_symbols', 'Adjoint', 'hadamard_product', 'HadamardProduct', + 'HadamardPower', 'Determinant', 'det', 'diagonalize_vector', 'DiagMatrix', + 'DiagonalMatrix', 'DiagonalOf', 'trace', 'DotProduct', + 'kronecker_product', 'KroneckerProduct', 'PermutationMatrix', + 'MatrixPermute', 'Permanent', 'per', 'rot_ccw_axis1', 'rot_ccw_axis2', + 'rot_ccw_axis3', 'rot_givens', + + # sympy.geometry + 'Point', 'Point2D', 'Point3D', 'Line', 'Ray', 'Segment', 'Line2D', + 'Segment2D', 'Ray2D', 'Line3D', 'Segment3D', 'Ray3D', 'Plane', 'Ellipse', + 'Circle', 'Polygon', 'RegularPolygon', 'Triangle', 'rad', 'deg', + 'are_similar', 'centroid', 'convex_hull', 'idiff', 'intersection', + 'closest_points', 'farthest_points', 'GeometryError', 'Curve', 'Parabola', + + # sympy.utilities + 'flatten', 'group', 'take', 'subsets', 'variations', 'numbered_symbols', + 'cartes', 'capture', 'dict_merge', 'prefixes', 'postfixes', 'sift', + 'topological_sort', 'unflatten', 'has_dups', 'has_variety', 'reshape', + 'rotations', 'filldedent', 'lambdify', 'threaded', 'xthreaded', + 'public', 'memoize_property', 'timed', + + # sympy.integrals + 'integrate', 'Integral', 'line_integrate', 'mellin_transform', + 'inverse_mellin_transform', 'MellinTransform', 'InverseMellinTransform', + 'laplace_transform', 'inverse_laplace_transform', 'LaplaceTransform', + 'InverseLaplaceTransform', 'fourier_transform', + 'inverse_fourier_transform', 'FourierTransform', + 'InverseFourierTransform', 'sine_transform', 'inverse_sine_transform', + 'SineTransform', 'InverseSineTransform', 'cosine_transform', + 'inverse_cosine_transform', 'CosineTransform', 'InverseCosineTransform', + 'hankel_transform', 'inverse_hankel_transform', 'HankelTransform', + 'InverseHankelTransform', 'singularityintegrate', + + # sympy.tensor + 'IndexedBase', 'Idx', 'Indexed', 'get_contraction_structure', + 'get_indices', 'shape', 'MutableDenseNDimArray', 'ImmutableDenseNDimArray', + 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray', + 'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array', + 'permutedims', 'Array', 'DenseNDimArray', 'SparseNDimArray', + + # sympy.parsing + 'parse_expr', + + # sympy.calculus + 'euler_equations', 'singularities', 'is_increasing', + 'is_strictly_increasing', 'is_decreasing', 'is_strictly_decreasing', + 'is_monotonic', 'finite_diff_weights', 'apply_finite_diff', + 'differentiate_finite', 'periodicity', 'not_empty_in', + 'AccumBounds', 'is_convex', 'stationary_points', 'minimum', 'maximum', + + # sympy.algebras + 'Quaternion', + + # sympy.printing + 'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode', + 'pprint_try_use_unicode', 'latex', 'print_latex', 'multiline_latex', + 'mathml', 'print_mathml', 'python', 'print_python', 'pycode', 'ccode', + 'print_ccode', 'smtlib_code', 'glsl_code', 'print_glsl', 'cxxcode', 'fcode', + 'print_fcode', 'rcode', 'print_rcode', 'jscode', 'print_jscode', + 'julia_code', 'mathematica_code', 'octave_code', 'rust_code', 'print_gtk', + 'preview', 'srepr', 'print_tree', 'StrPrinter', 'sstr', 'sstrrepr', + 'TableForm', 'dotprint', 'maple_code', 'print_maple_code', + + # sympy.plotting + 'plot', 'textplot', 'plot_backends', 'plot_implicit', 'plot_parametric', + + # sympy.interactive + 'init_session', 'init_printing', 'interactive_traversal', + + # sympy.testing + 'test', 'doctest', +] + + +#===========================================================================# +# # +# XXX: The names below were importable before SymPy 1.6 using # +# # +# from sympy import * # +# # +# This happened implicitly because there was no __all__ defined in this # +# __init__.py file. Not every package is imported. The list matches what # +# would have been imported before. It is possible that these packages will # +# not be imported by a star-import from sympy in future. # +# # +#===========================================================================# + + +__all__.extend(( + 'algebras', + 'assumptions', + 'calculus', + 'concrete', + 'discrete', + 'external', + 'functions', + 'geometry', + 'interactive', + 'multipledispatch', + 'ntheory', + 'parsing', + 'plotting', + 'polys', + 'printing', + 'release', + 'strategies', + 'tensor', + 'utilities', +)) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/abc.py b/env-llmeval/lib/python3.10/site-packages/sympy/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..177e8902e78dd6c23f2a5a4970098a27503f683a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/abc.py @@ -0,0 +1,111 @@ +""" +This module exports all latin and greek letters as Symbols, so you can +conveniently do + + >>> from sympy.abc import x, y + +instead of the slightly more clunky-looking + + >>> from sympy import symbols + >>> x, y = symbols('x y') + +Caveats +======= + +1. As of the time of writing this, the names ``O``, ``S``, ``I``, ``N``, +``E``, and ``Q`` are colliding with names defined in SymPy. If you import them +from both ``sympy.abc`` and ``sympy``, the second import will "win". +This is an issue only for * imports, which should only be used for short-lived +code such as interactive sessions and throwaway scripts that do not survive +until the next SymPy upgrade, where ``sympy`` may contain a different set of +names. + +2. This module does not define symbol names on demand, i.e. +``from sympy.abc import foo`` will be reported as an error because +``sympy.abc`` does not contain the name ``foo``. To get a symbol named ``foo``, +you still need to use ``Symbol('foo')`` or ``symbols('foo')``. +You can freely mix usage of ``sympy.abc`` and ``Symbol``/``symbols``, though +sticking with one and only one way to get the symbols does tend to make the code +more readable. + +The module also defines some special names to help detect which names clash +with the default SymPy namespace. + +``_clash1`` defines all the single letter variables that clash with +SymPy objects; ``_clash2`` defines the multi-letter clashing symbols; +and ``_clash`` is the union of both. These can be passed for ``locals`` +during sympification if one desires Symbols rather than the non-Symbol +objects for those names. + +Examples +======== + +>>> from sympy import S +>>> from sympy.abc import _clash1, _clash2, _clash +>>> S("Q & C", locals=_clash1) +C & Q +>>> S('pi(x)', locals=_clash2) +pi(x) +>>> S('pi(C, Q)', locals=_clash) +pi(C, Q) + +""" + +from typing import Any, Dict as tDict + +import string + +from .core import Symbol, symbols +from .core.alphabets import greeks +from sympy.parsing.sympy_parser import null + +##### Symbol definitions ##### + +# Implementation note: The easiest way to avoid typos in the symbols() +# parameter is to copy it from the left-hand side of the assignment. + +a, b, c, d, e, f, g, h, i, j = symbols('a, b, c, d, e, f, g, h, i, j') +k, l, m, n, o, p, q, r, s, t = symbols('k, l, m, n, o, p, q, r, s, t') +u, v, w, x, y, z = symbols('u, v, w, x, y, z') + +A, B, C, D, E, F, G, H, I, J = symbols('A, B, C, D, E, F, G, H, I, J') +K, L, M, N, O, P, Q, R, S, T = symbols('K, L, M, N, O, P, Q, R, S, T') +U, V, W, X, Y, Z = symbols('U, V, W, X, Y, Z') + +alpha, beta, gamma, delta = symbols('alpha, beta, gamma, delta') +epsilon, zeta, eta, theta = symbols('epsilon, zeta, eta, theta') +iota, kappa, lamda, mu = symbols('iota, kappa, lamda, mu') +nu, xi, omicron, pi = symbols('nu, xi, omicron, pi') +rho, sigma, tau, upsilon = symbols('rho, sigma, tau, upsilon') +phi, chi, psi, omega = symbols('phi, chi, psi, omega') + + +##### Clashing-symbols diagnostics ##### + +# We want to know which names in SymPy collide with those in here. +# This is mostly for diagnosing SymPy's namespace during SymPy development. + +_latin = list(string.ascii_letters) +# QOSINE should not be imported as they clash; gamma, pi and zeta clash, too +_greek = list(greeks) # make a copy, so we can mutate it +# Note: We import lamda since lambda is a reserved keyword in Python +_greek.remove("lambda") +_greek.append("lamda") + +ns: tDict[str, Any] = {} +exec('from sympy import *', ns) +_clash1: tDict[str, Any] = {} +_clash2: tDict[str, Any] = {} +while ns: + _k, _ = ns.popitem() + if _k in _greek: + _clash2[_k] = null + _greek.remove(_k) + elif _k in _latin: + _clash1[_k] = null + _latin.remove(_k) +_clash = {} +_clash.update(_clash1) +_clash.update(_clash2) + +del _latin, _greek, Symbol, _k, null diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__init__.py b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..865c0556769e35ca7e8a09a4c208a1cfbd17369c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__init__.py @@ -0,0 +1,25 @@ +"""Calculus-related methods.""" + +from .euler import euler_equations +from .singularities import (singularities, is_increasing, + is_strictly_increasing, is_decreasing, + is_strictly_decreasing, is_monotonic) +from .finite_diff import finite_diff_weights, apply_finite_diff, differentiate_finite +from .util import (periodicity, not_empty_in, is_convex, + stationary_points, minimum, maximum) +from .accumulationbounds import AccumBounds + +__all__ = [ +'euler_equations', + +'singularities', 'is_increasing', +'is_strictly_increasing', 'is_decreasing', +'is_strictly_decreasing', 'is_monotonic', + +'finite_diff_weights', 'apply_finite_diff', 'differentiate_finite', + +'periodicity', 'not_empty_in', 'is_convex', 'stationary_points', +'minimum', 'maximum', + +'AccumBounds' +] diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad939df8a7025ec5c18dfe18332414b2ccbe65cd Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/accumulationbounds.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/accumulationbounds.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a61a932e6a1b9996fc677a85fa63c8d6f22b3f1 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/accumulationbounds.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/euler.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/euler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82f1050d987592c8205c25cc0907f6caaa894659 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/euler.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/finite_diff.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/finite_diff.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0011442fca172e7c1034c4394463886cdde4a81 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/finite_diff.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/singularities.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/singularities.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e39a2c5b7e5077d24bcd822976642c91aa0d006 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/singularities.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/util.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83932c429f5df26a9a1eda09ba627df6441d0b81 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/__pycache__/util.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/calculus/accumulationbounds.py b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/accumulationbounds.py new file mode 100644 index 0000000000000000000000000000000000000000..1d879234327d49dd7ad125de096657cc5822d560 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/accumulationbounds.py @@ -0,0 +1,805 @@ +from sympy.core import Add, Mul, Pow, S +from sympy.core.basic import Basic +from sympy.core.expr import Expr +from sympy.core.numbers import _sympifyit, oo, zoo +from sympy.core.relational import is_le, is_lt, is_ge, is_gt +from sympy.core.sympify import _sympify +from sympy.functions.elementary.miscellaneous import Min, Max +from sympy.logic.boolalg import And +from sympy.multipledispatch import dispatch +from sympy.series.order import Order +from sympy.sets.sets import FiniteSet + + +class AccumulationBounds(Expr): + r"""An accumulation bounds. + + # Note AccumulationBounds has an alias: AccumBounds + + AccumulationBounds represent an interval `[a, b]`, which is always closed + at the ends. Here `a` and `b` can be any value from extended real numbers. + + The intended meaning of AccummulationBounds is to give an approximate + location of the accumulation points of a real function at a limit point. + + Let `a` and `b` be reals such that `a \le b`. + + `\left\langle a, b\right\rangle = \{x \in \mathbb{R} \mid a \le x \le b\}` + + `\left\langle -\infty, b\right\rangle = \{x \in \mathbb{R} \mid x \le b\} \cup \{-\infty, \infty\}` + + `\left\langle a, \infty \right\rangle = \{x \in \mathbb{R} \mid a \le x\} \cup \{-\infty, \infty\}` + + `\left\langle -\infty, \infty \right\rangle = \mathbb{R} \cup \{-\infty, \infty\}` + + ``oo`` and ``-oo`` are added to the second and third definition respectively, + since if either ``-oo`` or ``oo`` is an argument, then the other one should + be included (though not as an end point). This is forced, since we have, + for example, ``1/AccumBounds(0, 1) = AccumBounds(1, oo)``, and the limit at + `0` is not one-sided. As `x` tends to `0-`, then `1/x \rightarrow -\infty`, so `-\infty` + should be interpreted as belonging to ``AccumBounds(1, oo)`` though it need + not appear explicitly. + + In many cases it suffices to know that the limit set is bounded. + However, in some other cases more exact information could be useful. + For example, all accumulation values of `\cos(x) + 1` are non-negative. + (``AccumBounds(-1, 1) + 1 = AccumBounds(0, 2)``) + + A AccumulationBounds object is defined to be real AccumulationBounds, + if its end points are finite reals. + + Let `X`, `Y` be real AccumulationBounds, then their sum, difference, + product are defined to be the following sets: + + `X + Y = \{ x+y \mid x \in X \cap y \in Y\}` + + `X - Y = \{ x-y \mid x \in X \cap y \in Y\}` + + `X \times Y = \{ x \times y \mid x \in X \cap y \in Y\}` + + When an AccumBounds is raised to a negative power, if 0 is contained + between the bounds then an infinite range is returned, otherwise if an + endpoint is 0 then a semi-infinite range with consistent sign will be returned. + + AccumBounds in expressions behave a lot like Intervals but the + semantics are not necessarily the same. Division (or exponentiation + to a negative integer power) could be handled with *intervals* by + returning a union of the results obtained after splitting the + bounds between negatives and positives, but that is not done with + AccumBounds. In addition, bounds are assumed to be independent of + each other; if the same bound is used in more than one place in an + expression, the result may not be the supremum or infimum of the + expression (see below). Finally, when a boundary is ``1``, + exponentiation to the power of ``oo`` yields ``oo``, neither + ``1`` nor ``nan``. + + Examples + ======== + + >>> from sympy import AccumBounds, sin, exp, log, pi, E, S, oo + >>> from sympy.abc import x + + >>> AccumBounds(0, 1) + AccumBounds(1, 2) + AccumBounds(1, 3) + + >>> AccumBounds(0, 1) - AccumBounds(0, 2) + AccumBounds(-2, 1) + + >>> AccumBounds(-2, 3)*AccumBounds(-1, 1) + AccumBounds(-3, 3) + + >>> AccumBounds(1, 2)*AccumBounds(3, 5) + AccumBounds(3, 10) + + The exponentiation of AccumulationBounds is defined + as follows: + + If 0 does not belong to `X` or `n > 0` then + + `X^n = \{ x^n \mid x \in X\}` + + >>> AccumBounds(1, 4)**(S(1)/2) + AccumBounds(1, 2) + + otherwise, an infinite or semi-infinite result is obtained: + + >>> 1/AccumBounds(-1, 1) + AccumBounds(-oo, oo) + >>> 1/AccumBounds(0, 2) + AccumBounds(1/2, oo) + >>> 1/AccumBounds(-oo, 0) + AccumBounds(-oo, 0) + + A boundary of 1 will always generate all nonnegatives: + + >>> AccumBounds(1, 2)**oo + AccumBounds(0, oo) + >>> AccumBounds(0, 1)**oo + AccumBounds(0, oo) + + If the exponent is itself an AccumulationBounds or is not an + integer then unevaluated results will be returned unless the base + values are positive: + + >>> AccumBounds(2, 3)**AccumBounds(-1, 2) + AccumBounds(1/3, 9) + >>> AccumBounds(-2, 3)**AccumBounds(-1, 2) + AccumBounds(-2, 3)**AccumBounds(-1, 2) + + >>> AccumBounds(-2, -1)**(S(1)/2) + sqrt(AccumBounds(-2, -1)) + + Note: `\left\langle a, b\right\rangle^2` is not same as `\left\langle a, b\right\rangle \times \left\langle a, b\right\rangle` + + >>> AccumBounds(-1, 1)**2 + AccumBounds(0, 1) + + >>> AccumBounds(1, 3) < 4 + True + + >>> AccumBounds(1, 3) < -1 + False + + Some elementary functions can also take AccumulationBounds as input. + A function `f` evaluated for some real AccumulationBounds `\left\langle a, b \right\rangle` + is defined as `f(\left\langle a, b\right\rangle) = \{ f(x) \mid a \le x \le b \}` + + >>> sin(AccumBounds(pi/6, pi/3)) + AccumBounds(1/2, sqrt(3)/2) + + >>> exp(AccumBounds(0, 1)) + AccumBounds(1, E) + + >>> log(AccumBounds(1, E)) + AccumBounds(0, 1) + + Some symbol in an expression can be substituted for a AccumulationBounds + object. But it does not necessarily evaluate the AccumulationBounds for + that expression. + + The same expression can be evaluated to different values depending upon + the form it is used for substitution since each instance of an + AccumulationBounds is considered independent. For example: + + >>> (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1)) + AccumBounds(-1, 4) + + >>> ((x + 1)**2).subs(x, AccumBounds(-1, 1)) + AccumBounds(0, 4) + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Interval_arithmetic + + .. [2] https://fab.cba.mit.edu/classes/S62.12/docs/Hickey_interval.pdf + + Notes + ===== + + Do not use ``AccumulationBounds`` for floating point interval arithmetic + calculations, use ``mpmath.iv`` instead. + """ + + is_extended_real = True + is_number = False + + def __new__(cls, min, max): + + min = _sympify(min) + max = _sympify(max) + + # Only allow real intervals (use symbols with 'is_extended_real=True'). + if not min.is_extended_real or not max.is_extended_real: + raise ValueError("Only real AccumulationBounds are supported") + + if max == min: + return max + + # Make sure that the created AccumBounds object will be valid. + if max.is_number and min.is_number: + bad = max.is_comparable and min.is_comparable and max < min + else: + bad = (max - min).is_extended_negative + if bad: + raise ValueError( + "Lower limit should be smaller than upper limit") + + return Basic.__new__(cls, min, max) + + # setting the operation priority + _op_priority = 11.0 + + def _eval_is_real(self): + if self.min.is_real and self.max.is_real: + return True + + @property + def min(self): + """ + Returns the minimum possible value attained by AccumulationBounds + object. + + Examples + ======== + + >>> from sympy import AccumBounds + >>> AccumBounds(1, 3).min + 1 + + """ + return self.args[0] + + @property + def max(self): + """ + Returns the maximum possible value attained by AccumulationBounds + object. + + Examples + ======== + + >>> from sympy import AccumBounds + >>> AccumBounds(1, 3).max + 3 + + """ + return self.args[1] + + @property + def delta(self): + """ + Returns the difference of maximum possible value attained by + AccumulationBounds object and minimum possible value attained + by AccumulationBounds object. + + Examples + ======== + + >>> from sympy import AccumBounds + >>> AccumBounds(1, 3).delta + 2 + + """ + return self.max - self.min + + @property + def mid(self): + """ + Returns the mean of maximum possible value attained by + AccumulationBounds object and minimum possible value + attained by AccumulationBounds object. + + Examples + ======== + + >>> from sympy import AccumBounds + >>> AccumBounds(1, 3).mid + 2 + + """ + return (self.min + self.max) / 2 + + @_sympifyit('other', NotImplemented) + def _eval_power(self, other): + return self.__pow__(other) + + @_sympifyit('other', NotImplemented) + def __add__(self, other): + if isinstance(other, Expr): + if isinstance(other, AccumBounds): + return AccumBounds( + Add(self.min, other.min), + Add(self.max, other.max)) + if other is S.Infinity and self.min is S.NegativeInfinity or \ + other is S.NegativeInfinity and self.max is S.Infinity: + return AccumBounds(-oo, oo) + elif other.is_extended_real: + if self.min is S.NegativeInfinity and self.max is S.Infinity: + return AccumBounds(-oo, oo) + elif self.min is S.NegativeInfinity: + return AccumBounds(-oo, self.max + other) + elif self.max is S.Infinity: + return AccumBounds(self.min + other, oo) + else: + return AccumBounds(Add(self.min, other), Add(self.max, other)) + return Add(self, other, evaluate=False) + return NotImplemented + + __radd__ = __add__ + + def __neg__(self): + return AccumBounds(-self.max, -self.min) + + @_sympifyit('other', NotImplemented) + def __sub__(self, other): + if isinstance(other, Expr): + if isinstance(other, AccumBounds): + return AccumBounds( + Add(self.min, -other.max), + Add(self.max, -other.min)) + if other is S.NegativeInfinity and self.min is S.NegativeInfinity or \ + other is S.Infinity and self.max is S.Infinity: + return AccumBounds(-oo, oo) + elif other.is_extended_real: + if self.min is S.NegativeInfinity and self.max is S.Infinity: + return AccumBounds(-oo, oo) + elif self.min is S.NegativeInfinity: + return AccumBounds(-oo, self.max - other) + elif self.max is S.Infinity: + return AccumBounds(self.min - other, oo) + else: + return AccumBounds( + Add(self.min, -other), + Add(self.max, -other)) + return Add(self, -other, evaluate=False) + return NotImplemented + + @_sympifyit('other', NotImplemented) + def __rsub__(self, other): + return self.__neg__() + other + + @_sympifyit('other', NotImplemented) + def __mul__(self, other): + if self.args == (-oo, oo): + return self + if isinstance(other, Expr): + if isinstance(other, AccumBounds): + if other.args == (-oo, oo): + return other + v = set() + for a in self.args: + vi = other*a + for i in vi.args or (vi,): + v.add(i) + return AccumBounds(Min(*v), Max(*v)) + if other is S.Infinity: + if self.min.is_zero: + return AccumBounds(0, oo) + if self.max.is_zero: + return AccumBounds(-oo, 0) + if other is S.NegativeInfinity: + if self.min.is_zero: + return AccumBounds(-oo, 0) + if self.max.is_zero: + return AccumBounds(0, oo) + if other.is_extended_real: + if other.is_zero: + if self.max is S.Infinity: + return AccumBounds(0, oo) + if self.min is S.NegativeInfinity: + return AccumBounds(-oo, 0) + return S.Zero + if other.is_extended_positive: + return AccumBounds( + Mul(self.min, other), + Mul(self.max, other)) + elif other.is_extended_negative: + return AccumBounds( + Mul(self.max, other), + Mul(self.min, other)) + if isinstance(other, Order): + return other + return Mul(self, other, evaluate=False) + return NotImplemented + + __rmul__ = __mul__ + + @_sympifyit('other', NotImplemented) + def __truediv__(self, other): + if isinstance(other, Expr): + if isinstance(other, AccumBounds): + if other.min.is_positive or other.max.is_negative: + return self * AccumBounds(1/other.max, 1/other.min) + + if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative and + other.min.is_extended_nonpositive and other.max.is_extended_nonnegative): + if self.min.is_zero and other.min.is_zero: + return AccumBounds(0, oo) + if self.max.is_zero and other.min.is_zero: + return AccumBounds(-oo, 0) + return AccumBounds(-oo, oo) + + if self.max.is_extended_negative: + if other.min.is_extended_negative: + if other.max.is_zero: + return AccumBounds(self.max / other.min, oo) + if other.max.is_extended_positive: + # if we were dealing with intervals we would return + # Union(Interval(-oo, self.max/other.max), + # Interval(self.max/other.min, oo)) + return AccumBounds(-oo, oo) + + if other.min.is_zero and other.max.is_extended_positive: + return AccumBounds(-oo, self.max / other.max) + + if self.min.is_extended_positive: + if other.min.is_extended_negative: + if other.max.is_zero: + return AccumBounds(-oo, self.min / other.min) + if other.max.is_extended_positive: + # if we were dealing with intervals we would return + # Union(Interval(-oo, self.min/other.min), + # Interval(self.min/other.max, oo)) + return AccumBounds(-oo, oo) + + if other.min.is_zero and other.max.is_extended_positive: + return AccumBounds(self.min / other.max, oo) + + elif other.is_extended_real: + if other in (S.Infinity, S.NegativeInfinity): + if self == AccumBounds(-oo, oo): + return AccumBounds(-oo, oo) + if self.max is S.Infinity: + return AccumBounds(Min(0, other), Max(0, other)) + if self.min is S.NegativeInfinity: + return AccumBounds(Min(0, -other), Max(0, -other)) + if other.is_extended_positive: + return AccumBounds(self.min / other, self.max / other) + elif other.is_extended_negative: + return AccumBounds(self.max / other, self.min / other) + if (1 / other) is S.ComplexInfinity: + return Mul(self, 1 / other, evaluate=False) + else: + return Mul(self, 1 / other) + + return NotImplemented + + @_sympifyit('other', NotImplemented) + def __rtruediv__(self, other): + if isinstance(other, Expr): + if other.is_extended_real: + if other.is_zero: + return S.Zero + if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative): + if self.min.is_zero: + if other.is_extended_positive: + return AccumBounds(Mul(other, 1 / self.max), oo) + if other.is_extended_negative: + return AccumBounds(-oo, Mul(other, 1 / self.max)) + if self.max.is_zero: + if other.is_extended_positive: + return AccumBounds(-oo, Mul(other, 1 / self.min)) + if other.is_extended_negative: + return AccumBounds(Mul(other, 1 / self.min), oo) + return AccumBounds(-oo, oo) + else: + return AccumBounds(Min(other / self.min, other / self.max), + Max(other / self.min, other / self.max)) + return Mul(other, 1 / self, evaluate=False) + else: + return NotImplemented + + @_sympifyit('other', NotImplemented) + def __pow__(self, other): + if isinstance(other, Expr): + if other is S.Infinity: + if self.min.is_extended_nonnegative: + if self.max < 1: + return S.Zero + if self.min > 1: + return S.Infinity + return AccumBounds(0, oo) + elif self.max.is_extended_negative: + if self.min > -1: + return S.Zero + if self.max < -1: + return zoo + return S.NaN + else: + if self.min > -1: + if self.max < 1: + return S.Zero + return AccumBounds(0, oo) + return AccumBounds(-oo, oo) + + if other is S.NegativeInfinity: + return (1/self)**oo + + # generically true + if (self.max - self.min).is_nonnegative: + # well defined + if self.min.is_nonnegative: + # no 0 to worry about + if other.is_nonnegative: + # no infinity to worry about + return self.func(self.min**other, self.max**other) + + if other.is_zero: + return S.One # x**0 = 1 + + if other.is_Integer or other.is_integer: + if self.min.is_extended_positive: + return AccumBounds( + Min(self.min**other, self.max**other), + Max(self.min**other, self.max**other)) + elif self.max.is_extended_negative: + return AccumBounds( + Min(self.max**other, self.min**other), + Max(self.max**other, self.min**other)) + + if other % 2 == 0: + if other.is_extended_negative: + if self.min.is_zero: + return AccumBounds(self.max**other, oo) + if self.max.is_zero: + return AccumBounds(self.min**other, oo) + return (1/self)**(-other) + return AccumBounds( + S.Zero, Max(self.min**other, self.max**other)) + elif other % 2 == 1: + if other.is_extended_negative: + if self.min.is_zero: + return AccumBounds(self.max**other, oo) + if self.max.is_zero: + return AccumBounds(-oo, self.min**other) + return (1/self)**(-other) + return AccumBounds(self.min**other, self.max**other) + + # non-integer exponent + # 0**neg or neg**frac yields complex + if (other.is_number or other.is_rational) and ( + self.min.is_extended_nonnegative or ( + other.is_extended_nonnegative and + self.min.is_extended_nonnegative)): + num, den = other.as_numer_denom() + if num is S.One: + return AccumBounds(*[i**(1/den) for i in self.args]) + + elif den is not S.One: # e.g. if other is not Float + return (self**num)**(1/den) # ok for non-negative base + + if isinstance(other, AccumBounds): + if (self.min.is_extended_positive or + self.min.is_extended_nonnegative and + other.min.is_extended_nonnegative): + p = [self**i for i in other.args] + if not any(i.is_Pow for i in p): + a = [j for i in p for j in i.args or (i,)] + try: + return self.func(min(a), max(a)) + except TypeError: # can't sort + pass + + return Pow(self, other, evaluate=False) + + return NotImplemented + + @_sympifyit('other', NotImplemented) + def __rpow__(self, other): + if other.is_real and other.is_extended_nonnegative and ( + self.max - self.min).is_extended_positive: + if other is S.One: + return S.One + if other.is_extended_positive: + a, b = [other**i for i in self.args] + if min(a, b) != a: + a, b = b, a + return self.func(a, b) + if other.is_zero: + if self.min.is_zero: + return self.func(0, 1) + if self.min.is_extended_positive: + return S.Zero + + return Pow(other, self, evaluate=False) + + def __abs__(self): + if self.max.is_extended_negative: + return self.__neg__() + elif self.min.is_extended_negative: + return AccumBounds(S.Zero, Max(abs(self.min), self.max)) + else: + return self + + + def __contains__(self, other): + """ + Returns ``True`` if other is contained in self, where other + belongs to extended real numbers, ``False`` if not contained, + otherwise TypeError is raised. + + Examples + ======== + + >>> from sympy import AccumBounds, oo + >>> 1 in AccumBounds(-1, 3) + True + + -oo and oo go together as limits (in AccumulationBounds). + + >>> -oo in AccumBounds(1, oo) + True + + >>> oo in AccumBounds(-oo, 0) + True + + """ + other = _sympify(other) + + if other in (S.Infinity, S.NegativeInfinity): + if self.min is S.NegativeInfinity or self.max is S.Infinity: + return True + return False + + rv = And(self.min <= other, self.max >= other) + if rv not in (True, False): + raise TypeError("input failed to evaluate") + return rv + + def intersection(self, other): + """ + Returns the intersection of 'self' and 'other'. + Here other can be an instance of :py:class:`~.FiniteSet` or AccumulationBounds. + + Parameters + ========== + + other : AccumulationBounds + Another AccumulationBounds object with which the intersection + has to be computed. + + Returns + ======= + + AccumulationBounds + Intersection of ``self`` and ``other``. + + Examples + ======== + + >>> from sympy import AccumBounds, FiniteSet + >>> AccumBounds(1, 3).intersection(AccumBounds(2, 4)) + AccumBounds(2, 3) + + >>> AccumBounds(1, 3).intersection(AccumBounds(4, 6)) + EmptySet + + >>> AccumBounds(1, 4).intersection(FiniteSet(1, 2, 5)) + {1, 2} + + """ + if not isinstance(other, (AccumBounds, FiniteSet)): + raise TypeError( + "Input must be AccumulationBounds or FiniteSet object") + + if isinstance(other, FiniteSet): + fin_set = S.EmptySet + for i in other: + if i in self: + fin_set = fin_set + FiniteSet(i) + return fin_set + + if self.max < other.min or self.min > other.max: + return S.EmptySet + + if self.min <= other.min: + if self.max <= other.max: + return AccumBounds(other.min, self.max) + if self.max > other.max: + return other + + if other.min <= self.min: + if other.max < self.max: + return AccumBounds(self.min, other.max) + if other.max > self.max: + return self + + def union(self, other): + # TODO : Devise a better method for Union of AccumBounds + # this method is not actually correct and + # can be made better + if not isinstance(other, AccumBounds): + raise TypeError( + "Input must be AccumulationBounds or FiniteSet object") + + if self.min <= other.min and self.max >= other.min: + return AccumBounds(self.min, Max(self.max, other.max)) + + if other.min <= self.min and other.max >= self.min: + return AccumBounds(other.min, Max(self.max, other.max)) + + +@dispatch(AccumulationBounds, AccumulationBounds) # type: ignore # noqa:F811 +def _eval_is_le(lhs, rhs): # noqa:F811 + if is_le(lhs.max, rhs.min): + return True + if is_gt(lhs.min, rhs.max): + return False + + +@dispatch(AccumulationBounds, Basic) # type: ignore # noqa:F811 +def _eval_is_le(lhs, rhs): # noqa: F811 + + """ + Returns ``True `` if range of values attained by ``lhs`` AccumulationBounds + object is greater than the range of values attained by ``rhs``, + where ``rhs`` may be any value of type AccumulationBounds object or + extended real number value, ``False`` if ``rhs`` satisfies + the same property, else an unevaluated :py:class:`~.Relational`. + + Examples + ======== + + >>> from sympy import AccumBounds, oo + >>> AccumBounds(1, 3) > AccumBounds(4, oo) + False + >>> AccumBounds(1, 4) > AccumBounds(3, 4) + AccumBounds(1, 4) > AccumBounds(3, 4) + >>> AccumBounds(1, oo) > -1 + True + + """ + if not rhs.is_extended_real: + raise TypeError( + "Invalid comparison of %s %s" % + (type(rhs), rhs)) + elif rhs.is_comparable: + if is_le(lhs.max, rhs): + return True + if is_gt(lhs.min, rhs): + return False + + +@dispatch(AccumulationBounds, AccumulationBounds) +def _eval_is_ge(lhs, rhs): # noqa:F811 + if is_ge(lhs.min, rhs.max): + return True + if is_lt(lhs.max, rhs.min): + return False + + +@dispatch(AccumulationBounds, Expr) # type:ignore +def _eval_is_ge(lhs, rhs): # noqa: F811 + """ + Returns ``True`` if range of values attained by ``lhs`` AccumulationBounds + object is less that the range of values attained by ``rhs``, where + other may be any value of type AccumulationBounds object or extended + real number value, ``False`` if ``rhs`` satisfies the same + property, else an unevaluated :py:class:`~.Relational`. + + Examples + ======== + + >>> from sympy import AccumBounds, oo + >>> AccumBounds(1, 3) >= AccumBounds(4, oo) + False + >>> AccumBounds(1, 4) >= AccumBounds(3, 4) + AccumBounds(1, 4) >= AccumBounds(3, 4) + >>> AccumBounds(1, oo) >= 1 + True + """ + + if not rhs.is_extended_real: + raise TypeError( + "Invalid comparison of %s %s" % + (type(rhs), rhs)) + elif rhs.is_comparable: + if is_ge(lhs.min, rhs): + return True + if is_lt(lhs.max, rhs): + return False + + +@dispatch(Expr, AccumulationBounds) # type:ignore +def _eval_is_ge(lhs, rhs): # noqa:F811 + if not lhs.is_extended_real: + raise TypeError( + "Invalid comparison of %s %s" % + (type(lhs), lhs)) + elif lhs.is_comparable: + if is_le(rhs.max, lhs): + return True + if is_gt(rhs.min, lhs): + return False + + +@dispatch(AccumulationBounds, AccumulationBounds) # type:ignore +def _eval_is_ge(lhs, rhs): # noqa:F811 + if is_ge(lhs.min, rhs.max): + return True + if is_lt(lhs.max, rhs.min): + return False + +# setting an alias for AccumulationBounds +AccumBounds = AccumulationBounds diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/calculus/euler.py b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/euler.py new file mode 100644 index 0000000000000000000000000000000000000000..817acf76091dfba2dba40487ca7735e307c0fc15 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/euler.py @@ -0,0 +1,108 @@ +""" +This module implements a method to find +Euler-Lagrange Equations for given Lagrangian. +""" +from itertools import combinations_with_replacement +from sympy.core.function import (Derivative, Function, diff) +from sympy.core.relational import Eq +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.sympify import sympify +from sympy.utilities.iterables import iterable + + +def euler_equations(L, funcs=(), vars=()): + r""" + Find the Euler-Lagrange equations [1]_ for a given Lagrangian. + + Parameters + ========== + + L : Expr + The Lagrangian that should be a function of the functions listed + in the second argument and their derivatives. + + For example, in the case of two functions $f(x,y)$, $g(x,y)$ and + two independent variables $x$, $y$ the Lagrangian has the form: + + .. math:: L\left(f(x,y),g(x,y),\frac{\partial f(x,y)}{\partial x}, + \frac{\partial f(x,y)}{\partial y}, + \frac{\partial g(x,y)}{\partial x}, + \frac{\partial g(x,y)}{\partial y},x,y\right) + + In many cases it is not necessary to provide anything, except the + Lagrangian, it will be auto-detected (and an error raised if this + cannot be done). + + funcs : Function or an iterable of Functions + The functions that the Lagrangian depends on. The Euler equations + are differential equations for each of these functions. + + vars : Symbol or an iterable of Symbols + The Symbols that are the independent variables of the functions. + + Returns + ======= + + eqns : list of Eq + The list of differential equations, one for each function. + + Examples + ======== + + >>> from sympy import euler_equations, Symbol, Function + >>> x = Function('x') + >>> t = Symbol('t') + >>> L = (x(t).diff(t))**2/2 - x(t)**2/2 + >>> euler_equations(L, x(t), t) + [Eq(-x(t) - Derivative(x(t), (t, 2)), 0)] + >>> u = Function('u') + >>> x = Symbol('x') + >>> L = (u(t, x).diff(t))**2/2 - (u(t, x).diff(x))**2/2 + >>> euler_equations(L, u(t, x), [t, x]) + [Eq(-Derivative(u(t, x), (t, 2)) + Derivative(u(t, x), (x, 2)), 0)] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Lagrange_equation + + """ + + funcs = tuple(funcs) if iterable(funcs) else (funcs,) + + if not funcs: + funcs = tuple(L.atoms(Function)) + else: + for f in funcs: + if not isinstance(f, Function): + raise TypeError('Function expected, got: %s' % f) + + vars = tuple(vars) if iterable(vars) else (vars,) + + if not vars: + vars = funcs[0].args + else: + vars = tuple(sympify(var) for var in vars) + + if not all(isinstance(v, Symbol) for v in vars): + raise TypeError('Variables are not symbols, got %s' % vars) + + for f in funcs: + if not vars == f.args: + raise ValueError("Variables %s do not match args: %s" % (vars, f)) + + order = max([len(d.variables) for d in L.atoms(Derivative) + if d.expr in funcs] + [0]) + + eqns = [] + for f in funcs: + eq = diff(L, f) + for i in range(1, order + 1): + for p in combinations_with_replacement(vars, i): + eq = eq + S.NegativeOne**i*diff(L, diff(f, *p), *p) + new_eq = Eq(eq, 0) + if isinstance(new_eq, Eq): + eqns.append(new_eq) + + return eqns diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/calculus/finite_diff.py b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/finite_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..17eece149aadad236cefeb350e1ef4a383c84f01 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/finite_diff.py @@ -0,0 +1,476 @@ +""" +Finite difference weights +========================= + +This module implements an algorithm for efficient generation of finite +difference weights for ordinary differentials of functions for +derivatives from 0 (interpolation) up to arbitrary order. + +The core algorithm is provided in the finite difference weight generating +function (``finite_diff_weights``), and two convenience functions are provided +for: + +- estimating a derivative (or interpolate) directly from a series of points + is also provided (``apply_finite_diff``). +- differentiating by using finite difference approximations + (``differentiate_finite``). + +""" + +from sympy.core.function import Derivative +from sympy.core.singleton import S +from sympy.core.function import Subs +from sympy.core.traversal import preorder_traversal +from sympy.utilities.exceptions import sympy_deprecation_warning +from sympy.utilities.iterables import iterable + + + +def finite_diff_weights(order, x_list, x0=S.One): + """ + Calculates the finite difference weights for an arbitrarily spaced + one-dimensional grid (``x_list``) for derivatives at ``x0`` of order + 0, 1, ..., up to ``order`` using a recursive formula. Order of accuracy + is at least ``len(x_list) - order``, if ``x_list`` is defined correctly. + + Parameters + ========== + + order: int + Up to what derivative order weights should be calculated. + 0 corresponds to interpolation. + x_list: sequence + Sequence of (unique) values for the independent variable. + It is useful (but not necessary) to order ``x_list`` from + nearest to furthest from ``x0``; see examples below. + x0: Number or Symbol + Root or value of the independent variable for which the finite + difference weights should be generated. Default is ``S.One``. + + Returns + ======= + + list + A list of sublists, each corresponding to coefficients for + increasing derivative order, and each containing lists of + coefficients for increasing subsets of x_list. + + Examples + ======== + + >>> from sympy import finite_diff_weights, S + >>> res = finite_diff_weights(1, [-S(1)/2, S(1)/2, S(3)/2, S(5)/2], 0) + >>> res + [[[1, 0, 0, 0], + [1/2, 1/2, 0, 0], + [3/8, 3/4, -1/8, 0], + [5/16, 15/16, -5/16, 1/16]], + [[0, 0, 0, 0], + [-1, 1, 0, 0], + [-1, 1, 0, 0], + [-23/24, 7/8, 1/8, -1/24]]] + >>> res[0][-1] # FD weights for 0th derivative, using full x_list + [5/16, 15/16, -5/16, 1/16] + >>> res[1][-1] # FD weights for 1st derivative + [-23/24, 7/8, 1/8, -1/24] + >>> res[1][-2] # FD weights for 1st derivative, using x_list[:-1] + [-1, 1, 0, 0] + >>> res[1][-1][0] # FD weight for 1st deriv. for x_list[0] + -23/24 + >>> res[1][-1][1] # FD weight for 1st deriv. for x_list[1], etc. + 7/8 + + Each sublist contains the most accurate formula at the end. + Note, that in the above example ``res[1][1]`` is the same as ``res[1][2]``. + Since res[1][2] has an order of accuracy of + ``len(x_list[:3]) - order = 3 - 1 = 2``, the same is true for ``res[1][1]``! + + >>> res = finite_diff_weights(1, [S(0), S(1), -S(1), S(2), -S(2)], 0)[1] + >>> res + [[0, 0, 0, 0, 0], + [-1, 1, 0, 0, 0], + [0, 1/2, -1/2, 0, 0], + [-1/2, 1, -1/3, -1/6, 0], + [0, 2/3, -2/3, -1/12, 1/12]] + >>> res[0] # no approximation possible, using x_list[0] only + [0, 0, 0, 0, 0] + >>> res[1] # classic forward step approximation + [-1, 1, 0, 0, 0] + >>> res[2] # classic centered approximation + [0, 1/2, -1/2, 0, 0] + >>> res[3:] # higher order approximations + [[-1/2, 1, -1/3, -1/6, 0], [0, 2/3, -2/3, -1/12, 1/12]] + + Let us compare this to a differently defined ``x_list``. Pay attention to + ``foo[i][k]`` corresponding to the gridpoint defined by ``x_list[k]``. + + >>> foo = finite_diff_weights(1, [-S(2), -S(1), S(0), S(1), S(2)], 0)[1] + >>> foo + [[0, 0, 0, 0, 0], + [-1, 1, 0, 0, 0], + [1/2, -2, 3/2, 0, 0], + [1/6, -1, 1/2, 1/3, 0], + [1/12, -2/3, 0, 2/3, -1/12]] + >>> foo[1] # not the same and of lower accuracy as res[1]! + [-1, 1, 0, 0, 0] + >>> foo[2] # classic double backward step approximation + [1/2, -2, 3/2, 0, 0] + >>> foo[4] # the same as res[4] + [1/12, -2/3, 0, 2/3, -1/12] + + Note that, unless you plan on using approximations based on subsets of + ``x_list``, the order of gridpoints does not matter. + + The capability to generate weights at arbitrary points can be + used e.g. to minimize Runge's phenomenon by using Chebyshev nodes: + + >>> from sympy import cos, symbols, pi, simplify + >>> N, (h, x) = 4, symbols('h x') + >>> x_list = [x+h*cos(i*pi/(N)) for i in range(N,-1,-1)] # chebyshev nodes + >>> print(x_list) + [-h + x, -sqrt(2)*h/2 + x, x, sqrt(2)*h/2 + x, h + x] + >>> mycoeffs = finite_diff_weights(1, x_list, 0)[1][4] + >>> [simplify(c) for c in mycoeffs] #doctest: +NORMALIZE_WHITESPACE + [(h**3/2 + h**2*x - 3*h*x**2 - 4*x**3)/h**4, + (-sqrt(2)*h**3 - 4*h**2*x + 3*sqrt(2)*h*x**2 + 8*x**3)/h**4, + (6*h**2*x - 8*x**3)/h**4, + (sqrt(2)*h**3 - 4*h**2*x - 3*sqrt(2)*h*x**2 + 8*x**3)/h**4, + (-h**3/2 + h**2*x + 3*h*x**2 - 4*x**3)/h**4] + + Notes + ===== + + If weights for a finite difference approximation of 3rd order + derivative is wanted, weights for 0th, 1st and 2nd order are + calculated "for free", so are formulae using subsets of ``x_list``. + This is something one can take advantage of to save computational cost. + Be aware that one should define ``x_list`` from nearest to furthest from + ``x0``. If not, subsets of ``x_list`` will yield poorer approximations, + which might not grand an order of accuracy of ``len(x_list) - order``. + + See also + ======== + + sympy.calculus.finite_diff.apply_finite_diff + + References + ========== + + .. [1] Generation of Finite Difference Formulas on Arbitrarily Spaced + Grids, Bengt Fornberg; Mathematics of computation; 51; 184; + (1988); 699-706; doi:10.1090/S0025-5718-1988-0935077-0 + + """ + # The notation below closely corresponds to the one used in the paper. + order = S(order) + if not order.is_number: + raise ValueError("Cannot handle symbolic order.") + if order < 0: + raise ValueError("Negative derivative order illegal.") + if int(order) != order: + raise ValueError("Non-integer order illegal") + M = order + N = len(x_list) - 1 + delta = [[[0 for nu in range(N+1)] for n in range(N+1)] for + m in range(M+1)] + delta[0][0][0] = S.One + c1 = S.One + for n in range(1, N+1): + c2 = S.One + for nu in range(n): + c3 = x_list[n] - x_list[nu] + c2 = c2 * c3 + if n <= M: + delta[n][n-1][nu] = 0 + for m in range(min(n, M)+1): + delta[m][n][nu] = (x_list[n]-x0)*delta[m][n-1][nu] -\ + m*delta[m-1][n-1][nu] + delta[m][n][nu] /= c3 + for m in range(min(n, M)+1): + delta[m][n][n] = c1/c2*(m*delta[m-1][n-1][n-1] - + (x_list[n-1]-x0)*delta[m][n-1][n-1]) + c1 = c2 + return delta + + +def apply_finite_diff(order, x_list, y_list, x0=S.Zero): + """ + Calculates the finite difference approximation of + the derivative of requested order at ``x0`` from points + provided in ``x_list`` and ``y_list``. + + Parameters + ========== + + order: int + order of derivative to approximate. 0 corresponds to interpolation. + x_list: sequence + Sequence of (unique) values for the independent variable. + y_list: sequence + The function value at corresponding values for the independent + variable in x_list. + x0: Number or Symbol + At what value of the independent variable the derivative should be + evaluated. Defaults to 0. + + Returns + ======= + + sympy.core.add.Add or sympy.core.numbers.Number + The finite difference expression approximating the requested + derivative order at ``x0``. + + Examples + ======== + + >>> from sympy import apply_finite_diff + >>> cube = lambda arg: (1.0*arg)**3 + >>> xlist = range(-3,3+1) + >>> apply_finite_diff(2, xlist, map(cube, xlist), 2) - 12 # doctest: +SKIP + -3.55271367880050e-15 + + we see that the example above only contain rounding errors. + apply_finite_diff can also be used on more abstract objects: + + >>> from sympy import IndexedBase, Idx + >>> x, y = map(IndexedBase, 'xy') + >>> i = Idx('i') + >>> x_list, y_list = zip(*[(x[i+j], y[i+j]) for j in range(-1,2)]) + >>> apply_finite_diff(1, x_list, y_list, x[i]) + ((x[i + 1] - x[i])/(-x[i - 1] + x[i]) - 1)*y[i]/(x[i + 1] - x[i]) - + (x[i + 1] - x[i])*y[i - 1]/((x[i + 1] - x[i - 1])*(-x[i - 1] + x[i])) + + (-x[i - 1] + x[i])*y[i + 1]/((x[i + 1] - x[i - 1])*(x[i + 1] - x[i])) + + Notes + ===== + + Order = 0 corresponds to interpolation. + Only supply so many points you think makes sense + to around x0 when extracting the derivative (the function + need to be well behaved within that region). Also beware + of Runge's phenomenon. + + See also + ======== + + sympy.calculus.finite_diff.finite_diff_weights + + References + ========== + + Fortran 90 implementation with Python interface for numerics: finitediff_ + + .. _finitediff: https://github.com/bjodah/finitediff + + """ + + # In the original paper the following holds for the notation: + # M = order + # N = len(x_list) - 1 + + N = len(x_list) - 1 + if len(x_list) != len(y_list): + raise ValueError("x_list and y_list not equal in length.") + + delta = finite_diff_weights(order, x_list, x0) + + derivative = 0 + for nu in range(len(x_list)): + derivative += delta[order][N][nu]*y_list[nu] + return derivative + + +def _as_finite_diff(derivative, points=1, x0=None, wrt=None): + """ + Returns an approximation of a derivative of a function in + the form of a finite difference formula. The expression is a + weighted sum of the function at a number of discrete values of + (one of) the independent variable(s). + + Parameters + ========== + + derivative: a Derivative instance + + points: sequence or coefficient, optional + If sequence: discrete values (length >= order+1) of the + independent variable used for generating the finite + difference weights. + If it is a coefficient, it will be used as the step-size + for generating an equidistant sequence of length order+1 + centered around ``x0``. default: 1 (step-size 1) + + x0: number or Symbol, optional + the value of the independent variable (``wrt``) at which the + derivative is to be approximated. Default: same as ``wrt``. + + wrt: Symbol, optional + "with respect to" the variable for which the (partial) + derivative is to be approximated for. If not provided it + is required that the Derivative is ordinary. Default: ``None``. + + Examples + ======== + + >>> from sympy import symbols, Function, exp, sqrt, Symbol + >>> from sympy.calculus.finite_diff import _as_finite_diff + >>> x, h = symbols('x h') + >>> f = Function('f') + >>> _as_finite_diff(f(x).diff(x)) + -f(x - 1/2) + f(x + 1/2) + + The default step size and number of points are 1 and ``order + 1`` + respectively. We can change the step size by passing a symbol + as a parameter: + + >>> _as_finite_diff(f(x).diff(x), h) + -f(-h/2 + x)/h + f(h/2 + x)/h + + We can also specify the discretized values to be used in a sequence: + + >>> _as_finite_diff(f(x).diff(x), [x, x+h, x+2*h]) + -3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h) + + The algorithm is not restricted to use equidistant spacing, nor + do we need to make the approximation around ``x0``, but we can get + an expression estimating the derivative at an offset: + + >>> e, sq2 = exp(1), sqrt(2) + >>> xl = [x-h, x+h, x+e*h] + >>> _as_finite_diff(f(x).diff(x, 1), xl, x+h*sq2) + 2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/((-h + E*h)*(h + E*h)) + + (-(-sqrt(2)*h + h)/(2*h) - (-sqrt(2)*h + E*h)/(2*h))*f(-h + x)/(h + E*h) + + (-(h + sqrt(2)*h)/(2*h) + (-sqrt(2)*h + E*h)/(2*h))*f(h + x)/(-h + E*h) + + Partial derivatives are also supported: + + >>> y = Symbol('y') + >>> d2fdxdy=f(x,y).diff(x,y) + >>> _as_finite_diff(d2fdxdy, wrt=x) + -Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y) + + See also + ======== + + sympy.calculus.finite_diff.apply_finite_diff + sympy.calculus.finite_diff.finite_diff_weights + + """ + if derivative.is_Derivative: + pass + elif derivative.is_Atom: + return derivative + else: + return derivative.fromiter( + [_as_finite_diff(ar, points, x0, wrt) for ar + in derivative.args], **derivative.assumptions0) + + if wrt is None: + old = None + for v in derivative.variables: + if old is v: + continue + derivative = _as_finite_diff(derivative, points, x0, v) + old = v + return derivative + + order = derivative.variables.count(wrt) + + if x0 is None: + x0 = wrt + + if not iterable(points): + if getattr(points, 'is_Function', False) and wrt in points.args: + points = points.subs(wrt, x0) + # points is simply the step-size, let's make it a + # equidistant sequence centered around x0 + if order % 2 == 0: + # even order => odd number of points, grid point included + points = [x0 + points*i for i + in range(-order//2, order//2 + 1)] + else: + # odd order => even number of points, half-way wrt grid point + points = [x0 + points*S(i)/2 for i + in range(-order, order + 1, 2)] + others = [wrt, 0] + for v in set(derivative.variables): + if v == wrt: + continue + others += [v, derivative.variables.count(v)] + if len(points) < order+1: + raise ValueError("Too few points for order %d" % order) + return apply_finite_diff(order, points, [ + Derivative(derivative.expr.subs({wrt: x}), *others) for + x in points], x0) + + +def differentiate_finite(expr, *symbols, + points=1, x0=None, wrt=None, evaluate=False): + r""" Differentiate expr and replace Derivatives with finite differences. + + Parameters + ========== + + expr : expression + \*symbols : differentiate with respect to symbols + points: sequence, coefficient or undefined function, optional + see ``Derivative.as_finite_difference`` + x0: number or Symbol, optional + see ``Derivative.as_finite_difference`` + wrt: Symbol, optional + see ``Derivative.as_finite_difference`` + + Examples + ======== + + >>> from sympy import sin, Function, differentiate_finite + >>> from sympy.abc import x, y, h + >>> f, g = Function('f'), Function('g') + >>> differentiate_finite(f(x)*g(x), x, points=[x-h, x+h]) + -f(-h + x)*g(-h + x)/(2*h) + f(h + x)*g(h + x)/(2*h) + + ``differentiate_finite`` works on any expression, including the expressions + with embedded derivatives: + + >>> differentiate_finite(f(x) + sin(x), x, 2) + -2*f(x) + f(x - 1) + f(x + 1) - 2*sin(x) + sin(x - 1) + sin(x + 1) + >>> differentiate_finite(f(x, y), x, y) + f(x - 1/2, y - 1/2) - f(x - 1/2, y + 1/2) - f(x + 1/2, y - 1/2) + f(x + 1/2, y + 1/2) + >>> differentiate_finite(f(x)*g(x).diff(x), x) + (-g(x) + g(x + 1))*f(x + 1/2) - (g(x) - g(x - 1))*f(x - 1/2) + + To make finite difference with non-constant discretization step use + undefined functions: + + >>> dx = Function('dx') + >>> differentiate_finite(f(x)*g(x).diff(x), points=dx(x)) + -(-g(x - dx(x)/2 - dx(x - dx(x)/2)/2)/dx(x - dx(x)/2) + + g(x - dx(x)/2 + dx(x - dx(x)/2)/2)/dx(x - dx(x)/2))*f(x - dx(x)/2)/dx(x) + + (-g(x + dx(x)/2 - dx(x + dx(x)/2)/2)/dx(x + dx(x)/2) + + g(x + dx(x)/2 + dx(x + dx(x)/2)/2)/dx(x + dx(x)/2))*f(x + dx(x)/2)/dx(x) + + """ + if any(term.is_Derivative for term in list(preorder_traversal(expr))): + evaluate = False + + Dexpr = expr.diff(*symbols, evaluate=evaluate) + if evaluate: + sympy_deprecation_warning(""" + The evaluate flag to differentiate_finite() is deprecated. + + evaluate=True expands the intermediate derivatives before computing + differences, but this usually not what you want, as it does not + satisfy the product rule. + """, + deprecated_since_version="1.5", + active_deprecations_target="deprecated-differentiate_finite-evaluate", + ) + return Dexpr.replace( + lambda arg: arg.is_Derivative, + lambda arg: arg.as_finite_difference(points=points, x0=x0, wrt=wrt)) + else: + DFexpr = Dexpr.as_finite_difference(points=points, x0=x0, wrt=wrt) + return DFexpr.replace( + lambda arg: isinstance(arg, Subs), + lambda arg: arg.expr.as_finite_difference( + points=points, x0=arg.point[0], wrt=arg.variables[0])) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/calculus/singularities.py b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/singularities.py new file mode 100644 index 0000000000000000000000000000000000000000..3a2ea1a17c3b69d9e49a481cec794c0d86df834c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/singularities.py @@ -0,0 +1,398 @@ +""" +Singularities +============= + +This module implements algorithms for finding singularities for a function +and identifying types of functions. + +The differential calculus methods in this module include methods to identify +the following function types in the given ``Interval``: +- Increasing +- Strictly Increasing +- Decreasing +- Strictly Decreasing +- Monotonic + +""" + +from sympy.core.power import Pow +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.core.sympify import sympify +from sympy.functions.elementary.exponential import log +from sympy.functions.elementary.trigonometric import sec, csc, cot, tan, cos +from sympy.utilities.misc import filldedent + + +def singularities(expression, symbol, domain=None): + """ + Find singularities of a given function. + + Parameters + ========== + + expression : Expr + The target function in which singularities need to be found. + symbol : Symbol + The symbol over the values of which the singularity in + expression in being searched for. + + Returns + ======= + + Set + A set of values for ``symbol`` for which ``expression`` has a + singularity. An ``EmptySet`` is returned if ``expression`` has no + singularities for any given value of ``Symbol``. + + Raises + ====== + + NotImplementedError + Methods for determining the singularities of this function have + not been developed. + + Notes + ===== + + This function does not find non-isolated singularities + nor does it find branch points of the expression. + + Currently supported functions are: + - univariate continuous (real or complex) functions + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Mathematical_singularity + + Examples + ======== + + >>> from sympy import singularities, Symbol, log + >>> x = Symbol('x', real=True) + >>> y = Symbol('y', real=False) + >>> singularities(x**2 + x + 1, x) + EmptySet + >>> singularities(1/(x + 1), x) + {-1} + >>> singularities(1/(y**2 + 1), y) + {-I, I} + >>> singularities(1/(y**3 + 1), y) + {-1, 1/2 - sqrt(3)*I/2, 1/2 + sqrt(3)*I/2} + >>> singularities(log(x), x) + {0} + + """ + from sympy.solvers.solveset import solveset + + if domain is None: + domain = S.Reals if symbol.is_real else S.Complexes + try: + sings = S.EmptySet + for i in expression.rewrite([sec, csc, cot, tan], cos).atoms(Pow): + if i.exp.is_infinite: + raise NotImplementedError + if i.exp.is_negative: + sings += solveset(i.base, symbol, domain) + for i in expression.atoms(log): + sings += solveset(i.args[0], symbol, domain) + return sings + except NotImplementedError: + raise NotImplementedError(filldedent(''' + Methods for determining the singularities + of this function have not been developed.''')) + + +########################################################################### +# DIFFERENTIAL CALCULUS METHODS # +########################################################################### + + +def monotonicity_helper(expression, predicate, interval=S.Reals, symbol=None): + """ + Helper function for functions checking function monotonicity. + + Parameters + ========== + + expression : Expr + The target function which is being checked + predicate : function + The property being tested for. The function takes in an integer + and returns a boolean. The integer input is the derivative and + the boolean result should be true if the property is being held, + and false otherwise. + interval : Set, optional + The range of values in which we are testing, defaults to all reals. + symbol : Symbol, optional + The symbol present in expression which gets varied over the given range. + + It returns a boolean indicating whether the interval in which + the function's derivative satisfies given predicate is a superset + of the given interval. + + Returns + ======= + + Boolean + True if ``predicate`` is true for all the derivatives when ``symbol`` + is varied in ``range``, False otherwise. + + """ + from sympy.solvers.solveset import solveset + + expression = sympify(expression) + free = expression.free_symbols + + if symbol is None: + if len(free) > 1: + raise NotImplementedError( + 'The function has not yet been implemented' + ' for all multivariate expressions.' + ) + + variable = symbol or (free.pop() if free else Symbol('x')) + derivative = expression.diff(variable) + predicate_interval = solveset(predicate(derivative), variable, S.Reals) + return interval.is_subset(predicate_interval) + + +def is_increasing(expression, interval=S.Reals, symbol=None): + """ + Return whether the function is increasing in the given interval. + + Parameters + ========== + + expression : Expr + The target function which is being checked. + interval : Set, optional + The range of values in which we are testing (defaults to set of + all real numbers). + symbol : Symbol, optional + The symbol present in expression which gets varied over the given range. + + Returns + ======= + + Boolean + True if ``expression`` is increasing (either strictly increasing or + constant) in the given ``interval``, False otherwise. + + Examples + ======== + + >>> from sympy import is_increasing + >>> from sympy.abc import x, y + >>> from sympy import S, Interval, oo + >>> is_increasing(x**3 - 3*x**2 + 4*x, S.Reals) + True + >>> is_increasing(-x**2, Interval(-oo, 0)) + True + >>> is_increasing(-x**2, Interval(0, oo)) + False + >>> is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) + False + >>> is_increasing(x**2 + y, Interval(1, 2), x) + True + + """ + return monotonicity_helper(expression, lambda x: x >= 0, interval, symbol) + + +def is_strictly_increasing(expression, interval=S.Reals, symbol=None): + """ + Return whether the function is strictly increasing in the given interval. + + Parameters + ========== + + expression : Expr + The target function which is being checked. + interval : Set, optional + The range of values in which we are testing (defaults to set of + all real numbers). + symbol : Symbol, optional + The symbol present in expression which gets varied over the given range. + + Returns + ======= + + Boolean + True if ``expression`` is strictly increasing in the given ``interval``, + False otherwise. + + Examples + ======== + + >>> from sympy import is_strictly_increasing + >>> from sympy.abc import x, y + >>> from sympy import Interval, oo + >>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2)) + True + >>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo)) + True + >>> is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) + False + >>> is_strictly_increasing(-x**2, Interval(0, oo)) + False + >>> is_strictly_increasing(-x**2 + y, Interval(-oo, 0), x) + False + + """ + return monotonicity_helper(expression, lambda x: x > 0, interval, symbol) + + +def is_decreasing(expression, interval=S.Reals, symbol=None): + """ + Return whether the function is decreasing in the given interval. + + Parameters + ========== + + expression : Expr + The target function which is being checked. + interval : Set, optional + The range of values in which we are testing (defaults to set of + all real numbers). + symbol : Symbol, optional + The symbol present in expression which gets varied over the given range. + + Returns + ======= + + Boolean + True if ``expression`` is decreasing (either strictly decreasing or + constant) in the given ``interval``, False otherwise. + + Examples + ======== + + >>> from sympy import is_decreasing + >>> from sympy.abc import x, y + >>> from sympy import S, Interval, oo + >>> is_decreasing(1/(x**2 - 3*x), Interval.open(S(3)/2, 3)) + True + >>> is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3)) + True + >>> is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo)) + True + >>> is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2)) + False + >>> is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, 1.5)) + False + >>> is_decreasing(-x**2, Interval(-oo, 0)) + False + >>> is_decreasing(-x**2 + y, Interval(-oo, 0), x) + False + + """ + return monotonicity_helper(expression, lambda x: x <= 0, interval, symbol) + + +def is_strictly_decreasing(expression, interval=S.Reals, symbol=None): + """ + Return whether the function is strictly decreasing in the given interval. + + Parameters + ========== + + expression : Expr + The target function which is being checked. + interval : Set, optional + The range of values in which we are testing (defaults to set of + all real numbers). + symbol : Symbol, optional + The symbol present in expression which gets varied over the given range. + + Returns + ======= + + Boolean + True if ``expression`` is strictly decreasing in the given ``interval``, + False otherwise. + + Examples + ======== + + >>> from sympy import is_strictly_decreasing + >>> from sympy.abc import x, y + >>> from sympy import S, Interval, oo + >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo)) + True + >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, S(3)/2)) + False + >>> is_strictly_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, 1.5)) + False + >>> is_strictly_decreasing(-x**2, Interval(-oo, 0)) + False + >>> is_strictly_decreasing(-x**2 + y, Interval(-oo, 0), x) + False + + """ + return monotonicity_helper(expression, lambda x: x < 0, interval, symbol) + + +def is_monotonic(expression, interval=S.Reals, symbol=None): + """ + Return whether the function is monotonic in the given interval. + + Parameters + ========== + + expression : Expr + The target function which is being checked. + interval : Set, optional + The range of values in which we are testing (defaults to set of + all real numbers). + symbol : Symbol, optional + The symbol present in expression which gets varied over the given range. + + Returns + ======= + + Boolean + True if ``expression`` is monotonic in the given ``interval``, + False otherwise. + + Raises + ====== + + NotImplementedError + Monotonicity check has not been implemented for the queried function. + + Examples + ======== + + >>> from sympy import is_monotonic + >>> from sympy.abc import x, y + >>> from sympy import S, Interval, oo + >>> is_monotonic(1/(x**2 - 3*x), Interval.open(S(3)/2, 3)) + True + >>> is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3)) + True + >>> is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo)) + True + >>> is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals) + True + >>> is_monotonic(-x**2, S.Reals) + False + >>> is_monotonic(x**2 + y + 1, Interval(1, 2), x) + True + + """ + from sympy.solvers.solveset import solveset + + expression = sympify(expression) + + free = expression.free_symbols + if symbol is None and len(free) > 1: + raise NotImplementedError( + 'is_monotonic has not yet been implemented' + ' for all multivariate expressions.' + ) + + variable = symbol or (free.pop() if free else Symbol('x')) + turning_points = solveset(expression.diff(variable), variable, interval) + return interval.intersection(turning_points) is S.EmptySet diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/test_accumulationbounds.py b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/test_accumulationbounds.py new file mode 100644 index 0000000000000000000000000000000000000000..bcc47c66327fe21ddca3a6b73ca5914e0441b38e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/test_accumulationbounds.py @@ -0,0 +1,336 @@ +from sympy.core.numbers import (E, Rational, oo, pi, zoo) +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt) +from sympy.functions.elementary.trigonometric import (cos, sin, tan) +from sympy.calculus.accumulationbounds import AccumBounds +from sympy.core import Add, Mul, Pow +from sympy.core.expr import unchanged +from sympy.testing.pytest import raises, XFAIL +from sympy.abc import x + +a = Symbol('a', real=True) +B = AccumBounds + + +def test_AccumBounds(): + assert B(1, 2).args == (1, 2) + assert B(1, 2).delta is S.One + assert B(1, 2).mid == Rational(3, 2) + assert B(1, 3).is_real == True + + assert B(1, 1) is S.One + + assert B(1, 2) + 1 == B(2, 3) + assert 1 + B(1, 2) == B(2, 3) + assert B(1, 2) + B(2, 3) == B(3, 5) + + assert -B(1, 2) == B(-2, -1) + + assert B(1, 2) - 1 == B(0, 1) + assert 1 - B(1, 2) == B(-1, 0) + assert B(2, 3) - B(1, 2) == B(0, 2) + + assert x + B(1, 2) == Add(B(1, 2), x) + assert a + B(1, 2) == B(1 + a, 2 + a) + assert B(1, 2) - x == Add(B(1, 2), -x) + + assert B(-oo, 1) + oo == B(-oo, oo) + assert B(1, oo) + oo is oo + assert B(1, oo) - oo == B(-oo, oo) + assert (-oo - B(-1, oo)) is -oo + assert B(-oo, 1) - oo is -oo + + assert B(1, oo) - oo == B(-oo, oo) + assert B(-oo, 1) - (-oo) == B(-oo, oo) + assert (oo - B(1, oo)) == B(-oo, oo) + assert (-oo - B(1, oo)) is -oo + + assert B(1, 2)/2 == B(S.Half, 1) + assert 2/B(2, 3) == B(Rational(2, 3), 1) + assert 1/B(-1, 1) == B(-oo, oo) + + assert abs(B(1, 2)) == B(1, 2) + assert abs(B(-2, -1)) == B(1, 2) + assert abs(B(-2, 1)) == B(0, 2) + assert abs(B(-1, 2)) == B(0, 2) + c = Symbol('c') + raises(ValueError, lambda: B(0, c)) + raises(ValueError, lambda: B(1, -1)) + r = Symbol('r', real=True) + raises(ValueError, lambda: B(r, r - 1)) + + +def test_AccumBounds_mul(): + assert B(1, 2)*2 == B(2, 4) + assert 2*B(1, 2) == B(2, 4) + assert B(1, 2)*B(2, 3) == B(2, 6) + assert B(0, 2)*B(2, oo) == B(0, oo) + l, r = B(-oo, oo), B(-a, a) + assert l*r == B(-oo, oo) + assert r*l == B(-oo, oo) + l, r = B(1, oo), B(-3, -2) + assert l*r == B(-oo, -2) + assert r*l == B(-oo, -2) + assert B(1, 2)*0 == 0 + assert B(1, oo)*0 == B(0, oo) + assert B(-oo, 1)*0 == B(-oo, 0) + assert B(-oo, oo)*0 == B(-oo, oo) + + assert B(1, 2)*x == Mul(B(1, 2), x, evaluate=False) + + assert B(0, 2)*oo == B(0, oo) + assert B(-2, 0)*oo == B(-oo, 0) + assert B(0, 2)*(-oo) == B(-oo, 0) + assert B(-2, 0)*(-oo) == B(0, oo) + assert B(-1, 1)*oo == B(-oo, oo) + assert B(-1, 1)*(-oo) == B(-oo, oo) + assert B(-oo, oo)*oo == B(-oo, oo) + + +def test_AccumBounds_div(): + assert B(-1, 3)/B(3, 4) == B(Rational(-1, 3), 1) + assert B(-2, 4)/B(-3, 4) == B(-oo, oo) + assert B(-3, -2)/B(-4, 0) == B(S.Half, oo) + + # these two tests can have a better answer + # after Union of B is improved + assert B(-3, -2)/B(-2, 1) == B(-oo, oo) + assert B(2, 3)/B(-2, 2) == B(-oo, oo) + + assert B(-3, -2)/B(0, 4) == B(-oo, Rational(-1, 2)) + assert B(2, 4)/B(-3, 0) == B(-oo, Rational(-2, 3)) + assert B(2, 4)/B(0, 3) == B(Rational(2, 3), oo) + + assert B(0, 1)/B(0, 1) == B(0, oo) + assert B(-1, 0)/B(0, 1) == B(-oo, 0) + assert B(-1, 2)/B(-2, 2) == B(-oo, oo) + + assert 1/B(-1, 2) == B(-oo, oo) + assert 1/B(0, 2) == B(S.Half, oo) + assert (-1)/B(0, 2) == B(-oo, Rational(-1, 2)) + assert 1/B(-oo, 0) == B(-oo, 0) + assert 1/B(-1, 0) == B(-oo, -1) + assert (-2)/B(-oo, 0) == B(0, oo) + assert 1/B(-oo, -1) == B(-1, 0) + + assert B(1, 2)/a == Mul(B(1, 2), 1/a, evaluate=False) + + assert B(1, 2)/0 == B(1, 2)*zoo + assert B(1, oo)/oo == B(0, oo) + assert B(1, oo)/(-oo) == B(-oo, 0) + assert B(-oo, -1)/oo == B(-oo, 0) + assert B(-oo, -1)/(-oo) == B(0, oo) + assert B(-oo, oo)/oo == B(-oo, oo) + assert B(-oo, oo)/(-oo) == B(-oo, oo) + assert B(-1, oo)/oo == B(0, oo) + assert B(-1, oo)/(-oo) == B(-oo, 0) + assert B(-oo, 1)/oo == B(-oo, 0) + assert B(-oo, 1)/(-oo) == B(0, oo) + + +def test_issue_18795(): + r = Symbol('r', real=True) + a = B(-1,1) + c = B(7, oo) + b = B(-oo, oo) + assert c - tan(r) == B(7-tan(r), oo) + assert b + tan(r) == B(-oo, oo) + assert (a + r)/a == B(-oo, oo)*B(r - 1, r + 1) + assert (b + a)/a == B(-oo, oo) + + +def test_AccumBounds_func(): + assert (x**2 + 2*x + 1).subs(x, B(-1, 1)) == B(-1, 4) + assert exp(B(0, 1)) == B(1, E) + assert exp(B(-oo, oo)) == B(0, oo) + assert log(B(3, 6)) == B(log(3), log(6)) + + +@XFAIL +def test_AccumBounds_powf(): + nn = Symbol('nn', nonnegative=True) + assert B(1 + nn, 2 + nn)**B(1, 2) == B(1 + nn, (2 + nn)**2) + i = Symbol('i', integer=True, negative=True) + assert B(1, 2)**i == B(2**i, 1) + + +def test_AccumBounds_pow(): + assert B(0, 2)**2 == B(0, 4) + assert B(-1, 1)**2 == B(0, 1) + assert B(1, 2)**2 == B(1, 4) + assert B(-1, 2)**3 == B(-1, 8) + assert B(-1, 1)**0 == 1 + + assert B(1, 2)**Rational(5, 2) == B(1, 4*sqrt(2)) + assert B(0, 2)**S.Half == B(0, sqrt(2)) + + neg = Symbol('neg', negative=True) + assert unchanged(Pow, B(neg, 1), S.Half) + nn = Symbol('nn', nonnegative=True) + assert B(nn, nn + 1)**S.Half == B(sqrt(nn), sqrt(nn + 1)) + assert B(nn, nn + 1)**nn == B(nn**nn, (nn + 1)**nn) + assert unchanged(Pow, B(nn, nn + 1), x) + i = Symbol('i', integer=True) + assert B(1, 2)**i == B(Min(1, 2**i), Max(1, 2**i)) + i = Symbol('i', integer=True, nonnegative=True) + assert B(1, 2)**i == B(1, 2**i) + assert B(0, 1)**i == B(0**i, 1) + + assert B(1, 5)**(-2) == B(Rational(1, 25), 1) + assert B(-1, 3)**(-2) == B(0, oo) + assert B(0, 2)**(-3) == B(Rational(1, 8), oo) + assert B(-2, 0)**(-3) == B(-oo, -Rational(1, 8)) + assert B(0, 2)**(-2) == B(Rational(1, 4), oo) + assert B(-1, 2)**(-3) == B(-oo, oo) + assert B(-3, -2)**(-3) == B(Rational(-1, 8), Rational(-1, 27)) + assert B(-3, -2)**(-2) == B(Rational(1, 9), Rational(1, 4)) + assert B(0, oo)**S.Half == B(0, oo) + assert B(-oo, 0)**(-2) == B(0, oo) + assert B(-2, 0)**(-2) == B(Rational(1, 4), oo) + + assert B(Rational(1, 3), S.Half)**oo is S.Zero + assert B(0, S.Half)**oo is S.Zero + assert B(S.Half, 1)**oo == B(0, oo) + assert B(0, 1)**oo == B(0, oo) + assert B(2, 3)**oo is oo + assert B(1, 2)**oo == B(0, oo) + assert B(S.Half, 3)**oo == B(0, oo) + assert B(Rational(-1, 3), Rational(-1, 4))**oo is S.Zero + assert B(-1, Rational(-1, 2))**oo is S.NaN + assert B(-3, -2)**oo is zoo + assert B(-2, -1)**oo is S.NaN + assert B(-2, Rational(-1, 2))**oo is S.NaN + assert B(Rational(-1, 2), S.Half)**oo is S.Zero + assert B(Rational(-1, 2), 1)**oo == B(0, oo) + assert B(Rational(-2, 3), 2)**oo == B(0, oo) + assert B(-1, 1)**oo == B(-oo, oo) + assert B(-1, S.Half)**oo == B(-oo, oo) + assert B(-1, 2)**oo == B(-oo, oo) + assert B(-2, S.Half)**oo == B(-oo, oo) + + assert B(1, 2)**x == Pow(B(1, 2), x, evaluate=False) + + assert B(2, 3)**(-oo) is S.Zero + assert B(0, 2)**(-oo) == B(0, oo) + assert B(-1, 2)**(-oo) == B(-oo, oo) + + assert (tan(x)**sin(2*x)).subs(x, B(0, pi/2)) == \ + Pow(B(-oo, oo), B(0, 1)) + + +def test_AccumBounds_exponent(): + # base is 0 + z = 0**B(a, a + S.Half) + assert z.subs(a, 0) == B(0, 1) + assert z.subs(a, 1) == 0 + p = z.subs(a, -1) + assert p.is_Pow and p.args == (0, B(-1, -S.Half)) + # base > 0 + # when base is 1 the type of bounds does not matter + assert 1**B(a, a + 1) == 1 + # otherwise we need to know if 0 is in the bounds + assert S.Half**B(-2, 2) == B(S(1)/4, 4) + assert 2**B(-2, 2) == B(S(1)/4, 4) + + # +eps may introduce +oo + # if there is a negative integer exponent + assert B(0, 1)**B(S(1)/2, 1) == B(0, 1) + assert B(0, 1)**B(0, 1) == B(0, 1) + + # positive bases have positive bounds + assert B(2, 3)**B(-3, -2) == B(S(1)/27, S(1)/4) + assert B(2, 3)**B(-3, 2) == B(S(1)/27, 9) + + # bounds generating imaginary parts unevaluated + assert unchanged(Pow, B(-1, 1), B(1, 2)) + assert B(0, S(1)/2)**B(1, oo) == B(0, S(1)/2) + assert B(0, 1)**B(1, oo) == B(0, oo) + assert B(0, 2)**B(1, oo) == B(0, oo) + assert B(0, oo)**B(1, oo) == B(0, oo) + assert B(S(1)/2, 1)**B(1, oo) == B(0, oo) + assert B(S(1)/2, 1)**B(-oo, -1) == B(0, oo) + assert B(S(1)/2, 1)**B(-oo, oo) == B(0, oo) + assert B(S(1)/2, 2)**B(1, oo) == B(0, oo) + assert B(S(1)/2, 2)**B(-oo, -1) == B(0, oo) + assert B(S(1)/2, 2)**B(-oo, oo) == B(0, oo) + assert B(S(1)/2, oo)**B(1, oo) == B(0, oo) + assert B(S(1)/2, oo)**B(-oo, -1) == B(0, oo) + assert B(S(1)/2, oo)**B(-oo, oo) == B(0, oo) + assert B(1, 2)**B(1, oo) == B(0, oo) + assert B(1, 2)**B(-oo, -1) == B(0, oo) + assert B(1, 2)**B(-oo, oo) == B(0, oo) + assert B(1, oo)**B(1, oo) == B(0, oo) + assert B(1, oo)**B(-oo, -1) == B(0, oo) + assert B(1, oo)**B(-oo, oo) == B(0, oo) + assert B(2, oo)**B(1, oo) == B(2, oo) + assert B(2, oo)**B(-oo, -1) == B(0, S(1)/2) + assert B(2, oo)**B(-oo, oo) == B(0, oo) + + +def test_comparison_AccumBounds(): + assert (B(1, 3) < 4) == S.true + assert (B(1, 3) < -1) == S.false + assert (B(1, 3) < 2).rel_op == '<' + assert (B(1, 3) <= 2).rel_op == '<=' + + assert (B(1, 3) > 4) == S.false + assert (B(1, 3) > -1) == S.true + assert (B(1, 3) > 2).rel_op == '>' + assert (B(1, 3) >= 2).rel_op == '>=' + + assert (B(1, 3) < B(4, 6)) == S.true + assert (B(1, 3) < B(2, 4)).rel_op == '<' + assert (B(1, 3) < B(-2, 0)) == S.false + + assert (B(1, 3) <= B(4, 6)) == S.true + assert (B(1, 3) <= B(-2, 0)) == S.false + + assert (B(1, 3) > B(4, 6)) == S.false + assert (B(1, 3) > B(-2, 0)) == S.true + + assert (B(1, 3) >= B(4, 6)) == S.false + assert (B(1, 3) >= B(-2, 0)) == S.true + + # issue 13499 + assert (cos(x) > 0).subs(x, oo) == (B(-1, 1) > 0) + + c = Symbol('c') + raises(TypeError, lambda: (B(0, 1) < c)) + raises(TypeError, lambda: (B(0, 1) <= c)) + raises(TypeError, lambda: (B(0, 1) > c)) + raises(TypeError, lambda: (B(0, 1) >= c)) + + +def test_contains_AccumBounds(): + assert (1 in B(1, 2)) == S.true + raises(TypeError, lambda: a in B(1, 2)) + assert 0 in B(-1, 0) + raises(TypeError, lambda: + (cos(1)**2 + sin(1)**2 - 1) in B(-1, 0)) + assert (-oo in B(1, oo)) == S.true + assert (oo in B(-oo, 0)) == S.true + + # issue 13159 + assert Mul(0, B(-1, 1)) == Mul(B(-1, 1), 0) == 0 + import itertools + for perm in itertools.permutations([0, B(-1, 1), x]): + assert Mul(*perm) == 0 + + +def test_intersection_AccumBounds(): + assert B(0, 3).intersection(B(1, 2)) == B(1, 2) + assert B(0, 3).intersection(B(1, 4)) == B(1, 3) + assert B(0, 3).intersection(B(-1, 2)) == B(0, 2) + assert B(0, 3).intersection(B(-1, 4)) == B(0, 3) + assert B(0, 1).intersection(B(2, 3)) == S.EmptySet + raises(TypeError, lambda: B(0, 3).intersection(1)) + + +def test_union_AccumBounds(): + assert B(0, 3).union(B(1, 2)) == B(0, 3) + assert B(0, 3).union(B(1, 4)) == B(0, 4) + assert B(0, 3).union(B(-1, 2)) == B(-1, 3) + assert B(0, 3).union(B(-1, 4)) == B(-1, 4) + raises(TypeError, lambda: B(0, 3).union(1)) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/test_finite_diff.py b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/test_finite_diff.py new file mode 100644 index 0000000000000000000000000000000000000000..ce695c6c6ac7aa86a8a8545e81458236a0ebda9c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/test_finite_diff.py @@ -0,0 +1,168 @@ +from itertools import product + +from sympy.core.function import (Function, diff) +from sympy.core.numbers import Rational +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.elementary.exponential import exp +from sympy.calculus.finite_diff import ( + apply_finite_diff, differentiate_finite, finite_diff_weights, + _as_finite_diff +) +from sympy.testing.pytest import raises, warns_deprecated_sympy + + +def test_apply_finite_diff(): + x, h = symbols('x h') + f = Function('f') + assert (apply_finite_diff(1, [x-h, x+h], [f(x-h), f(x+h)], x) - + (f(x+h)-f(x-h))/(2*h)).simplify() == 0 + + assert (apply_finite_diff(1, [5, 6, 7], [f(5), f(6), f(7)], 5) - + (Rational(-3, 2)*f(5) + 2*f(6) - S.Half*f(7))).simplify() == 0 + raises(ValueError, lambda: apply_finite_diff(1, [x, h], [f(x)])) + + +def test_finite_diff_weights(): + + d = finite_diff_weights(1, [5, 6, 7], 5) + assert d[1][2] == [Rational(-3, 2), 2, Rational(-1, 2)] + + # Table 1, p. 702 in doi:10.1090/S0025-5718-1988-0935077-0 + # -------------------------------------------------------- + xl = [0, 1, -1, 2, -2, 3, -3, 4, -4] + + # d holds all coefficients + d = finite_diff_weights(4, xl, S.Zero) + + # Zeroeth derivative + for i in range(5): + assert d[0][i] == [S.One] + [S.Zero]*8 + + # First derivative + assert d[1][0] == [S.Zero]*9 + assert d[1][2] == [S.Zero, S.Half, Rational(-1, 2)] + [S.Zero]*6 + assert d[1][4] == [S.Zero, Rational(2, 3), Rational(-2, 3), Rational(-1, 12), Rational(1, 12)] + [S.Zero]*4 + assert d[1][6] == [S.Zero, Rational(3, 4), Rational(-3, 4), Rational(-3, 20), Rational(3, 20), + Rational(1, 60), Rational(-1, 60)] + [S.Zero]*2 + assert d[1][8] == [S.Zero, Rational(4, 5), Rational(-4, 5), Rational(-1, 5), Rational(1, 5), + Rational(4, 105), Rational(-4, 105), Rational(-1, 280), Rational(1, 280)] + + # Second derivative + for i in range(2): + assert d[2][i] == [S.Zero]*9 + assert d[2][2] == [-S(2), S.One, S.One] + [S.Zero]*6 + assert d[2][4] == [Rational(-5, 2), Rational(4, 3), Rational(4, 3), Rational(-1, 12), Rational(-1, 12)] + [S.Zero]*4 + assert d[2][6] == [Rational(-49, 18), Rational(3, 2), Rational(3, 2), Rational(-3, 20), Rational(-3, 20), + Rational(1, 90), Rational(1, 90)] + [S.Zero]*2 + assert d[2][8] == [Rational(-205, 72), Rational(8, 5), Rational(8, 5), Rational(-1, 5), Rational(-1, 5), + Rational(8, 315), Rational(8, 315), Rational(-1, 560), Rational(-1, 560)] + + # Third derivative + for i in range(3): + assert d[3][i] == [S.Zero]*9 + assert d[3][4] == [S.Zero, -S.One, S.One, S.Half, Rational(-1, 2)] + [S.Zero]*4 + assert d[3][6] == [S.Zero, Rational(-13, 8), Rational(13, 8), S.One, -S.One, + Rational(-1, 8), Rational(1, 8)] + [S.Zero]*2 + assert d[3][8] == [S.Zero, Rational(-61, 30), Rational(61, 30), Rational(169, 120), Rational(-169, 120), + Rational(-3, 10), Rational(3, 10), Rational(7, 240), Rational(-7, 240)] + + # Fourth derivative + for i in range(4): + assert d[4][i] == [S.Zero]*9 + assert d[4][4] == [S(6), -S(4), -S(4), S.One, S.One] + [S.Zero]*4 + assert d[4][6] == [Rational(28, 3), Rational(-13, 2), Rational(-13, 2), S(2), S(2), + Rational(-1, 6), Rational(-1, 6)] + [S.Zero]*2 + assert d[4][8] == [Rational(91, 8), Rational(-122, 15), Rational(-122, 15), Rational(169, 60), Rational(169, 60), + Rational(-2, 5), Rational(-2, 5), Rational(7, 240), Rational(7, 240)] + + # Table 2, p. 703 in doi:10.1090/S0025-5718-1988-0935077-0 + # -------------------------------------------------------- + xl = [[j/S(2) for j in list(range(-i*2+1, 0, 2))+list(range(1, i*2+1, 2))] + for i in range(1, 5)] + + # d holds all coefficients + d = [finite_diff_weights({0: 1, 1: 2, 2: 4, 3: 4}[i], xl[i], 0) for + i in range(4)] + + # Zeroth derivative + assert d[0][0][1] == [S.Half, S.Half] + assert d[1][0][3] == [Rational(-1, 16), Rational(9, 16), Rational(9, 16), Rational(-1, 16)] + assert d[2][0][5] == [Rational(3, 256), Rational(-25, 256), Rational(75, 128), Rational(75, 128), + Rational(-25, 256), Rational(3, 256)] + assert d[3][0][7] == [Rational(-5, 2048), Rational(49, 2048), Rational(-245, 2048), Rational(1225, 2048), + Rational(1225, 2048), Rational(-245, 2048), Rational(49, 2048), Rational(-5, 2048)] + + # First derivative + assert d[0][1][1] == [-S.One, S.One] + assert d[1][1][3] == [Rational(1, 24), Rational(-9, 8), Rational(9, 8), Rational(-1, 24)] + assert d[2][1][5] == [Rational(-3, 640), Rational(25, 384), Rational(-75, 64), + Rational(75, 64), Rational(-25, 384), Rational(3, 640)] + assert d[3][1][7] == [Rational(5, 7168), Rational(-49, 5120), + Rational(245, 3072), Rational(-1225, 1024), + Rational(1225, 1024), Rational(-245, 3072), + Rational(49, 5120), Rational(-5, 7168)] + + # Reasonably the rest of the table is also correct... (testing of that + # deemed excessive at the moment) + raises(ValueError, lambda: finite_diff_weights(-1, [1, 2])) + raises(ValueError, lambda: finite_diff_weights(1.2, [1, 2])) + x = symbols('x') + raises(ValueError, lambda: finite_diff_weights(x, [1, 2])) + + +def test_as_finite_diff(): + x = symbols('x') + f = Function('f') + dx = Function('dx') + + _as_finite_diff(f(x).diff(x), [x-2, x-1, x, x+1, x+2]) + + # Use of undefined functions in ``points`` + df_true = -f(x+dx(x)/2-dx(x+dx(x)/2)/2) / dx(x+dx(x)/2) \ + + f(x+dx(x)/2+dx(x+dx(x)/2)/2) / dx(x+dx(x)/2) + df_test = diff(f(x), x).as_finite_difference(points=dx(x), x0=x+dx(x)/2) + assert (df_test - df_true).simplify() == 0 + + +def test_differentiate_finite(): + x, y, h = symbols('x y h') + f = Function('f') + with warns_deprecated_sympy(): + res0 = differentiate_finite(f(x, y) + exp(42), x, y, evaluate=True) + xm, xp, ym, yp = [v + sign*S.Half for v, sign in product([x, y], [-1, 1])] + ref0 = f(xm, ym) + f(xp, yp) - f(xm, yp) - f(xp, ym) + assert (res0 - ref0).simplify() == 0 + + g = Function('g') + with warns_deprecated_sympy(): + res1 = differentiate_finite(f(x)*g(x) + 42, x, evaluate=True) + ref1 = (-f(x - S.Half) + f(x + S.Half))*g(x) + \ + (-g(x - S.Half) + g(x + S.Half))*f(x) + assert (res1 - ref1).simplify() == 0 + + res2 = differentiate_finite(f(x) + x**3 + 42, x, points=[x-1, x+1]) + ref2 = (f(x + 1) + (x + 1)**3 - f(x - 1) - (x - 1)**3)/2 + assert (res2 - ref2).simplify() == 0 + raises(TypeError, lambda: differentiate_finite(f(x)*g(x), x, + pints=[x-1, x+1])) + + res3 = differentiate_finite(f(x)*g(x).diff(x), x) + ref3 = (-g(x) + g(x + 1))*f(x + S.Half) - (g(x) - g(x - 1))*f(x - S.Half) + assert res3 == ref3 + + res4 = differentiate_finite(f(x)*g(x).diff(x).diff(x), x) + ref4 = -((g(x - Rational(3, 2)) - 2*g(x - S.Half) + g(x + S.Half))*f(x - S.Half)) \ + + (g(x - S.Half) - 2*g(x + S.Half) + g(x + Rational(3, 2)))*f(x + S.Half) + assert res4 == ref4 + + res5_expr = f(x).diff(x)*g(x).diff(x) + res5 = differentiate_finite(res5_expr, points=[x-h, x, x+h]) + ref5 = (-2*f(x)/h + f(-h + x)/(2*h) + 3*f(h + x)/(2*h))*(-2*g(x)/h + g(-h + x)/(2*h) \ + + 3*g(h + x)/(2*h))/(2*h) - (2*f(x)/h - 3*f(-h + x)/(2*h) - \ + f(h + x)/(2*h))*(2*g(x)/h - 3*g(-h + x)/(2*h) - g(h + x)/(2*h))/(2*h) + assert res5 == ref5 + + res6 = res5.limit(h, 0).doit() + ref6 = diff(res5_expr, x) + assert res6 == ref6 diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/test_util.py b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..6367fb98b1cb5c4d3af706d9b7a994eab379aaa1 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/test_util.py @@ -0,0 +1,331 @@ +from sympy.core.numbers import (E, I, Rational, oo, pi) +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.complexes import (Abs, re) +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import (cos, cot, csc, sec, sin, tan) +from sympy.functions.special.error_functions import expint +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.simplify.simplify import simplify +from sympy.calculus.util import (function_range, continuous_domain, not_empty_in, + periodicity, lcim, is_convex, + stationary_points, minimum, maximum) +from sympy.sets.sets import (Interval, FiniteSet, Complement, Union) +from sympy.testing.pytest import raises, _both_exp_pow +from sympy.abc import x + +a = Symbol('a', real=True) + +def test_function_range(): + x, y, a, b = symbols('x y a b') + assert function_range(sin(x), x, Interval(-pi/2, pi/2) + ) == Interval(-1, 1) + assert function_range(sin(x), x, Interval(0, pi) + ) == Interval(0, 1) + assert function_range(tan(x), x, Interval(0, pi) + ) == Interval(-oo, oo) + assert function_range(tan(x), x, Interval(pi/2, pi) + ) == Interval(-oo, 0) + assert function_range((x + 3)/(x - 2), x, Interval(-5, 5) + ) == Union(Interval(-oo, Rational(2, 7)), Interval(Rational(8, 3), oo)) + assert function_range(1/(x**2), x, Interval(-1, 1) + ) == Interval(1, oo) + assert function_range(exp(x), x, Interval(-1, 1) + ) == Interval(exp(-1), exp(1)) + assert function_range(log(x) - x, x, S.Reals + ) == Interval(-oo, -1) + assert function_range(sqrt(3*x - 1), x, Interval(0, 2) + ) == Interval(0, sqrt(5)) + assert function_range(x*(x - 1) - (x**2 - x), x, S.Reals + ) == FiniteSet(0) + assert function_range(x*(x - 1) - (x**2 - x) + y, x, S.Reals + ) == FiniteSet(y) + assert function_range(sin(x), x, Union(Interval(-5, -3), FiniteSet(4)) + ) == Union(Interval(-sin(3), 1), FiniteSet(sin(4))) + assert function_range(cos(x), x, Interval(-oo, -4) + ) == Interval(-1, 1) + assert function_range(cos(x), x, S.EmptySet) == S.EmptySet + assert function_range(x/sqrt(x**2+1), x, S.Reals) == Interval.open(-1,1) + raises(NotImplementedError, lambda : function_range( + exp(x)*(sin(x) - cos(x))/2 - x, x, S.Reals)) + raises(NotImplementedError, lambda : function_range( + sin(x) + x, x, S.Reals)) # issue 13273 + raises(NotImplementedError, lambda : function_range( + log(x), x, S.Integers)) + raises(NotImplementedError, lambda : function_range( + sin(x)/2, x, S.Naturals)) + + +def test_continuous_domain(): + x = Symbol('x') + assert continuous_domain(sin(x), x, Interval(0, 2*pi)) == Interval(0, 2*pi) + assert continuous_domain(tan(x), x, Interval(0, 2*pi)) == \ + Union(Interval(0, pi/2, False, True), Interval(pi/2, pi*Rational(3, 2), True, True), + Interval(pi*Rational(3, 2), 2*pi, True, False)) + assert continuous_domain((x - 1)/((x - 1)**2), x, S.Reals) == \ + Union(Interval(-oo, 1, True, True), Interval(1, oo, True, True)) + assert continuous_domain(log(x) + log(4*x - 1), x, S.Reals) == \ + Interval(Rational(1, 4), oo, True, True) + assert continuous_domain(1/sqrt(x - 3), x, S.Reals) == Interval(3, oo, True, True) + assert continuous_domain(1/x - 2, x, S.Reals) == \ + Union(Interval.open(-oo, 0), Interval.open(0, oo)) + assert continuous_domain(1/(x**2 - 4) + 2, x, S.Reals) == \ + Union(Interval.open(-oo, -2), Interval.open(-2, 2), Interval.open(2, oo)) + domain = continuous_domain(log(tan(x)**2 + 1), x, S.Reals) + assert not domain.contains(3*pi/2) + assert domain.contains(5) + d = Symbol('d', even=True, zero=False) + assert continuous_domain(x**(1/d), x, S.Reals) == Interval(0, oo) + + +def test_not_empty_in(): + assert not_empty_in(FiniteSet(x, 2*x).intersect(Interval(1, 2, True, False)), x) == \ + Interval(S.Half, 2, True, False) + assert not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) == \ + Union(Interval(-sqrt(2), -1), Interval(1, 2)) + assert not_empty_in(FiniteSet(x**2 + x, x).intersect(Interval(2, 4)), x) == \ + Union(Interval(-sqrt(17)/2 - S.Half, -2), + Interval(1, Rational(-1, 2) + sqrt(17)/2), Interval(2, 4)) + assert not_empty_in(FiniteSet(x/(x - 1)).intersect(S.Reals), x) == \ + Complement(S.Reals, FiniteSet(1)) + assert not_empty_in(FiniteSet(a/(a - 1)).intersect(S.Reals), a) == \ + Complement(S.Reals, FiniteSet(1)) + assert not_empty_in(FiniteSet((x**2 - 3*x + 2)/(x - 1)).intersect(S.Reals), x) == \ + Complement(S.Reals, FiniteSet(1)) + assert not_empty_in(FiniteSet(3, 4, x/(x - 1)).intersect(Interval(2, 3)), x) == \ + Interval(-oo, oo) + assert not_empty_in(FiniteSet(4, x/(x - 1)).intersect(Interval(2, 3)), x) == \ + Interval(S(3)/2, 2) + assert not_empty_in(FiniteSet(x/(x**2 - 1)).intersect(S.Reals), x) == \ + Complement(S.Reals, FiniteSet(-1, 1)) + assert not_empty_in(FiniteSet(x, x**2).intersect(Union(Interval(1, 3, True, True), + Interval(4, 5))), x) == \ + Union(Interval(-sqrt(5), -2), Interval(-sqrt(3), -1, True, True), + Interval(1, 3, True, True), Interval(4, 5)) + assert not_empty_in(FiniteSet(1).intersect(Interval(3, 4)), x) == S.EmptySet + assert not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) == \ + Union(Interval(-2, -1, True, False), Interval(2, oo)) + raises(ValueError, lambda: not_empty_in(x)) + raises(ValueError, lambda: not_empty_in(Interval(0, 1), x)) + raises(NotImplementedError, + lambda: not_empty_in(FiniteSet(x).intersect(S.Reals), x, a)) + + +@_both_exp_pow +def test_periodicity(): + x = Symbol('x') + y = Symbol('y') + z = Symbol('z', real=True) + + assert periodicity(sin(2*x), x) == pi + assert periodicity((-2)*tan(4*x), x) == pi/4 + assert periodicity(sin(x)**2, x) == 2*pi + assert periodicity(3**tan(3*x), x) == pi/3 + assert periodicity(tan(x)*cos(x), x) == 2*pi + assert periodicity(sin(x)**(tan(x)), x) == 2*pi + assert periodicity(tan(x)*sec(x), x) == 2*pi + assert periodicity(sin(2*x)*cos(2*x) - y, x) == pi/2 + assert periodicity(tan(x) + cot(x), x) == pi + assert periodicity(sin(x) - cos(2*x), x) == 2*pi + assert periodicity(sin(x) - 1, x) == 2*pi + assert periodicity(sin(4*x) + sin(x)*cos(x), x) == pi + assert periodicity(exp(sin(x)), x) == 2*pi + assert periodicity(log(cot(2*x)) - sin(cos(2*x)), x) == pi + assert periodicity(sin(2*x)*exp(tan(x) - csc(2*x)), x) == pi + assert periodicity(cos(sec(x) - csc(2*x)), x) == 2*pi + assert periodicity(tan(sin(2*x)), x) == pi + assert periodicity(2*tan(x)**2, x) == pi + assert periodicity(sin(x%4), x) == 4 + assert periodicity(sin(x)%4, x) == 2*pi + assert periodicity(tan((3*x-2)%4), x) == Rational(4, 3) + assert periodicity((sqrt(2)*(x+1)+x) % 3, x) == 3 / (sqrt(2)+1) + assert periodicity((x**2+1) % x, x) is None + assert periodicity(sin(re(x)), x) == 2*pi + assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero + assert periodicity(tan(x), y) is S.Zero + assert periodicity(sin(x) + I*cos(x), x) == 2*pi + assert periodicity(x - sin(2*y), y) == pi + + assert periodicity(exp(x), x) is None + assert periodicity(exp(I*x), x) == 2*pi + assert periodicity(exp(I*z), z) == 2*pi + assert periodicity(exp(z), z) is None + assert periodicity(exp(log(sin(z) + I*cos(2*z)), evaluate=False), z) == 2*pi + assert periodicity(exp(log(sin(2*z) + I*cos(z)), evaluate=False), z) == 2*pi + assert periodicity(exp(sin(z)), z) == 2*pi + assert periodicity(exp(2*I*z), z) == pi + assert periodicity(exp(z + I*sin(z)), z) is None + assert periodicity(exp(cos(z/2) + sin(z)), z) == 4*pi + assert periodicity(log(x), x) is None + assert periodicity(exp(x)**sin(x), x) is None + assert periodicity(sin(x)**y, y) is None + + assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi + assert all(periodicity(Abs(f(x)), x) == pi for f in ( + cos, sin, sec, csc, tan, cot)) + assert periodicity(Abs(sin(tan(x))), x) == pi + assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2*pi + assert periodicity(sin(x) > S.Half, x) == 2*pi + + assert periodicity(x > 2, x) is None + assert periodicity(x**3 - x**2 + 1, x) is None + assert periodicity(Abs(x), x) is None + assert periodicity(Abs(x**2 - 1), x) is None + + assert periodicity((x**2 + 4)%2, x) is None + assert periodicity((E**x)%3, x) is None + + assert periodicity(sin(expint(1, x))/expint(1, x), x) is None + # returning `None` for any Piecewise + p = Piecewise((0, x < -1), (x**2, x <= 1), (log(x), True)) + assert periodicity(p, x) is None + + m = MatrixSymbol('m', 3, 3) + raises(NotImplementedError, lambda: periodicity(sin(m), m)) + raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m)) + raises(NotImplementedError, lambda: periodicity(sin(m), m[0, 0])) + raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m[0, 0])) + + +def test_periodicity_check(): + x = Symbol('x') + y = Symbol('y') + + assert periodicity(tan(x), x, check=True) == pi + assert periodicity(sin(x) + cos(x), x, check=True) == 2*pi + assert periodicity(sec(x), x) == 2*pi + assert periodicity(sin(x*y), x) == 2*pi/abs(y) + assert periodicity(Abs(sec(sec(x))), x) == pi + + +def test_lcim(): + assert lcim([S.Half, S(2), S(3)]) == 6 + assert lcim([pi/2, pi/4, pi]) == pi + assert lcim([2*pi, pi/2]) == 2*pi + assert lcim([S.One, 2*pi]) is None + assert lcim([S(2) + 2*E, E/3 + Rational(1, 3), S.One + E]) == S(2) + 2*E + + +def test_is_convex(): + assert is_convex(1/x, x, domain=Interval.open(0, oo)) == True + assert is_convex(1/x, x, domain=Interval(-oo, 0)) == False + assert is_convex(x**2, x, domain=Interval(0, oo)) == True + assert is_convex(1/x**3, x, domain=Interval.Lopen(0, oo)) == True + assert is_convex(-1/x**3, x, domain=Interval.Ropen(-oo, 0)) == True + assert is_convex(log(x), x) == False + raises(NotImplementedError, lambda: is_convex(log(x), x, a)) + + +def test_stationary_points(): + x, y = symbols('x y') + + assert stationary_points(sin(x), x, Interval(-pi/2, pi/2) + ) == {-pi/2, pi/2} + assert stationary_points(sin(x), x, Interval.Ropen(0, pi/4) + ) is S.EmptySet + assert stationary_points(tan(x), x, + ) is S.EmptySet + assert stationary_points(sin(x)*cos(x), x, Interval(0, pi) + ) == {pi/4, pi*Rational(3, 4)} + assert stationary_points(sec(x), x, Interval(0, pi) + ) == {0, pi} + assert stationary_points((x+3)*(x-2), x + ) == FiniteSet(Rational(-1, 2)) + assert stationary_points((x + 3)/(x - 2), x, Interval(-5, 5) + ) is S.EmptySet + assert stationary_points((x**2+3)/(x-2), x + ) == {2 - sqrt(7), 2 + sqrt(7)} + assert stationary_points((x**2+3)/(x-2), x, Interval(0, 5) + ) == {2 + sqrt(7)} + assert stationary_points(x**4 + x**3 - 5*x**2, x, S.Reals + ) == FiniteSet(-2, 0, Rational(5, 4)) + assert stationary_points(exp(x), x + ) is S.EmptySet + assert stationary_points(log(x) - x, x, S.Reals + ) == {1} + assert stationary_points(cos(x), x, Union(Interval(0, 5), Interval(-6, -3)) + ) == {0, -pi, pi} + assert stationary_points(y, x, S.Reals + ) == S.Reals + assert stationary_points(y, x, S.EmptySet) == S.EmptySet + + +def test_maximum(): + x, y = symbols('x y') + assert maximum(sin(x), x) is S.One + assert maximum(sin(x), x, Interval(0, 1)) == sin(1) + assert maximum(tan(x), x) is oo + assert maximum(tan(x), x, Interval(-pi/4, pi/4)) is S.One + assert maximum(sin(x)*cos(x), x, S.Reals) == S.Half + assert simplify(maximum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8))) + ) == sqrt(2)/4 + assert maximum((x+3)*(x-2), x) is oo + assert maximum((x+3)*(x-2), x, Interval(-5, 0)) == S(14) + assert maximum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(2, 7) + assert simplify(maximum(-x**4-x**3+x**2+10, x) + ) == 41*sqrt(41)/512 + Rational(5419, 512) + assert maximum(exp(x), x, Interval(-oo, 2)) == exp(2) + assert maximum(log(x) - x, x, S.Reals) is S.NegativeOne + assert maximum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3)) + ) is S.One + assert maximum(cos(x)-sin(x), x, S.Reals) == sqrt(2) + assert maximum(y, x, S.Reals) == y + assert maximum(abs(a**3 + a), a, Interval(0, 2)) == 10 + assert maximum(abs(60*a**3 + 24*a), a, Interval(0, 2)) == 528 + assert maximum(abs(12*a*(5*a**2 + 2)), a, Interval(0, 2)) == 528 + assert maximum(x/sqrt(x**2+1), x, S.Reals) == 1 + + raises(ValueError, lambda : maximum(sin(x), x, S.EmptySet)) + raises(ValueError, lambda : maximum(log(cos(x)), x, S.EmptySet)) + raises(ValueError, lambda : maximum(1/(x**2 + y**2 + 1), x, S.EmptySet)) + raises(ValueError, lambda : maximum(sin(x), sin(x))) + raises(ValueError, lambda : maximum(sin(x), x*y, S.EmptySet)) + raises(ValueError, lambda : maximum(sin(x), S.One)) + + +def test_minimum(): + x, y = symbols('x y') + + assert minimum(sin(x), x) is S.NegativeOne + assert minimum(sin(x), x, Interval(1, 4)) == sin(4) + assert minimum(tan(x), x) is -oo + assert minimum(tan(x), x, Interval(-pi/4, pi/4)) is S.NegativeOne + assert minimum(sin(x)*cos(x), x, S.Reals) == Rational(-1, 2) + assert simplify(minimum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8))) + ) == -sqrt(2)/4 + assert minimum((x+3)*(x-2), x) == Rational(-25, 4) + assert minimum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(-3, 2) + assert minimum(x**4-x**3+x**2+10, x) == S(10) + assert minimum(exp(x), x, Interval(-2, oo)) == exp(-2) + assert minimum(log(x) - x, x, S.Reals) is -oo + assert minimum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3)) + ) is S.NegativeOne + assert minimum(cos(x)-sin(x), x, S.Reals) == -sqrt(2) + assert minimum(y, x, S.Reals) == y + assert minimum(x/sqrt(x**2+1), x, S.Reals) == -1 + + raises(ValueError, lambda : minimum(sin(x), x, S.EmptySet)) + raises(ValueError, lambda : minimum(log(cos(x)), x, S.EmptySet)) + raises(ValueError, lambda : minimum(1/(x**2 + y**2 + 1), x, S.EmptySet)) + raises(ValueError, lambda : minimum(sin(x), sin(x))) + raises(ValueError, lambda : minimum(sin(x), x*y, S.EmptySet)) + raises(ValueError, lambda : minimum(sin(x), S.One)) + + +def test_issue_19869(): + t = symbols('t') + assert (maximum(sqrt(3)*(t - 1)/(3*sqrt(t**2 + 1)), t) + ) == sqrt(3)/3 + + +def test_issue_16469(): + x = Symbol("x", real=True) + f = abs(x) + assert function_range(f, x, S.Reals) == Interval(0, oo, False, True) + + +@_both_exp_pow +def test_issue_18747(): + assert periodicity(exp(pi*I*(x/4+S.Half/2)), x) == 8 diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/calculus/util.py b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/util.py new file mode 100644 index 0000000000000000000000000000000000000000..e140396d8cd73bdcc769dc79366ad70c3e302715 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/calculus/util.py @@ -0,0 +1,841 @@ +from .accumulationbounds import AccumBounds, AccumulationBounds # noqa: F401 +from .singularities import singularities +from sympy.core import Pow, S +from sympy.core.function import diff, expand_mul +from sympy.core.kind import NumberKind +from sympy.core.mod import Mod +from sympy.core.numbers import equal_valued +from sympy.core.relational import Relational +from sympy.core.symbol import Symbol, Dummy +from sympy.core.sympify import _sympify +from sympy.functions.elementary.complexes import Abs, im, re +from sympy.functions.elementary.exponential import exp, log +from sympy.functions.elementary.piecewise import Piecewise +from sympy.functions.elementary.trigonometric import ( + TrigonometricFunction, sin, cos, csc, sec) +from sympy.polys.polytools import degree, lcm_list +from sympy.sets.sets import (Interval, Intersection, FiniteSet, Union, + Complement) +from sympy.sets.fancysets import ImageSet +from sympy.utilities import filldedent +from sympy.utilities.iterables import iterable + + +def continuous_domain(f, symbol, domain): + """ + Returns the intervals in the given domain for which the function + is continuous. + This method is limited by the ability to determine the various + singularities and discontinuities of the given function. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for which the intervals are to be determined. + domain : :py:class:`~.Interval` + The domain over which the continuity of the symbol has to be checked. + + Examples + ======== + + >>> from sympy import Interval, Symbol, S, tan, log, pi, sqrt + >>> from sympy.calculus.util import continuous_domain + >>> x = Symbol('x') + >>> continuous_domain(1/x, x, S.Reals) + Union(Interval.open(-oo, 0), Interval.open(0, oo)) + >>> continuous_domain(tan(x), x, Interval(0, pi)) + Union(Interval.Ropen(0, pi/2), Interval.Lopen(pi/2, pi)) + >>> continuous_domain(sqrt(x - 2), x, Interval(-5, 5)) + Interval(2, 5) + >>> continuous_domain(log(2*x - 1), x, S.Reals) + Interval.open(1/2, oo) + + Returns + ======= + + :py:class:`~.Interval` + Union of all intervals where the function is continuous. + + Raises + ====== + + NotImplementedError + If the method to determine continuity of such a function + has not yet been developed. + + """ + from sympy.solvers.inequalities import solve_univariate_inequality + + if domain.is_subset(S.Reals): + constrained_interval = domain + for atom in f.atoms(Pow): + den = atom.exp.as_numer_denom()[1] + if den.is_even and den.is_nonzero: + constraint = solve_univariate_inequality(atom.base >= 0, + symbol).as_set() + constrained_interval = Intersection(constraint, + constrained_interval) + + for atom in f.atoms(log): + constraint = solve_univariate_inequality(atom.args[0] > 0, + symbol).as_set() + constrained_interval = Intersection(constraint, + constrained_interval) + + + return constrained_interval - singularities(f, symbol, domain) + + +def function_range(f, symbol, domain): + """ + Finds the range of a function in a given domain. + This method is limited by the ability to determine the singularities and + determine limits. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for which the range of function is to be determined. + domain : :py:class:`~.Interval` + The domain under which the range of the function has to be found. + + Examples + ======== + + >>> from sympy import Interval, Symbol, S, exp, log, pi, sqrt, sin, tan + >>> from sympy.calculus.util import function_range + >>> x = Symbol('x') + >>> function_range(sin(x), x, Interval(0, 2*pi)) + Interval(-1, 1) + >>> function_range(tan(x), x, Interval(-pi/2, pi/2)) + Interval(-oo, oo) + >>> function_range(1/x, x, S.Reals) + Union(Interval.open(-oo, 0), Interval.open(0, oo)) + >>> function_range(exp(x), x, S.Reals) + Interval.open(0, oo) + >>> function_range(log(x), x, S.Reals) + Interval(-oo, oo) + >>> function_range(sqrt(x), x, Interval(-5, 9)) + Interval(0, 3) + + Returns + ======= + + :py:class:`~.Interval` + Union of all ranges for all intervals under domain where function is + continuous. + + Raises + ====== + + NotImplementedError + If any of the intervals, in the given domain, for which function + is continuous are not finite or real, + OR if the critical points of the function on the domain cannot be found. + """ + + if domain is S.EmptySet: + return S.EmptySet + + period = periodicity(f, symbol) + if period == S.Zero: + # the expression is constant wrt symbol + return FiniteSet(f.expand()) + + from sympy.series.limits import limit + from sympy.solvers.solveset import solveset + + if period is not None: + if isinstance(domain, Interval): + if (domain.inf - domain.sup).is_infinite: + domain = Interval(0, period) + elif isinstance(domain, Union): + for sub_dom in domain.args: + if isinstance(sub_dom, Interval) and \ + ((sub_dom.inf - sub_dom.sup).is_infinite): + domain = Interval(0, period) + + intervals = continuous_domain(f, symbol, domain) + range_int = S.EmptySet + if isinstance(intervals,(Interval, FiniteSet)): + interval_iter = (intervals,) + + elif isinstance(intervals, Union): + interval_iter = intervals.args + + else: + raise NotImplementedError(filldedent(''' + Unable to find range for the given domain. + ''')) + + for interval in interval_iter: + if isinstance(interval, FiniteSet): + for singleton in interval: + if singleton in domain: + range_int += FiniteSet(f.subs(symbol, singleton)) + elif isinstance(interval, Interval): + vals = S.EmptySet + critical_points = S.EmptySet + critical_values = S.EmptySet + bounds = ((interval.left_open, interval.inf, '+'), + (interval.right_open, interval.sup, '-')) + + for is_open, limit_point, direction in bounds: + if is_open: + critical_values += FiniteSet(limit(f, symbol, limit_point, direction)) + vals += critical_values + + else: + vals += FiniteSet(f.subs(symbol, limit_point)) + + solution = solveset(f.diff(symbol), symbol, interval) + + if not iterable(solution): + raise NotImplementedError( + 'Unable to find critical points for {}'.format(f)) + if isinstance(solution, ImageSet): + raise NotImplementedError( + 'Infinite number of critical points for {}'.format(f)) + + critical_points += solution + + for critical_point in critical_points: + vals += FiniteSet(f.subs(symbol, critical_point)) + + left_open, right_open = False, False + + if critical_values is not S.EmptySet: + if critical_values.inf == vals.inf: + left_open = True + + if critical_values.sup == vals.sup: + right_open = True + + range_int += Interval(vals.inf, vals.sup, left_open, right_open) + else: + raise NotImplementedError(filldedent(''' + Unable to find range for the given domain. + ''')) + + return range_int + + +def not_empty_in(finset_intersection, *syms): + """ + Finds the domain of the functions in ``finset_intersection`` in which the + ``finite_set`` is not-empty. + + Parameters + ========== + + finset_intersection : Intersection of FiniteSet + The unevaluated intersection of FiniteSet containing + real-valued functions with Union of Sets + syms : Tuple of symbols + Symbol for which domain is to be found + + Raises + ====== + + NotImplementedError + The algorithms to find the non-emptiness of the given FiniteSet are + not yet implemented. + ValueError + The input is not valid. + RuntimeError + It is a bug, please report it to the github issue tracker + (https://github.com/sympy/sympy/issues). + + Examples + ======== + + >>> from sympy import FiniteSet, Interval, not_empty_in, oo + >>> from sympy.abc import x + >>> not_empty_in(FiniteSet(x/2).intersect(Interval(0, 1)), x) + Interval(0, 2) + >>> not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) + Union(Interval(1, 2), Interval(-sqrt(2), -1)) + >>> not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) + Union(Interval.Lopen(-2, -1), Interval(2, oo)) + """ + + # TODO: handle piecewise defined functions + # TODO: handle transcendental functions + # TODO: handle multivariate functions + if len(syms) == 0: + raise ValueError("One or more symbols must be given in syms.") + + if finset_intersection is S.EmptySet: + return S.EmptySet + + if isinstance(finset_intersection, Union): + elm_in_sets = finset_intersection.args[0] + return Union(not_empty_in(finset_intersection.args[1], *syms), + elm_in_sets) + + if isinstance(finset_intersection, FiniteSet): + finite_set = finset_intersection + _sets = S.Reals + else: + finite_set = finset_intersection.args[1] + _sets = finset_intersection.args[0] + + if not isinstance(finite_set, FiniteSet): + raise ValueError('A FiniteSet must be given, not %s: %s' % + (type(finite_set), finite_set)) + + if len(syms) == 1: + symb = syms[0] + else: + raise NotImplementedError('more than one variables %s not handled' % + (syms,)) + + def elm_domain(expr, intrvl): + """ Finds the domain of an expression in any given interval """ + from sympy.solvers.solveset import solveset + + _start = intrvl.start + _end = intrvl.end + _singularities = solveset(expr.as_numer_denom()[1], symb, + domain=S.Reals) + + if intrvl.right_open: + if _end is S.Infinity: + _domain1 = S.Reals + else: + _domain1 = solveset(expr < _end, symb, domain=S.Reals) + else: + _domain1 = solveset(expr <= _end, symb, domain=S.Reals) + + if intrvl.left_open: + if _start is S.NegativeInfinity: + _domain2 = S.Reals + else: + _domain2 = solveset(expr > _start, symb, domain=S.Reals) + else: + _domain2 = solveset(expr >= _start, symb, domain=S.Reals) + + # domain in the interval + expr_with_sing = Intersection(_domain1, _domain2) + expr_domain = Complement(expr_with_sing, _singularities) + return expr_domain + + if isinstance(_sets, Interval): + return Union(*[elm_domain(element, _sets) for element in finite_set]) + + if isinstance(_sets, Union): + _domain = S.EmptySet + for intrvl in _sets.args: + _domain_element = Union(*[elm_domain(element, intrvl) + for element in finite_set]) + _domain = Union(_domain, _domain_element) + return _domain + + +def periodicity(f, symbol, check=False): + """ + Tests the given function for periodicity in the given symbol. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for which the period is to be determined. + check : bool, optional + The flag to verify whether the value being returned is a period or not. + + Returns + ======= + + period + The period of the function is returned. + ``None`` is returned when the function is aperiodic or has a complex period. + The value of $0$ is returned as the period of a constant function. + + Raises + ====== + + NotImplementedError + The value of the period computed cannot be verified. + + + Notes + ===== + + Currently, we do not support functions with a complex period. + The period of functions having complex periodic values such + as ``exp``, ``sinh`` is evaluated to ``None``. + + The value returned might not be the "fundamental" period of the given + function i.e. it may not be the smallest periodic value of the function. + + The verification of the period through the ``check`` flag is not reliable + due to internal simplification of the given expression. Hence, it is set + to ``False`` by default. + + Examples + ======== + >>> from sympy import periodicity, Symbol, sin, cos, tan, exp + >>> x = Symbol('x') + >>> f = sin(x) + sin(2*x) + sin(3*x) + >>> periodicity(f, x) + 2*pi + >>> periodicity(sin(x)*cos(x), x) + pi + >>> periodicity(exp(tan(2*x) - 1), x) + pi/2 + >>> periodicity(sin(4*x)**cos(2*x), x) + pi + >>> periodicity(exp(x), x) + """ + if symbol.kind is not NumberKind: + raise NotImplementedError("Cannot use symbol of kind %s" % symbol.kind) + temp = Dummy('x', real=True) + f = f.subs(symbol, temp) + symbol = temp + + def _check(orig_f, period): + '''Return the checked period or raise an error.''' + new_f = orig_f.subs(symbol, symbol + period) + if new_f.equals(orig_f): + return period + else: + raise NotImplementedError(filldedent(''' + The period of the given function cannot be verified. + When `%s` was replaced with `%s + %s` in `%s`, the result + was `%s` which was not recognized as being the same as + the original function. + So either the period was wrong or the two forms were + not recognized as being equal. + Set check=False to obtain the value.''' % + (symbol, symbol, period, orig_f, new_f))) + + orig_f = f + period = None + + if isinstance(f, Relational): + f = f.lhs - f.rhs + + f = f.simplify() + + if symbol not in f.free_symbols: + return S.Zero + + if isinstance(f, TrigonometricFunction): + try: + period = f.period(symbol) + except NotImplementedError: + pass + + if isinstance(f, Abs): + arg = f.args[0] + if isinstance(arg, (sec, csc, cos)): + # all but tan and cot might have a + # a period that is half as large + # so recast as sin + arg = sin(arg.args[0]) + period = periodicity(arg, symbol) + if period is not None and isinstance(arg, sin): + # the argument of Abs was a trigonometric other than + # cot or tan; test to see if the half-period + # is valid. Abs(arg) has behaviour equivalent to + # orig_f, so use that for test: + orig_f = Abs(arg) + try: + return _check(orig_f, period/2) + except NotImplementedError as err: + if check: + raise NotImplementedError(err) + # else let new orig_f and period be + # checked below + + if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1): + f = Pow(S.Exp1, expand_mul(f.exp)) + if im(f) != 0: + period_real = periodicity(re(f), symbol) + period_imag = periodicity(im(f), symbol) + if period_real is not None and period_imag is not None: + period = lcim([period_real, period_imag]) + + if f.is_Pow and f.base != S.Exp1: + base, expo = f.args + base_has_sym = base.has(symbol) + expo_has_sym = expo.has(symbol) + + if base_has_sym and not expo_has_sym: + period = periodicity(base, symbol) + + elif expo_has_sym and not base_has_sym: + period = periodicity(expo, symbol) + + else: + period = _periodicity(f.args, symbol) + + elif f.is_Mul: + coeff, g = f.as_independent(symbol, as_Add=False) + if isinstance(g, TrigonometricFunction) or not equal_valued(coeff, 1): + period = periodicity(g, symbol) + else: + period = _periodicity(g.args, symbol) + + elif f.is_Add: + k, g = f.as_independent(symbol) + if k is not S.Zero: + return periodicity(g, symbol) + + period = _periodicity(g.args, symbol) + + elif isinstance(f, Mod): + a, n = f.args + + if a == symbol: + period = n + elif isinstance(a, TrigonometricFunction): + period = periodicity(a, symbol) + #check if 'f' is linear in 'symbol' + elif (a.is_polynomial(symbol) and degree(a, symbol) == 1 and + symbol not in n.free_symbols): + period = Abs(n / a.diff(symbol)) + + elif isinstance(f, Piecewise): + pass # not handling Piecewise yet as the return type is not favorable + + elif period is None: + from sympy.solvers.decompogen import compogen, decompogen + g_s = decompogen(f, symbol) + num_of_gs = len(g_s) + if num_of_gs > 1: + for index, g in enumerate(reversed(g_s)): + start_index = num_of_gs - 1 - index + g = compogen(g_s[start_index:], symbol) + if g not in (orig_f, f): # Fix for issue 12620 + period = periodicity(g, symbol) + if period is not None: + break + + if period is not None: + if check: + return _check(orig_f, period) + return period + + return None + + +def _periodicity(args, symbol): + """ + Helper for `periodicity` to find the period of a list of simpler + functions. + It uses the `lcim` method to find the least common period of + all the functions. + + Parameters + ========== + + args : Tuple of :py:class:`~.Symbol` + All the symbols present in a function. + + symbol : :py:class:`~.Symbol` + The symbol over which the function is to be evaluated. + + Returns + ======= + + period + The least common period of the function for all the symbols + of the function. + ``None`` if for at least one of the symbols the function is aperiodic. + + """ + periods = [] + for f in args: + period = periodicity(f, symbol) + if period is None: + return None + + if period is not S.Zero: + periods.append(period) + + if len(periods) > 1: + return lcim(periods) + + if periods: + return periods[0] + + +def lcim(numbers): + """Returns the least common integral multiple of a list of numbers. + + The numbers can be rational or irrational or a mixture of both. + `None` is returned for incommensurable numbers. + + Parameters + ========== + + numbers : list + Numbers (rational and/or irrational) for which lcim is to be found. + + Returns + ======= + + number + lcim if it exists, otherwise ``None`` for incommensurable numbers. + + Examples + ======== + + >>> from sympy.calculus.util import lcim + >>> from sympy import S, pi + >>> lcim([S(1)/2, S(3)/4, S(5)/6]) + 15/2 + >>> lcim([2*pi, 3*pi, pi, pi/2]) + 6*pi + >>> lcim([S(1), 2*pi]) + """ + result = None + if all(num.is_irrational for num in numbers): + factorized_nums = [num.factor() for num in numbers] + factors_num = [num.as_coeff_Mul() for num in factorized_nums] + term = factors_num[0][1] + if all(factor == term for coeff, factor in factors_num): + common_term = term + coeffs = [coeff for coeff, factor in factors_num] + result = lcm_list(coeffs) * common_term + + elif all(num.is_rational for num in numbers): + result = lcm_list(numbers) + + else: + pass + + return result + +def is_convex(f, *syms, domain=S.Reals): + r"""Determines the convexity of the function passed in the argument. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + syms : Tuple of :py:class:`~.Symbol` + The variables with respect to which the convexity is to be determined. + domain : :py:class:`~.Interval`, optional + The domain over which the convexity of the function has to be checked. + If unspecified, S.Reals will be the default domain. + + Returns + ======= + + bool + The method returns ``True`` if the function is convex otherwise it + returns ``False``. + + Raises + ====== + + NotImplementedError + The check for the convexity of multivariate functions is not implemented yet. + + Notes + ===== + + To determine concavity of a function pass `-f` as the concerned function. + To determine logarithmic convexity of a function pass `\log(f)` as + concerned function. + To determine logarithmic concavity of a function pass `-\log(f)` as + concerned function. + + Currently, convexity check of multivariate functions is not handled. + + Examples + ======== + + >>> from sympy import is_convex, symbols, exp, oo, Interval + >>> x = symbols('x') + >>> is_convex(exp(x), x) + True + >>> is_convex(x**3, x, domain = Interval(-1, oo)) + False + >>> is_convex(1/x**2, x, domain=Interval.open(0, oo)) + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Convex_function + .. [2] http://www.ifp.illinois.edu/~angelia/L3_convfunc.pdf + .. [3] https://en.wikipedia.org/wiki/Logarithmically_convex_function + .. [4] https://en.wikipedia.org/wiki/Logarithmically_concave_function + .. [5] https://en.wikipedia.org/wiki/Concave_function + + """ + + if len(syms) > 1: + raise NotImplementedError( + "The check for the convexity of multivariate functions is not implemented yet.") + + from sympy.solvers.inequalities import solve_univariate_inequality + + f = _sympify(f) + var = syms[0] + if any(s in domain for s in singularities(f, var)): + return False + + condition = f.diff(var, 2) < 0 + if solve_univariate_inequality(condition, var, False, domain): + return False + return True + + +def stationary_points(f, symbol, domain=S.Reals): + """ + Returns the stationary points of a function (where derivative of the + function is 0) in the given domain. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for which the stationary points are to be determined. + domain : :py:class:`~.Interval` + The domain over which the stationary points have to be checked. + If unspecified, ``S.Reals`` will be the default domain. + + Returns + ======= + + Set + A set of stationary points for the function. If there are no + stationary point, an :py:class:`~.EmptySet` is returned. + + Examples + ======== + + >>> from sympy import Interval, Symbol, S, sin, pi, pprint, stationary_points + >>> x = Symbol('x') + + >>> stationary_points(1/x, x, S.Reals) + EmptySet + + >>> pprint(stationary_points(sin(x), x), use_unicode=False) + pi 3*pi + {2*n*pi + -- | n in Integers} U {2*n*pi + ---- | n in Integers} + 2 2 + + >>> stationary_points(sin(x),x, Interval(0, 4*pi)) + {pi/2, 3*pi/2, 5*pi/2, 7*pi/2} + + """ + from sympy.solvers.solveset import solveset + + if domain is S.EmptySet: + return S.EmptySet + + domain = continuous_domain(f, symbol, domain) + set = solveset(diff(f, symbol), symbol, domain) + + return set + + +def maximum(f, symbol, domain=S.Reals): + """ + Returns the maximum value of a function in the given domain. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for maximum value needs to be determined. + domain : :py:class:`~.Interval` + The domain over which the maximum have to be checked. + If unspecified, then the global maximum is returned. + + Returns + ======= + + number + Maximum value of the function in given domain. + + Examples + ======== + + >>> from sympy import Interval, Symbol, S, sin, cos, pi, maximum + >>> x = Symbol('x') + + >>> f = -x**2 + 2*x + 5 + >>> maximum(f, x, S.Reals) + 6 + + >>> maximum(sin(x), x, Interval(-pi, pi/4)) + sqrt(2)/2 + + >>> maximum(sin(x)*cos(x), x) + 1/2 + + """ + if isinstance(symbol, Symbol): + if domain is S.EmptySet: + raise ValueError("Maximum value not defined for empty domain.") + + return function_range(f, symbol, domain).sup + else: + raise ValueError("%s is not a valid symbol." % symbol) + + +def minimum(f, symbol, domain=S.Reals): + """ + Returns the minimum value of a function in the given domain. + + Parameters + ========== + + f : :py:class:`~.Expr` + The concerned function. + symbol : :py:class:`~.Symbol` + The variable for minimum value needs to be determined. + domain : :py:class:`~.Interval` + The domain over which the minimum have to be checked. + If unspecified, then the global minimum is returned. + + Returns + ======= + + number + Minimum value of the function in the given domain. + + Examples + ======== + + >>> from sympy import Interval, Symbol, S, sin, cos, minimum + >>> x = Symbol('x') + + >>> f = x**2 + 2*x + 5 + >>> minimum(f, x, S.Reals) + 4 + + >>> minimum(sin(x), x, Interval(2, 3)) + sin(3) + + >>> minimum(sin(x)*cos(x), x) + -1/2 + + """ + if isinstance(symbol, Symbol): + if domain is S.EmptySet: + raise ValueError("Minimum value not defined for empty domain.") + + return function_range(f, symbol, domain).inf + else: + raise ValueError("%s is not a valid symbol." % symbol) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/graycode.py b/env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/graycode.py new file mode 100644 index 0000000000000000000000000000000000000000..930fd337862a70e920a985947d74375b27741293 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/graycode.py @@ -0,0 +1,430 @@ +from sympy.core import Basic, Integer + +import random + + +class GrayCode(Basic): + """ + A Gray code is essentially a Hamiltonian walk on + a n-dimensional cube with edge length of one. + The vertices of the cube are represented by vectors + whose values are binary. The Hamilton walk visits + each vertex exactly once. The Gray code for a 3d + cube is ['000','100','110','010','011','111','101', + '001']. + + A Gray code solves the problem of sequentially + generating all possible subsets of n objects in such + a way that each subset is obtained from the previous + one by either deleting or adding a single object. + In the above example, 1 indicates that the object is + present, and 0 indicates that its absent. + + Gray codes have applications in statistics as well when + we want to compute various statistics related to subsets + in an efficient manner. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(3) + >>> list(a.generate_gray()) + ['000', '001', '011', '010', '110', '111', '101', '100'] + >>> a = GrayCode(4) + >>> list(a.generate_gray()) + ['0000', '0001', '0011', '0010', '0110', '0111', '0101', '0100', \ + '1100', '1101', '1111', '1110', '1010', '1011', '1001', '1000'] + + References + ========== + + .. [1] Nijenhuis,A. and Wilf,H.S.(1978). + Combinatorial Algorithms. Academic Press. + .. [2] Knuth, D. (2011). The Art of Computer Programming, Vol 4 + Addison Wesley + + + """ + + _skip = False + _current = 0 + _rank = None + + def __new__(cls, n, *args, **kw_args): + """ + Default constructor. + + It takes a single argument ``n`` which gives the dimension of the Gray + code. The starting Gray code string (``start``) or the starting ``rank`` + may also be given; the default is to start at rank = 0 ('0...0'). + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(3) + >>> a + GrayCode(3) + >>> a.n + 3 + + >>> a = GrayCode(3, start='100') + >>> a.current + '100' + + >>> a = GrayCode(4, rank=4) + >>> a.current + '0110' + >>> a.rank + 4 + + """ + if n < 1 or int(n) != n: + raise ValueError( + 'Gray code dimension must be a positive integer, not %i' % n) + n = Integer(n) + args = (n,) + args + obj = Basic.__new__(cls, *args) + if 'start' in kw_args: + obj._current = kw_args["start"] + if len(obj._current) > n: + raise ValueError('Gray code start has length %i but ' + 'should not be greater than %i' % (len(obj._current), n)) + elif 'rank' in kw_args: + if int(kw_args["rank"]) != kw_args["rank"]: + raise ValueError('Gray code rank must be a positive integer, ' + 'not %i' % kw_args["rank"]) + obj._rank = int(kw_args["rank"]) % obj.selections + obj._current = obj.unrank(n, obj._rank) + return obj + + def next(self, delta=1): + """ + Returns the Gray code a distance ``delta`` (default = 1) from the + current value in canonical order. + + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(3, start='110') + >>> a.next().current + '111' + >>> a.next(-1).current + '010' + """ + return GrayCode(self.n, rank=(self.rank + delta) % self.selections) + + @property + def selections(self): + """ + Returns the number of bit vectors in the Gray code. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(3) + >>> a.selections + 8 + """ + return 2**self.n + + @property + def n(self): + """ + Returns the dimension of the Gray code. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(5) + >>> a.n + 5 + """ + return self.args[0] + + def generate_gray(self, **hints): + """ + Generates the sequence of bit vectors of a Gray Code. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(3) + >>> list(a.generate_gray()) + ['000', '001', '011', '010', '110', '111', '101', '100'] + >>> list(a.generate_gray(start='011')) + ['011', '010', '110', '111', '101', '100'] + >>> list(a.generate_gray(rank=4)) + ['110', '111', '101', '100'] + + See Also + ======== + + skip + + References + ========== + + .. [1] Knuth, D. (2011). The Art of Computer Programming, + Vol 4, Addison Wesley + + """ + bits = self.n + start = None + if "start" in hints: + start = hints["start"] + elif "rank" in hints: + start = GrayCode.unrank(self.n, hints["rank"]) + if start is not None: + self._current = start + current = self.current + graycode_bin = gray_to_bin(current) + if len(graycode_bin) > self.n: + raise ValueError('Gray code start has length %i but should ' + 'not be greater than %i' % (len(graycode_bin), bits)) + self._current = int(current, 2) + graycode_int = int(''.join(graycode_bin), 2) + for i in range(graycode_int, 1 << bits): + if self._skip: + self._skip = False + else: + yield self.current + bbtc = (i ^ (i + 1)) + gbtc = (bbtc ^ (bbtc >> 1)) + self._current = (self._current ^ gbtc) + self._current = 0 + + def skip(self): + """ + Skips the bit generation. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(3) + >>> for i in a.generate_gray(): + ... if i == '010': + ... a.skip() + ... print(i) + ... + 000 + 001 + 011 + 010 + 111 + 101 + 100 + + See Also + ======== + + generate_gray + """ + self._skip = True + + @property + def rank(self): + """ + Ranks the Gray code. + + A ranking algorithm determines the position (or rank) + of a combinatorial object among all the objects w.r.t. + a given order. For example, the 4 bit binary reflected + Gray code (BRGC) '0101' has a rank of 6 as it appears in + the 6th position in the canonical ordering of the family + of 4 bit Gray codes. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> a = GrayCode(3) + >>> list(a.generate_gray()) + ['000', '001', '011', '010', '110', '111', '101', '100'] + >>> GrayCode(3, start='100').rank + 7 + >>> GrayCode(3, rank=7).current + '100' + + See Also + ======== + + unrank + + References + ========== + + .. [1] https://web.archive.org/web/20200224064753/http://statweb.stanford.edu/~susan/courses/s208/node12.html + + """ + if self._rank is None: + self._rank = int(gray_to_bin(self.current), 2) + return self._rank + + @property + def current(self): + """ + Returns the currently referenced Gray code as a bit string. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> GrayCode(3, start='100').current + '100' + """ + rv = self._current or '0' + if not isinstance(rv, str): + rv = bin(rv)[2:] + return rv.rjust(self.n, '0') + + @classmethod + def unrank(self, n, rank): + """ + Unranks an n-bit sized Gray code of rank k. This method exists + so that a derivative GrayCode class can define its own code of + a given rank. + + The string here is generated in reverse order to allow for tail-call + optimization. + + Examples + ======== + + >>> from sympy.combinatorics import GrayCode + >>> GrayCode(5, rank=3).current + '00010' + >>> GrayCode.unrank(5, 3) + '00010' + + See Also + ======== + + rank + """ + def _unrank(k, n): + if n == 1: + return str(k % 2) + m = 2**(n - 1) + if k < m: + return '0' + _unrank(k, n - 1) + return '1' + _unrank(m - (k % m) - 1, n - 1) + return _unrank(rank, n) + + +def random_bitstring(n): + """ + Generates a random bitlist of length n. + + Examples + ======== + + >>> from sympy.combinatorics.graycode import random_bitstring + >>> random_bitstring(3) # doctest: +SKIP + 100 + """ + return ''.join([random.choice('01') for i in range(n)]) + + +def gray_to_bin(bin_list): + """ + Convert from Gray coding to binary coding. + + We assume big endian encoding. + + Examples + ======== + + >>> from sympy.combinatorics.graycode import gray_to_bin + >>> gray_to_bin('100') + '111' + + See Also + ======== + + bin_to_gray + """ + b = [bin_list[0]] + for i in range(1, len(bin_list)): + b += str(int(b[i - 1] != bin_list[i])) + return ''.join(b) + + +def bin_to_gray(bin_list): + """ + Convert from binary coding to gray coding. + + We assume big endian encoding. + + Examples + ======== + + >>> from sympy.combinatorics.graycode import bin_to_gray + >>> bin_to_gray('111') + '100' + + See Also + ======== + + gray_to_bin + """ + b = [bin_list[0]] + for i in range(1, len(bin_list)): + b += str(int(bin_list[i]) ^ int(bin_list[i - 1])) + return ''.join(b) + + +def get_subset_from_bitstring(super_set, bitstring): + """ + Gets the subset defined by the bitstring. + + Examples + ======== + + >>> from sympy.combinatorics.graycode import get_subset_from_bitstring + >>> get_subset_from_bitstring(['a', 'b', 'c', 'd'], '0011') + ['c', 'd'] + >>> get_subset_from_bitstring(['c', 'a', 'c', 'c'], '1100') + ['c', 'a'] + + See Also + ======== + + graycode_subsets + """ + if len(super_set) != len(bitstring): + raise ValueError("The sizes of the lists are not equal") + return [super_set[i] for i, j in enumerate(bitstring) + if bitstring[i] == '1'] + + +def graycode_subsets(gray_code_set): + """ + Generates the subsets as enumerated by a Gray code. + + Examples + ======== + + >>> from sympy.combinatorics.graycode import graycode_subsets + >>> list(graycode_subsets(['a', 'b', 'c'])) + [[], ['c'], ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], \ + ['a', 'c'], ['a']] + >>> list(graycode_subsets(['a', 'b', 'c', 'c'])) + [[], ['c'], ['c', 'c'], ['c'], ['b', 'c'], ['b', 'c', 'c'], \ + ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'b', 'c', 'c'], \ + ['a', 'b', 'c'], ['a', 'c'], ['a', 'c', 'c'], ['a', 'c'], ['a']] + + See Also + ======== + + get_subset_from_bitstring + """ + for bitstring in list(GrayCode(len(gray_code_set)).generate_gray()): + yield get_subset_from_bitstring(gray_code_set, bitstring) diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/partitions.py b/env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/partitions.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe646baabbb5bf2350cba859a265ac32bbfaf53 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/partitions.py @@ -0,0 +1,745 @@ +from sympy.core import Basic, Dict, sympify, Tuple +from sympy.core.numbers import Integer +from sympy.core.sorting import default_sort_key +from sympy.core.sympify import _sympify +from sympy.functions.combinatorial.numbers import bell +from sympy.matrices import zeros +from sympy.sets.sets import FiniteSet, Union +from sympy.utilities.iterables import flatten, group +from sympy.utilities.misc import as_int + + +from collections import defaultdict + + +class Partition(FiniteSet): + """ + This class represents an abstract partition. + + A partition is a set of disjoint sets whose union equals a given set. + + See Also + ======== + + sympy.utilities.iterables.partitions, + sympy.utilities.iterables.multiset_partitions + """ + + _rank = None + _partition = None + + def __new__(cls, *partition): + """ + Generates a new partition object. + + This method also verifies if the arguments passed are + valid and raises a ValueError if they are not. + + Examples + ======== + + Creating Partition from Python lists: + + >>> from sympy.combinatorics import Partition + >>> a = Partition([1, 2], [3]) + >>> a + Partition({3}, {1, 2}) + >>> a.partition + [[1, 2], [3]] + >>> len(a) + 2 + >>> a.members + (1, 2, 3) + + Creating Partition from Python sets: + + >>> Partition({1, 2, 3}, {4, 5}) + Partition({4, 5}, {1, 2, 3}) + + Creating Partition from SymPy finite sets: + + >>> from sympy import FiniteSet + >>> a = FiniteSet(1, 2, 3) + >>> b = FiniteSet(4, 5) + >>> Partition(a, b) + Partition({4, 5}, {1, 2, 3}) + """ + args = [] + dups = False + for arg in partition: + if isinstance(arg, list): + as_set = set(arg) + if len(as_set) < len(arg): + dups = True + break # error below + arg = as_set + args.append(_sympify(arg)) + + if not all(isinstance(part, FiniteSet) for part in args): + raise ValueError( + "Each argument to Partition should be " \ + "a list, set, or a FiniteSet") + + # sort so we have a canonical reference for RGS + U = Union(*args) + if dups or len(U) < sum(len(arg) for arg in args): + raise ValueError("Partition contained duplicate elements.") + + obj = FiniteSet.__new__(cls, *args) + obj.members = tuple(U) + obj.size = len(U) + return obj + + def sort_key(self, order=None): + """Return a canonical key that can be used for sorting. + + Ordering is based on the size and sorted elements of the partition + and ties are broken with the rank. + + Examples + ======== + + >>> from sympy import default_sort_key + >>> from sympy.combinatorics import Partition + >>> from sympy.abc import x + >>> a = Partition([1, 2]) + >>> b = Partition([3, 4]) + >>> c = Partition([1, x]) + >>> d = Partition(list(range(4))) + >>> l = [d, b, a + 1, a, c] + >>> l.sort(key=default_sort_key); l + [Partition({1, 2}), Partition({1}, {2}), Partition({1, x}), Partition({3, 4}), Partition({0, 1, 2, 3})] + """ + if order is None: + members = self.members + else: + members = tuple(sorted(self.members, + key=lambda w: default_sort_key(w, order))) + return tuple(map(default_sort_key, (self.size, members, self.rank))) + + @property + def partition(self): + """Return partition as a sorted list of lists. + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> Partition([1], [2, 3]).partition + [[1], [2, 3]] + """ + if self._partition is None: + self._partition = sorted([sorted(p, key=default_sort_key) + for p in self.args]) + return self._partition + + def __add__(self, other): + """ + Return permutation whose rank is ``other`` greater than current rank, + (mod the maximum rank for the set). + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> a = Partition([1, 2], [3]) + >>> a.rank + 1 + >>> (a + 1).rank + 2 + >>> (a + 100).rank + 1 + """ + other = as_int(other) + offset = self.rank + other + result = RGS_unrank((offset) % + RGS_enum(self.size), + self.size) + return Partition.from_rgs(result, self.members) + + def __sub__(self, other): + """ + Return permutation whose rank is ``other`` less than current rank, + (mod the maximum rank for the set). + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> a = Partition([1, 2], [3]) + >>> a.rank + 1 + >>> (a - 1).rank + 0 + >>> (a - 100).rank + 1 + """ + return self.__add__(-other) + + def __le__(self, other): + """ + Checks if a partition is less than or equal to + the other based on rank. + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> a = Partition([1, 2], [3, 4, 5]) + >>> b = Partition([1], [2, 3], [4], [5]) + >>> a.rank, b.rank + (9, 34) + >>> a <= a + True + >>> a <= b + True + """ + return self.sort_key() <= sympify(other).sort_key() + + def __lt__(self, other): + """ + Checks if a partition is less than the other. + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> a = Partition([1, 2], [3, 4, 5]) + >>> b = Partition([1], [2, 3], [4], [5]) + >>> a.rank, b.rank + (9, 34) + >>> a < b + True + """ + return self.sort_key() < sympify(other).sort_key() + + @property + def rank(self): + """ + Gets the rank of a partition. + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> a = Partition([1, 2], [3], [4, 5]) + >>> a.rank + 13 + """ + if self._rank is not None: + return self._rank + self._rank = RGS_rank(self.RGS) + return self._rank + + @property + def RGS(self): + """ + Returns the "restricted growth string" of the partition. + + Explanation + =========== + + The RGS is returned as a list of indices, L, where L[i] indicates + the block in which element i appears. For example, in a partition + of 3 elements (a, b, c) into 2 blocks ([c], [a, b]) the RGS is + [1, 1, 0]: "a" is in block 1, "b" is in block 1 and "c" is in block 0. + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> a = Partition([1, 2], [3], [4, 5]) + >>> a.members + (1, 2, 3, 4, 5) + >>> a.RGS + (0, 0, 1, 2, 2) + >>> a + 1 + Partition({3}, {4}, {5}, {1, 2}) + >>> _.RGS + (0, 0, 1, 2, 3) + """ + rgs = {} + partition = self.partition + for i, part in enumerate(partition): + for j in part: + rgs[j] = i + return tuple([rgs[i] for i in sorted( + [i for p in partition for i in p], key=default_sort_key)]) + + @classmethod + def from_rgs(self, rgs, elements): + """ + Creates a set partition from a restricted growth string. + + Explanation + =========== + + The indices given in rgs are assumed to be the index + of the element as given in elements *as provided* (the + elements are not sorted by this routine). Block numbering + starts from 0. If any block was not referenced in ``rgs`` + an error will be raised. + + Examples + ======== + + >>> from sympy.combinatorics import Partition + >>> Partition.from_rgs([0, 1, 2, 0, 1], list('abcde')) + Partition({c}, {a, d}, {b, e}) + >>> Partition.from_rgs([0, 1, 2, 0, 1], list('cbead')) + Partition({e}, {a, c}, {b, d}) + >>> a = Partition([1, 4], [2], [3, 5]) + >>> Partition.from_rgs(a.RGS, a.members) + Partition({2}, {1, 4}, {3, 5}) + """ + if len(rgs) != len(elements): + raise ValueError('mismatch in rgs and element lengths') + max_elem = max(rgs) + 1 + partition = [[] for i in range(max_elem)] + j = 0 + for i in rgs: + partition[i].append(elements[j]) + j += 1 + if not all(p for p in partition): + raise ValueError('some blocks of the partition were empty.') + return Partition(*partition) + + +class IntegerPartition(Basic): + """ + This class represents an integer partition. + + Explanation + =========== + + In number theory and combinatorics, a partition of a positive integer, + ``n``, also called an integer partition, is a way of writing ``n`` as a + list of positive integers that sum to n. Two partitions that differ only + in the order of summands are considered to be the same partition; if order + matters then the partitions are referred to as compositions. For example, + 4 has five partitions: [4], [3, 1], [2, 2], [2, 1, 1], and [1, 1, 1, 1]; + the compositions [1, 2, 1] and [1, 1, 2] are the same as partition + [2, 1, 1]. + + See Also + ======== + + sympy.utilities.iterables.partitions, + sympy.utilities.iterables.multiset_partitions + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Partition_%28number_theory%29 + """ + + _dict = None + _keys = None + + def __new__(cls, partition, integer=None): + """ + Generates a new IntegerPartition object from a list or dictionary. + + Explanation + =========== + + The partition can be given as a list of positive integers or a + dictionary of (integer, multiplicity) items. If the partition is + preceded by an integer an error will be raised if the partition + does not sum to that given integer. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> a = IntegerPartition([5, 4, 3, 1, 1]) + >>> a + IntegerPartition(14, (5, 4, 3, 1, 1)) + >>> print(a) + [5, 4, 3, 1, 1] + >>> IntegerPartition({1:3, 2:1}) + IntegerPartition(5, (2, 1, 1, 1)) + + If the value that the partition should sum to is given first, a check + will be made to see n error will be raised if there is a discrepancy: + + >>> IntegerPartition(10, [5, 4, 3, 1]) + Traceback (most recent call last): + ... + ValueError: The partition is not valid + + """ + if integer is not None: + integer, partition = partition, integer + if isinstance(partition, (dict, Dict)): + _ = [] + for k, v in sorted(partition.items(), reverse=True): + if not v: + continue + k, v = as_int(k), as_int(v) + _.extend([k]*v) + partition = tuple(_) + else: + partition = tuple(sorted(map(as_int, partition), reverse=True)) + sum_ok = False + if integer is None: + integer = sum(partition) + sum_ok = True + else: + integer = as_int(integer) + + if not sum_ok and sum(partition) != integer: + raise ValueError("Partition did not add to %s" % integer) + if any(i < 1 for i in partition): + raise ValueError("All integer summands must be greater than one") + + obj = Basic.__new__(cls, Integer(integer), Tuple(*partition)) + obj.partition = list(partition) + obj.integer = integer + return obj + + def prev_lex(self): + """Return the previous partition of the integer, n, in lexical order, + wrapping around to [1, ..., 1] if the partition is [n]. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> p = IntegerPartition([4]) + >>> print(p.prev_lex()) + [3, 1] + >>> p.partition > p.prev_lex().partition + True + """ + d = defaultdict(int) + d.update(self.as_dict()) + keys = self._keys + if keys == [1]: + return IntegerPartition({self.integer: 1}) + if keys[-1] != 1: + d[keys[-1]] -= 1 + if keys[-1] == 2: + d[1] = 2 + else: + d[keys[-1] - 1] = d[1] = 1 + else: + d[keys[-2]] -= 1 + left = d[1] + keys[-2] + new = keys[-2] + d[1] = 0 + while left: + new -= 1 + if left - new >= 0: + d[new] += left//new + left -= d[new]*new + return IntegerPartition(self.integer, d) + + def next_lex(self): + """Return the next partition of the integer, n, in lexical order, + wrapping around to [n] if the partition is [1, ..., 1]. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> p = IntegerPartition([3, 1]) + >>> print(p.next_lex()) + [4] + >>> p.partition < p.next_lex().partition + True + """ + d = defaultdict(int) + d.update(self.as_dict()) + key = self._keys + a = key[-1] + if a == self.integer: + d.clear() + d[1] = self.integer + elif a == 1: + if d[a] > 1: + d[a + 1] += 1 + d[a] -= 2 + else: + b = key[-2] + d[b + 1] += 1 + d[1] = (d[b] - 1)*b + d[b] = 0 + else: + if d[a] > 1: + if len(key) == 1: + d.clear() + d[a + 1] = 1 + d[1] = self.integer - a - 1 + else: + a1 = a + 1 + d[a1] += 1 + d[1] = d[a]*a - a1 + d[a] = 0 + else: + b = key[-2] + b1 = b + 1 + d[b1] += 1 + need = d[b]*b + d[a]*a - b1 + d[a] = d[b] = 0 + d[1] = need + return IntegerPartition(self.integer, d) + + def as_dict(self): + """Return the partition as a dictionary whose keys are the + partition integers and the values are the multiplicity of that + integer. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> IntegerPartition([1]*3 + [2] + [3]*4).as_dict() + {1: 3, 2: 1, 3: 4} + """ + if self._dict is None: + groups = group(self.partition, multiple=False) + self._keys = [g[0] for g in groups] + self._dict = dict(groups) + return self._dict + + @property + def conjugate(self): + """ + Computes the conjugate partition of itself. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> a = IntegerPartition([6, 3, 3, 2, 1]) + >>> a.conjugate + [5, 4, 3, 1, 1, 1] + """ + j = 1 + temp_arr = list(self.partition) + [0] + k = temp_arr[0] + b = [0]*k + while k > 0: + while k > temp_arr[j]: + b[k - 1] = j + k -= 1 + j += 1 + return b + + def __lt__(self, other): + """Return True if self is less than other when the partition + is listed from smallest to biggest. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> a = IntegerPartition([3, 1]) + >>> a < a + False + >>> b = a.next_lex() + >>> a < b + True + >>> a == b + False + """ + return list(reversed(self.partition)) < list(reversed(other.partition)) + + def __le__(self, other): + """Return True if self is less than other when the partition + is listed from smallest to biggest. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> a = IntegerPartition([4]) + >>> a <= a + True + """ + return list(reversed(self.partition)) <= list(reversed(other.partition)) + + def as_ferrers(self, char='#'): + """ + Prints the ferrer diagram of a partition. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import IntegerPartition + >>> print(IntegerPartition([1, 1, 5]).as_ferrers()) + ##### + # + # + """ + return "\n".join([char*i for i in self.partition]) + + def __str__(self): + return str(list(self.partition)) + + +def random_integer_partition(n, seed=None): + """ + Generates a random integer partition summing to ``n`` as a list + of reverse-sorted integers. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import random_integer_partition + + For the following, a seed is given so a known value can be shown; in + practice, the seed would not be given. + + >>> random_integer_partition(100, seed=[1, 1, 12, 1, 2, 1, 85, 1]) + [85, 12, 2, 1] + >>> random_integer_partition(10, seed=[1, 2, 3, 1, 5, 1]) + [5, 3, 1, 1] + >>> random_integer_partition(1) + [1] + """ + from sympy.core.random import _randint + + n = as_int(n) + if n < 1: + raise ValueError('n must be a positive integer') + + randint = _randint(seed) + + partition = [] + while (n > 0): + k = randint(1, n) + mult = randint(1, n//k) + partition.append((k, mult)) + n -= k*mult + partition.sort(reverse=True) + partition = flatten([[k]*m for k, m in partition]) + return partition + + +def RGS_generalized(m): + """ + Computes the m + 1 generalized unrestricted growth strings + and returns them as rows in matrix. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import RGS_generalized + >>> RGS_generalized(6) + Matrix([ + [ 1, 1, 1, 1, 1, 1, 1], + [ 1, 2, 3, 4, 5, 6, 0], + [ 2, 5, 10, 17, 26, 0, 0], + [ 5, 15, 37, 77, 0, 0, 0], + [ 15, 52, 151, 0, 0, 0, 0], + [ 52, 203, 0, 0, 0, 0, 0], + [203, 0, 0, 0, 0, 0, 0]]) + """ + d = zeros(m + 1) + for i in range(m + 1): + d[0, i] = 1 + + for i in range(1, m + 1): + for j in range(m): + if j <= m - i: + d[i, j] = j * d[i - 1, j] + d[i - 1, j + 1] + else: + d[i, j] = 0 + return d + + +def RGS_enum(m): + """ + RGS_enum computes the total number of restricted growth strings + possible for a superset of size m. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import RGS_enum + >>> from sympy.combinatorics import Partition + >>> RGS_enum(4) + 15 + >>> RGS_enum(5) + 52 + >>> RGS_enum(6) + 203 + + We can check that the enumeration is correct by actually generating + the partitions. Here, the 15 partitions of 4 items are generated: + + >>> a = Partition(list(range(4))) + >>> s = set() + >>> for i in range(20): + ... s.add(a) + ... a += 1 + ... + >>> assert len(s) == 15 + + """ + if (m < 1): + return 0 + elif (m == 1): + return 1 + else: + return bell(m) + + +def RGS_unrank(rank, m): + """ + Gives the unranked restricted growth string for a given + superset size. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import RGS_unrank + >>> RGS_unrank(14, 4) + [0, 1, 2, 3] + >>> RGS_unrank(0, 4) + [0, 0, 0, 0] + """ + if m < 1: + raise ValueError("The superset size must be >= 1") + if rank < 0 or RGS_enum(m) <= rank: + raise ValueError("Invalid arguments") + + L = [1] * (m + 1) + j = 1 + D = RGS_generalized(m) + for i in range(2, m + 1): + v = D[m - i, j] + cr = j*v + if cr <= rank: + L[i] = j + 1 + rank -= cr + j += 1 + else: + L[i] = int(rank / v + 1) + rank %= v + return [x - 1 for x in L[1:]] + + +def RGS_rank(rgs): + """ + Computes the rank of a restricted growth string. + + Examples + ======== + + >>> from sympy.combinatorics.partitions import RGS_rank, RGS_unrank + >>> RGS_rank([0, 1, 2, 1, 3]) + 42 + >>> RGS_rank(RGS_unrank(4, 7)) + 4 + """ + rgs_size = len(rgs) + rank = 0 + D = RGS_generalized(rgs_size) + for i in range(1, rgs_size): + n = len(rgs[(i + 1):]) + m = max(rgs[0:i]) + rank += D[n, m + 1] * rgs[i] + return rank diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/pc_groups.py b/env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/pc_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..dbb4b0e442ec70d4c088fb51924fadc30cdf2fbf --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/pc_groups.py @@ -0,0 +1,709 @@ +from sympy.ntheory.primetest import isprime +from sympy.combinatorics.perm_groups import PermutationGroup +from sympy.printing.defaults import DefaultPrinting +from sympy.combinatorics.free_groups import free_group + + +class PolycyclicGroup(DefaultPrinting): + + is_group = True + is_solvable = True + + def __init__(self, pc_sequence, pc_series, relative_order, collector=None): + """ + + Parameters + ========== + + pc_sequence : list + A sequence of elements whose classes generate the cyclic factor + groups of pc_series. + pc_series : list + A subnormal sequence of subgroups where each factor group is cyclic. + relative_order : list + The orders of factor groups of pc_series. + collector : Collector + By default, it is None. Collector class provides the + polycyclic presentation with various other functionalities. + + """ + self.pcgs = pc_sequence + self.pc_series = pc_series + self.relative_order = relative_order + self.collector = Collector(self.pcgs, pc_series, relative_order) if not collector else collector + + def is_prime_order(self): + return all(isprime(order) for order in self.relative_order) + + def length(self): + return len(self.pcgs) + + +class Collector(DefaultPrinting): + + """ + References + ========== + + .. [1] Holt, D., Eick, B., O'Brien, E. + "Handbook of Computational Group Theory" + Section 8.1.3 + """ + + def __init__(self, pcgs, pc_series, relative_order, free_group_=None, pc_presentation=None): + """ + + Most of the parameters for the Collector class are the same as for PolycyclicGroup. + Others are described below. + + Parameters + ========== + + free_group_ : tuple + free_group_ provides the mapping of polycyclic generating + sequence with the free group elements. + pc_presentation : dict + Provides the presentation of polycyclic groups with the + help of power and conjugate relators. + + See Also + ======== + + PolycyclicGroup + + """ + self.pcgs = pcgs + self.pc_series = pc_series + self.relative_order = relative_order + self.free_group = free_group('x:{}'.format(len(pcgs)))[0] if not free_group_ else free_group_ + self.index = {s: i for i, s in enumerate(self.free_group.symbols)} + self.pc_presentation = self.pc_relators() + + def minimal_uncollected_subword(self, word): + r""" + Returns the minimal uncollected subwords. + + Explanation + =========== + + A word ``v`` defined on generators in ``X`` is a minimal + uncollected subword of the word ``w`` if ``v`` is a subword + of ``w`` and it has one of the following form + + * `v = {x_{i+1}}^{a_j}x_i` + + * `v = {x_{i+1}}^{a_j}{x_i}^{-1}` + + * `v = {x_i}^{a_j}` + + for `a_j` not in `\{1, \ldots, s-1\}`. Where, ``s`` is the power + exponent of the corresponding generator. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> from sympy.combinatorics import free_group + >>> G = SymmetricGroup(4) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> F, x1, x2 = free_group("x1, x2") + >>> word = x2**2*x1**7 + >>> collector.minimal_uncollected_subword(word) + ((x2, 2),) + + """ + # To handle the case word = + if not word: + return None + + array = word.array_form + re = self.relative_order + index = self.index + + for i in range(len(array)): + s1, e1 = array[i] + + if re[index[s1]] and (e1 < 0 or e1 > re[index[s1]]-1): + return ((s1, e1), ) + + for i in range(len(array)-1): + s1, e1 = array[i] + s2, e2 = array[i+1] + + if index[s1] > index[s2]: + e = 1 if e2 > 0 else -1 + return ((s1, e1), (s2, e)) + + return None + + def relations(self): + """ + Separates the given relators of pc presentation in power and + conjugate relations. + + Returns + ======= + + (power_rel, conj_rel) + Separates pc presentation into power and conjugate relations. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> G = SymmetricGroup(3) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> power_rel, conj_rel = collector.relations() + >>> power_rel + {x0**2: (), x1**3: ()} + >>> conj_rel + {x0**-1*x1*x0: x1**2} + + See Also + ======== + + pc_relators + + """ + power_relators = {} + conjugate_relators = {} + for key, value in self.pc_presentation.items(): + if len(key.array_form) == 1: + power_relators[key] = value + else: + conjugate_relators[key] = value + return power_relators, conjugate_relators + + def subword_index(self, word, w): + """ + Returns the start and ending index of a given + subword in a word. + + Parameters + ========== + + word : FreeGroupElement + word defined on free group elements for a + polycyclic group. + w : FreeGroupElement + subword of a given word, whose starting and + ending index to be computed. + + Returns + ======= + + (i, j) + A tuple containing starting and ending index of ``w`` + in the given word. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> from sympy.combinatorics import free_group + >>> G = SymmetricGroup(4) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> F, x1, x2 = free_group("x1, x2") + >>> word = x2**2*x1**7 + >>> w = x2**2*x1 + >>> collector.subword_index(word, w) + (0, 3) + >>> w = x1**7 + >>> collector.subword_index(word, w) + (2, 9) + + """ + low = -1 + high = -1 + for i in range(len(word)-len(w)+1): + if word.subword(i, i+len(w)) == w: + low = i + high = i+len(w) + break + if low == high == -1: + return -1, -1 + return low, high + + def map_relation(self, w): + """ + Return a conjugate relation. + + Explanation + =========== + + Given a word formed by two free group elements, the + corresponding conjugate relation with those free + group elements is formed and mapped with the collected + word in the polycyclic presentation. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> from sympy.combinatorics import free_group + >>> G = SymmetricGroup(3) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> F, x0, x1 = free_group("x0, x1") + >>> w = x1*x0 + >>> collector.map_relation(w) + x1**2 + + See Also + ======== + + pc_presentation + + """ + array = w.array_form + s1 = array[0][0] + s2 = array[1][0] + key = ((s2, -1), (s1, 1), (s2, 1)) + key = self.free_group.dtype(key) + return self.pc_presentation[key] + + + def collected_word(self, word): + r""" + Return the collected form of a word. + + Explanation + =========== + + A word ``w`` is called collected, if `w = {x_{i_1}}^{a_1} * \ldots * + {x_{i_r}}^{a_r}` with `i_1 < i_2< \ldots < i_r` and `a_j` is in + `\{1, \ldots, {s_j}-1\}`. + + Otherwise w is uncollected. + + Parameters + ========== + + word : FreeGroupElement + An uncollected word. + + Returns + ======= + + word + A collected word of form `w = {x_{i_1}}^{a_1}, \ldots, + {x_{i_r}}^{a_r}` with `i_1, i_2, \ldots, i_r` and `a_j \in + \{1, \ldots, {s_j}-1\}`. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> from sympy.combinatorics.perm_groups import PermutationGroup + >>> from sympy.combinatorics import free_group + >>> G = SymmetricGroup(4) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> F, x0, x1, x2, x3 = free_group("x0, x1, x2, x3") + >>> word = x3*x2*x1*x0 + >>> collected_word = collector.collected_word(word) + >>> free_to_perm = {} + >>> free_group = collector.free_group + >>> for sym, gen in zip(free_group.symbols, collector.pcgs): + ... free_to_perm[sym] = gen + >>> G1 = PermutationGroup() + >>> for w in word: + ... sym = w[0] + ... perm = free_to_perm[sym] + ... G1 = PermutationGroup([perm] + G1.generators) + >>> G2 = PermutationGroup() + >>> for w in collected_word: + ... sym = w[0] + ... perm = free_to_perm[sym] + ... G2 = PermutationGroup([perm] + G2.generators) + + The two are not identical, but they are equivalent: + + >>> G1.equals(G2), G1 == G2 + (True, False) + + See Also + ======== + + minimal_uncollected_subword + + """ + free_group = self.free_group + while True: + w = self.minimal_uncollected_subword(word) + if not w: + break + + low, high = self.subword_index(word, free_group.dtype(w)) + if low == -1: + continue + + s1, e1 = w[0] + if len(w) == 1: + re = self.relative_order[self.index[s1]] + q = e1 // re + r = e1-q*re + + key = ((w[0][0], re), ) + key = free_group.dtype(key) + if self.pc_presentation[key]: + presentation = self.pc_presentation[key].array_form + sym, exp = presentation[0] + word_ = ((w[0][0], r), (sym, q*exp)) + word_ = free_group.dtype(word_) + else: + if r != 0: + word_ = ((w[0][0], r), ) + word_ = free_group.dtype(word_) + else: + word_ = None + word = word.eliminate_word(free_group.dtype(w), word_) + + if len(w) == 2 and w[1][1] > 0: + s2, e2 = w[1] + s2 = ((s2, 1), ) + s2 = free_group.dtype(s2) + word_ = self.map_relation(free_group.dtype(w)) + word_ = s2*word_**e1 + word_ = free_group.dtype(word_) + word = word.substituted_word(low, high, word_) + + elif len(w) == 2 and w[1][1] < 0: + s2, e2 = w[1] + s2 = ((s2, 1), ) + s2 = free_group.dtype(s2) + word_ = self.map_relation(free_group.dtype(w)) + word_ = s2**-1*word_**e1 + word_ = free_group.dtype(word_) + word = word.substituted_word(low, high, word_) + + return word + + + def pc_relators(self): + r""" + Return the polycyclic presentation. + + Explanation + =========== + + There are two types of relations used in polycyclic + presentation. + + * Power relations : Power relators are of the form `x_i^{re_i}`, + where `i \in \{0, \ldots, \mathrm{len(pcgs)}\}`, ``x`` represents polycyclic + generator and ``re`` is the corresponding relative order. + + * Conjugate relations : Conjugate relators are of the form `x_j^-1x_ix_j`, + where `j < i \in \{0, \ldots, \mathrm{len(pcgs)}\}`. + + Returns + ======= + + A dictionary with power and conjugate relations as key and + their collected form as corresponding values. + + Notes + ===== + + Identity Permutation is mapped with empty ``()``. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> from sympy.combinatorics.permutations import Permutation + >>> S = SymmetricGroup(49).sylow_subgroup(7) + >>> der = S.derived_series() + >>> G = der[len(der)-2] + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> pcgs = PcGroup.pcgs + >>> len(pcgs) + 6 + >>> free_group = collector.free_group + >>> pc_resentation = collector.pc_presentation + >>> free_to_perm = {} + >>> for s, g in zip(free_group.symbols, pcgs): + ... free_to_perm[s] = g + + >>> for k, v in pc_resentation.items(): + ... k_array = k.array_form + ... if v != (): + ... v_array = v.array_form + ... lhs = Permutation() + ... for gen in k_array: + ... s = gen[0] + ... e = gen[1] + ... lhs = lhs*free_to_perm[s]**e + ... if v == (): + ... assert lhs.is_identity + ... continue + ... rhs = Permutation() + ... for gen in v_array: + ... s = gen[0] + ... e = gen[1] + ... rhs = rhs*free_to_perm[s]**e + ... assert lhs == rhs + + """ + free_group = self.free_group + rel_order = self.relative_order + pc_relators = {} + perm_to_free = {} + pcgs = self.pcgs + + for gen, s in zip(pcgs, free_group.generators): + perm_to_free[gen**-1] = s**-1 + perm_to_free[gen] = s + + pcgs = pcgs[::-1] + series = self.pc_series[::-1] + rel_order = rel_order[::-1] + collected_gens = [] + + for i, gen in enumerate(pcgs): + re = rel_order[i] + relation = perm_to_free[gen]**re + G = series[i] + + l = G.generator_product(gen**re, original = True) + l.reverse() + + word = free_group.identity + for g in l: + word = word*perm_to_free[g] + + word = self.collected_word(word) + pc_relators[relation] = word if word else () + self.pc_presentation = pc_relators + + collected_gens.append(gen) + if len(collected_gens) > 1: + conj = collected_gens[len(collected_gens)-1] + conjugator = perm_to_free[conj] + + for j in range(len(collected_gens)-1): + conjugated = perm_to_free[collected_gens[j]] + + relation = conjugator**-1*conjugated*conjugator + gens = conj**-1*collected_gens[j]*conj + + l = G.generator_product(gens, original = True) + l.reverse() + word = free_group.identity + for g in l: + word = word*perm_to_free[g] + + word = self.collected_word(word) + pc_relators[relation] = word if word else () + self.pc_presentation = pc_relators + + return pc_relators + + def exponent_vector(self, element): + r""" + Return the exponent vector of length equal to the + length of polycyclic generating sequence. + + Explanation + =========== + + For a given generator/element ``g`` of the polycyclic group, + it can be represented as `g = {x_1}^{e_1}, \ldots, {x_n}^{e_n}`, + where `x_i` represents polycyclic generators and ``n`` is + the number of generators in the free_group equal to the length + of pcgs. + + Parameters + ========== + + element : Permutation + Generator of a polycyclic group. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> from sympy.combinatorics.permutations import Permutation + >>> G = SymmetricGroup(4) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> pcgs = PcGroup.pcgs + >>> collector.exponent_vector(G[0]) + [1, 0, 0, 0] + >>> exp = collector.exponent_vector(G[1]) + >>> g = Permutation() + >>> for i in range(len(exp)): + ... g = g*pcgs[i]**exp[i] if exp[i] else g + >>> assert g == G[1] + + References + ========== + + .. [1] Holt, D., Eick, B., O'Brien, E. + "Handbook of Computational Group Theory" + Section 8.1.1, Definition 8.4 + + """ + free_group = self.free_group + G = PermutationGroup() + for g in self.pcgs: + G = PermutationGroup([g] + G.generators) + gens = G.generator_product(element, original = True) + gens.reverse() + + perm_to_free = {} + for sym, g in zip(free_group.generators, self.pcgs): + perm_to_free[g**-1] = sym**-1 + perm_to_free[g] = sym + w = free_group.identity + for g in gens: + w = w*perm_to_free[g] + + word = self.collected_word(w) + + index = self.index + exp_vector = [0]*len(free_group) + word = word.array_form + for t in word: + exp_vector[index[t[0]]] = t[1] + return exp_vector + + def depth(self, element): + r""" + Return the depth of a given element. + + Explanation + =========== + + The depth of a given element ``g`` is defined by + `\mathrm{dep}[g] = i` if `e_1 = e_2 = \ldots = e_{i-1} = 0` + and `e_i != 0`, where ``e`` represents the exponent-vector. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> G = SymmetricGroup(3) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> collector.depth(G[0]) + 2 + >>> collector.depth(G[1]) + 1 + + References + ========== + + .. [1] Holt, D., Eick, B., O'Brien, E. + "Handbook of Computational Group Theory" + Section 8.1.1, Definition 8.5 + + """ + exp_vector = self.exponent_vector(element) + return next((i+1 for i, x in enumerate(exp_vector) if x), len(self.pcgs)+1) + + def leading_exponent(self, element): + r""" + Return the leading non-zero exponent. + + Explanation + =========== + + The leading exponent for a given element `g` is defined + by `\mathrm{leading\_exponent}[g]` `= e_i`, if `\mathrm{depth}[g] = i`. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> G = SymmetricGroup(3) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> collector.leading_exponent(G[1]) + 1 + + """ + exp_vector = self.exponent_vector(element) + depth = self.depth(element) + if depth != len(self.pcgs)+1: + return exp_vector[depth-1] + return None + + def _sift(self, z, g): + h = g + d = self.depth(h) + while d < len(self.pcgs) and z[d-1] != 1: + k = z[d-1] + e = self.leading_exponent(h)*(self.leading_exponent(k))**-1 + e = e % self.relative_order[d-1] + h = k**-e*h + d = self.depth(h) + return h + + def induced_pcgs(self, gens): + """ + + Parameters + ========== + + gens : list + A list of generators on which polycyclic subgroup + is to be defined. + + Examples + ======== + + >>> from sympy.combinatorics.named_groups import SymmetricGroup + >>> S = SymmetricGroup(8) + >>> G = S.sylow_subgroup(2) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> gens = [G[0], G[1]] + >>> ipcgs = collector.induced_pcgs(gens) + >>> [gen.order() for gen in ipcgs] + [2, 2, 2] + >>> G = S.sylow_subgroup(3) + >>> PcGroup = G.polycyclic_group() + >>> collector = PcGroup.collector + >>> gens = [G[0], G[1]] + >>> ipcgs = collector.induced_pcgs(gens) + >>> [gen.order() for gen in ipcgs] + [3] + + """ + z = [1]*len(self.pcgs) + G = gens + while G: + g = G.pop(0) + h = self._sift(z, g) + d = self.depth(h) + if d < len(self.pcgs): + for gen in z: + if gen != 1: + G.append(h**-1*gen**-1*h*gen) + z[d-1] = h; + z = [gen for gen in z if gen != 1] + return z + + def constructive_membership_test(self, ipcgs, g): + """ + Return the exponent vector for induced pcgs. + """ + e = [0]*len(ipcgs) + h = g + d = self.depth(h) + for i, gen in enumerate(ipcgs): + while self.depth(gen) == d: + f = self.leading_exponent(h)*self.leading_exponent(gen) + f = f % self.relative_order[d-1] + h = gen**(-f)*h + e[i] = f + d = self.depth(h) + if h == 1: + return e + return False diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/permutations.py b/env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/permutations.py new file mode 100644 index 0000000000000000000000000000000000000000..6c823720d4719483adfcfdfcce52ed157d2b755c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/permutations.py @@ -0,0 +1,3112 @@ +import random +from collections import defaultdict +from collections.abc import Iterable +from functools import reduce + +from sympy.core.parameters import global_parameters +from sympy.core.basic import Atom +from sympy.core.expr import Expr +from sympy.core.numbers import Integer +from sympy.core.sympify import _sympify +from sympy.matrices import zeros +from sympy.polys.polytools import lcm +from sympy.printing.repr import srepr +from sympy.utilities.iterables import (flatten, has_variety, minlex, + has_dups, runs, is_sequence) +from sympy.utilities.misc import as_int +from mpmath.libmp.libintmath import ifac +from sympy.multipledispatch import dispatch + +def _af_rmul(a, b): + """ + Return the product b*a; input and output are array forms. The ith value + is a[b[i]]. + + Examples + ======== + + >>> from sympy.combinatorics.permutations import _af_rmul, Permutation + + >>> a, b = [1, 0, 2], [0, 2, 1] + >>> _af_rmul(a, b) + [1, 2, 0] + >>> [a[b[i]] for i in range(3)] + [1, 2, 0] + + This handles the operands in reverse order compared to the ``*`` operator: + + >>> a = Permutation(a) + >>> b = Permutation(b) + >>> list(a*b) + [2, 0, 1] + >>> [b(a(i)) for i in range(3)] + [2, 0, 1] + + See Also + ======== + + rmul, _af_rmuln + """ + return [a[i] for i in b] + + +def _af_rmuln(*abc): + """ + Given [a, b, c, ...] return the product of ...*c*b*a using array forms. + The ith value is a[b[c[i]]]. + + Examples + ======== + + >>> from sympy.combinatorics.permutations import _af_rmul, Permutation + + >>> a, b = [1, 0, 2], [0, 2, 1] + >>> _af_rmul(a, b) + [1, 2, 0] + >>> [a[b[i]] for i in range(3)] + [1, 2, 0] + + This handles the operands in reverse order compared to the ``*`` operator: + + >>> a = Permutation(a); b = Permutation(b) + >>> list(a*b) + [2, 0, 1] + >>> [b(a(i)) for i in range(3)] + [2, 0, 1] + + See Also + ======== + + rmul, _af_rmul + """ + a = abc + m = len(a) + if m == 3: + p0, p1, p2 = a + return [p0[p1[i]] for i in p2] + if m == 4: + p0, p1, p2, p3 = a + return [p0[p1[p2[i]]] for i in p3] + if m == 5: + p0, p1, p2, p3, p4 = a + return [p0[p1[p2[p3[i]]]] for i in p4] + if m == 6: + p0, p1, p2, p3, p4, p5 = a + return [p0[p1[p2[p3[p4[i]]]]] for i in p5] + if m == 7: + p0, p1, p2, p3, p4, p5, p6 = a + return [p0[p1[p2[p3[p4[p5[i]]]]]] for i in p6] + if m == 8: + p0, p1, p2, p3, p4, p5, p6, p7 = a + return [p0[p1[p2[p3[p4[p5[p6[i]]]]]]] for i in p7] + if m == 1: + return a[0][:] + if m == 2: + a, b = a + return [a[i] for i in b] + if m == 0: + raise ValueError("String must not be empty") + p0 = _af_rmuln(*a[:m//2]) + p1 = _af_rmuln(*a[m//2:]) + return [p0[i] for i in p1] + + +def _af_parity(pi): + """ + Computes the parity of a permutation in array form. + + Explanation + =========== + + The parity of a permutation reflects the parity of the + number of inversions in the permutation, i.e., the + number of pairs of x and y such that x > y but p[x] < p[y]. + + Examples + ======== + + >>> from sympy.combinatorics.permutations import _af_parity + >>> _af_parity([0, 1, 2, 3]) + 0 + >>> _af_parity([3, 2, 0, 1]) + 1 + + See Also + ======== + + Permutation + """ + n = len(pi) + a = [0] * n + c = 0 + for j in range(n): + if a[j] == 0: + c += 1 + a[j] = 1 + i = j + while pi[i] != j: + i = pi[i] + a[i] = 1 + return (n - c) % 2 + + +def _af_invert(a): + """ + Finds the inverse, ~A, of a permutation, A, given in array form. + + Examples + ======== + + >>> from sympy.combinatorics.permutations import _af_invert, _af_rmul + >>> A = [1, 2, 0, 3] + >>> _af_invert(A) + [2, 0, 1, 3] + >>> _af_rmul(_, A) + [0, 1, 2, 3] + + See Also + ======== + + Permutation, __invert__ + """ + inv_form = [0] * len(a) + for i, ai in enumerate(a): + inv_form[ai] = i + return inv_form + + +def _af_pow(a, n): + """ + Routine for finding powers of a permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy.combinatorics.permutations import _af_pow + >>> p = Permutation([2, 0, 3, 1]) + >>> p.order() + 4 + >>> _af_pow(p._array_form, 4) + [0, 1, 2, 3] + """ + if n == 0: + return list(range(len(a))) + if n < 0: + return _af_pow(_af_invert(a), -n) + if n == 1: + return a[:] + elif n == 2: + b = [a[i] for i in a] + elif n == 3: + b = [a[a[i]] for i in a] + elif n == 4: + b = [a[a[a[i]]] for i in a] + else: + # use binary multiplication + b = list(range(len(a))) + while 1: + if n & 1: + b = [b[i] for i in a] + n -= 1 + if not n: + break + if n % 4 == 0: + a = [a[a[a[i]]] for i in a] + n = n // 4 + elif n % 2 == 0: + a = [a[i] for i in a] + n = n // 2 + return b + + +def _af_commutes_with(a, b): + """ + Checks if the two permutations with array forms + given by ``a`` and ``b`` commute. + + Examples + ======== + + >>> from sympy.combinatorics.permutations import _af_commutes_with + >>> _af_commutes_with([1, 2, 0], [0, 2, 1]) + False + + See Also + ======== + + Permutation, commutes_with + """ + return not any(a[b[i]] != b[a[i]] for i in range(len(a) - 1)) + + +class Cycle(dict): + """ + Wrapper around dict which provides the functionality of a disjoint cycle. + + Explanation + =========== + + A cycle shows the rule to use to move subsets of elements to obtain + a permutation. The Cycle class is more flexible than Permutation in + that 1) all elements need not be present in order to investigate how + multiple cycles act in sequence and 2) it can contain singletons: + + >>> from sympy.combinatorics.permutations import Perm, Cycle + + A Cycle will automatically parse a cycle given as a tuple on the rhs: + + >>> Cycle(1, 2)(2, 3) + (1 3 2) + + The identity cycle, Cycle(), can be used to start a product: + + >>> Cycle()(1, 2)(2, 3) + (1 3 2) + + The array form of a Cycle can be obtained by calling the list + method (or passing it to the list function) and all elements from + 0 will be shown: + + >>> a = Cycle(1, 2) + >>> a.list() + [0, 2, 1] + >>> list(a) + [0, 2, 1] + + If a larger (or smaller) range is desired use the list method and + provide the desired size -- but the Cycle cannot be truncated to + a size smaller than the largest element that is out of place: + + >>> b = Cycle(2, 4)(1, 2)(3, 1, 4)(1, 3) + >>> b.list() + [0, 2, 1, 3, 4] + >>> b.list(b.size + 1) + [0, 2, 1, 3, 4, 5] + >>> b.list(-1) + [0, 2, 1] + + Singletons are not shown when printing with one exception: the largest + element is always shown -- as a singleton if necessary: + + >>> Cycle(1, 4, 10)(4, 5) + (1 5 4 10) + >>> Cycle(1, 2)(4)(5)(10) + (1 2)(10) + + The array form can be used to instantiate a Permutation so other + properties of the permutation can be investigated: + + >>> Perm(Cycle(1, 2)(3, 4).list()).transpositions() + [(1, 2), (3, 4)] + + Notes + ===== + + The underlying structure of the Cycle is a dictionary and although + the __iter__ method has been redefined to give the array form of the + cycle, the underlying dictionary items are still available with the + such methods as items(): + + >>> list(Cycle(1, 2).items()) + [(1, 2), (2, 1)] + + See Also + ======== + + Permutation + """ + def __missing__(self, arg): + """Enter arg into dictionary and return arg.""" + return as_int(arg) + + def __iter__(self): + yield from self.list() + + def __call__(self, *other): + """Return product of cycles processed from R to L. + + Examples + ======== + + >>> from sympy.combinatorics import Cycle + >>> Cycle(1, 2)(2, 3) + (1 3 2) + + An instance of a Cycle will automatically parse list-like + objects and Permutations that are on the right. It is more + flexible than the Permutation in that all elements need not + be present: + + >>> a = Cycle(1, 2) + >>> a(2, 3) + (1 3 2) + >>> a(2, 3)(4, 5) + (1 3 2)(4 5) + + """ + rv = Cycle(*other) + for k, v in zip(list(self.keys()), [rv[self[k]] for k in self.keys()]): + rv[k] = v + return rv + + def list(self, size=None): + """Return the cycles as an explicit list starting from 0 up + to the greater of the largest value in the cycles and size. + + Truncation of trailing unmoved items will occur when size + is less than the maximum element in the cycle; if this is + desired, setting ``size=-1`` will guarantee such trimming. + + Examples + ======== + + >>> from sympy.combinatorics import Cycle + >>> p = Cycle(2, 3)(4, 5) + >>> p.list() + [0, 1, 3, 2, 5, 4] + >>> p.list(10) + [0, 1, 3, 2, 5, 4, 6, 7, 8, 9] + + Passing a length too small will trim trailing, unchanged elements + in the permutation: + + >>> Cycle(2, 4)(1, 2, 4).list(-1) + [0, 2, 1] + """ + if not self and size is None: + raise ValueError('must give size for empty Cycle') + if size is not None: + big = max([i for i in self.keys() if self[i] != i] + [0]) + size = max(size, big + 1) + else: + size = self.size + return [self[i] for i in range(size)] + + def __repr__(self): + """We want it to print as a Cycle, not as a dict. + + Examples + ======== + + >>> from sympy.combinatorics import Cycle + >>> Cycle(1, 2) + (1 2) + >>> print(_) + (1 2) + >>> list(Cycle(1, 2).items()) + [(1, 2), (2, 1)] + """ + if not self: + return 'Cycle()' + cycles = Permutation(self).cyclic_form + s = ''.join(str(tuple(c)) for c in cycles) + big = self.size - 1 + if not any(i == big for c in cycles for i in c): + s += '(%s)' % big + return 'Cycle%s' % s + + def __str__(self): + """We want it to be printed in a Cycle notation with no + comma in-between. + + Examples + ======== + + >>> from sympy.combinatorics import Cycle + >>> Cycle(1, 2) + (1 2) + >>> Cycle(1, 2, 4)(5, 6) + (1 2 4)(5 6) + """ + if not self: + return '()' + cycles = Permutation(self).cyclic_form + s = ''.join(str(tuple(c)) for c in cycles) + big = self.size - 1 + if not any(i == big for c in cycles for i in c): + s += '(%s)' % big + s = s.replace(',', '') + return s + + def __init__(self, *args): + """Load up a Cycle instance with the values for the cycle. + + Examples + ======== + + >>> from sympy.combinatorics import Cycle + >>> Cycle(1, 2, 6) + (1 2 6) + """ + + if not args: + return + if len(args) == 1: + if isinstance(args[0], Permutation): + for c in args[0].cyclic_form: + self.update(self(*c)) + return + elif isinstance(args[0], Cycle): + for k, v in args[0].items(): + self[k] = v + return + args = [as_int(a) for a in args] + if any(i < 0 for i in args): + raise ValueError('negative integers are not allowed in a cycle.') + if has_dups(args): + raise ValueError('All elements must be unique in a cycle.') + for i in range(-len(args), 0): + self[args[i]] = args[i + 1] + + @property + def size(self): + if not self: + return 0 + return max(self.keys()) + 1 + + def copy(self): + return Cycle(self) + + +class Permutation(Atom): + r""" + A permutation, alternatively known as an 'arrangement number' or 'ordering' + is an arrangement of the elements of an ordered list into a one-to-one + mapping with itself. The permutation of a given arrangement is given by + indicating the positions of the elements after re-arrangement [2]_. For + example, if one started with elements ``[x, y, a, b]`` (in that order) and + they were reordered as ``[x, y, b, a]`` then the permutation would be + ``[0, 1, 3, 2]``. Notice that (in SymPy) the first element is always referred + to as 0 and the permutation uses the indices of the elements in the + original ordering, not the elements ``(a, b, ...)`` themselves. + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + + Permutations Notation + ===================== + + Permutations are commonly represented in disjoint cycle or array forms. + + Array Notation and 2-line Form + ------------------------------------ + + In the 2-line form, the elements and their final positions are shown + as a matrix with 2 rows: + + [0 1 2 ... n-1] + [p(0) p(1) p(2) ... p(n-1)] + + Since the first line is always ``range(n)``, where n is the size of p, + it is sufficient to represent the permutation by the second line, + referred to as the "array form" of the permutation. This is entered + in brackets as the argument to the Permutation class: + + >>> p = Permutation([0, 2, 1]); p + Permutation([0, 2, 1]) + + Given i in range(p.size), the permutation maps i to i^p + + >>> [i^p for i in range(p.size)] + [0, 2, 1] + + The composite of two permutations p*q means first apply p, then q, so + i^(p*q) = (i^p)^q which is i^p^q according to Python precedence rules: + + >>> q = Permutation([2, 1, 0]) + >>> [i^p^q for i in range(3)] + [2, 0, 1] + >>> [i^(p*q) for i in range(3)] + [2, 0, 1] + + One can use also the notation p(i) = i^p, but then the composition + rule is (p*q)(i) = q(p(i)), not p(q(i)): + + >>> [(p*q)(i) for i in range(p.size)] + [2, 0, 1] + >>> [q(p(i)) for i in range(p.size)] + [2, 0, 1] + >>> [p(q(i)) for i in range(p.size)] + [1, 2, 0] + + Disjoint Cycle Notation + ----------------------- + + In disjoint cycle notation, only the elements that have shifted are + indicated. + + For example, [1, 3, 2, 0] can be represented as (0, 1, 3)(2). + This can be understood from the 2 line format of the given permutation. + In the 2-line form, + [0 1 2 3] + [1 3 2 0] + + The element in the 0th position is 1, so 0 -> 1. The element in the 1st + position is three, so 1 -> 3. And the element in the third position is again + 0, so 3 -> 0. Thus, 0 -> 1 -> 3 -> 0, and 2 -> 2. Thus, this can be represented + as 2 cycles: (0, 1, 3)(2). + In common notation, singular cycles are not explicitly written as they can be + inferred implicitly. + + Only the relative ordering of elements in a cycle matter: + + >>> Permutation(1,2,3) == Permutation(2,3,1) == Permutation(3,1,2) + True + + The disjoint cycle notation is convenient when representing + permutations that have several cycles in them: + + >>> Permutation(1, 2)(3, 5) == Permutation([[1, 2], [3, 5]]) + True + + It also provides some economy in entry when computing products of + permutations that are written in disjoint cycle notation: + + >>> Permutation(1, 2)(1, 3)(2, 3) + Permutation([0, 3, 2, 1]) + >>> _ == Permutation([[1, 2]])*Permutation([[1, 3]])*Permutation([[2, 3]]) + True + + Caution: when the cycles have common elements between them then the order + in which the permutations are applied matters. This module applies + the permutations from *left to right*. + + >>> Permutation(1, 2)(2, 3) == Permutation([(1, 2), (2, 3)]) + True + >>> Permutation(1, 2)(2, 3).list() + [0, 3, 1, 2] + + In the above case, (1,2) is computed before (2,3). + As 0 -> 0, 0 -> 0, element in position 0 is 0. + As 1 -> 2, 2 -> 3, element in position 1 is 3. + As 2 -> 1, 1 -> 1, element in position 2 is 1. + As 3 -> 3, 3 -> 2, element in position 3 is 2. + + If the first and second elements had been + swapped first, followed by the swapping of the second + and third, the result would have been [0, 2, 3, 1]. + If, you want to apply the cycles in the conventional + right to left order, call the function with arguments in reverse order + as demonstrated below: + + >>> Permutation([(1, 2), (2, 3)][::-1]).list() + [0, 2, 3, 1] + + Entering a singleton in a permutation is a way to indicate the size of the + permutation. The ``size`` keyword can also be used. + + Array-form entry: + + >>> Permutation([[1, 2], [9]]) + Permutation([0, 2, 1], size=10) + >>> Permutation([[1, 2]], size=10) + Permutation([0, 2, 1], size=10) + + Cyclic-form entry: + + >>> Permutation(1, 2, size=10) + Permutation([0, 2, 1], size=10) + >>> Permutation(9)(1, 2) + Permutation([0, 2, 1], size=10) + + Caution: no singleton containing an element larger than the largest + in any previous cycle can be entered. This is an important difference + in how Permutation and Cycle handle the ``__call__`` syntax. A singleton + argument at the start of a Permutation performs instantiation of the + Permutation and is permitted: + + >>> Permutation(5) + Permutation([], size=6) + + A singleton entered after instantiation is a call to the permutation + -- a function call -- and if the argument is out of range it will + trigger an error. For this reason, it is better to start the cycle + with the singleton: + + The following fails because there is no element 3: + + >>> Permutation(1, 2)(3) + Traceback (most recent call last): + ... + IndexError: list index out of range + + This is ok: only the call to an out of range singleton is prohibited; + otherwise the permutation autosizes: + + >>> Permutation(3)(1, 2) + Permutation([0, 2, 1, 3]) + >>> Permutation(1, 2)(3, 4) == Permutation(3, 4)(1, 2) + True + + + Equality testing + ---------------- + + The array forms must be the same in order for permutations to be equal: + + >>> Permutation([1, 0, 2, 3]) == Permutation([1, 0]) + False + + + Identity Permutation + -------------------- + + The identity permutation is a permutation in which no element is out of + place. It can be entered in a variety of ways. All the following create + an identity permutation of size 4: + + >>> I = Permutation([0, 1, 2, 3]) + >>> all(p == I for p in [ + ... Permutation(3), + ... Permutation(range(4)), + ... Permutation([], size=4), + ... Permutation(size=4)]) + True + + Watch out for entering the range *inside* a set of brackets (which is + cycle notation): + + >>> I == Permutation([range(4)]) + False + + + Permutation Printing + ==================== + + There are a few things to note about how Permutations are printed. + + .. deprecated:: 1.6 + + Configuring Permutation printing by setting + ``Permutation.print_cyclic`` is deprecated. Users should use the + ``perm_cyclic`` flag to the printers, as described below. + + 1) If you prefer one form (array or cycle) over another, you can set + ``init_printing`` with the ``perm_cyclic`` flag. + + >>> from sympy import init_printing + >>> p = Permutation(1, 2)(4, 5)(3, 4) + >>> p + Permutation([0, 2, 1, 4, 5, 3]) + + >>> init_printing(perm_cyclic=True, pretty_print=False) + >>> p + (1 2)(3 4 5) + + 2) Regardless of the setting, a list of elements in the array for cyclic + form can be obtained and either of those can be copied and supplied as + the argument to Permutation: + + >>> p.array_form + [0, 2, 1, 4, 5, 3] + >>> p.cyclic_form + [[1, 2], [3, 4, 5]] + >>> Permutation(_) == p + True + + 3) Printing is economical in that as little as possible is printed while + retaining all information about the size of the permutation: + + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> Permutation([1, 0, 2, 3]) + Permutation([1, 0, 2, 3]) + >>> Permutation([1, 0, 2, 3], size=20) + Permutation([1, 0], size=20) + >>> Permutation([1, 0, 2, 4, 3, 5, 6], size=20) + Permutation([1, 0, 2, 4, 3], size=20) + + >>> p = Permutation([1, 0, 2, 3]) + >>> init_printing(perm_cyclic=True, pretty_print=False) + >>> p + (3)(0 1) + >>> init_printing(perm_cyclic=False, pretty_print=False) + + The 2 was not printed but it is still there as can be seen with the + array_form and size methods: + + >>> p.array_form + [1, 0, 2, 3] + >>> p.size + 4 + + Short introduction to other methods + =================================== + + The permutation can act as a bijective function, telling what element is + located at a given position + + >>> q = Permutation([5, 2, 3, 4, 1, 0]) + >>> q.array_form[1] # the hard way + 2 + >>> q(1) # the easy way + 2 + >>> {i: q(i) for i in range(q.size)} # showing the bijection + {0: 5, 1: 2, 2: 3, 3: 4, 4: 1, 5: 0} + + The full cyclic form (including singletons) can be obtained: + + >>> p.full_cyclic_form + [[0, 1], [2], [3]] + + Any permutation can be factored into transpositions of pairs of elements: + + >>> Permutation([[1, 2], [3, 4, 5]]).transpositions() + [(1, 2), (3, 5), (3, 4)] + >>> Permutation.rmul(*[Permutation([ti], size=6) for ti in _]).cyclic_form + [[1, 2], [3, 4, 5]] + + The number of permutations on a set of n elements is given by n! and is + called the cardinality. + + >>> p.size + 4 + >>> p.cardinality + 24 + + A given permutation has a rank among all the possible permutations of the + same elements, but what that rank is depends on how the permutations are + enumerated. (There are a number of different methods of doing so.) The + lexicographic rank is given by the rank method and this rank is used to + increment a permutation with addition/subtraction: + + >>> p.rank() + 6 + >>> p + 1 + Permutation([1, 0, 3, 2]) + >>> p.next_lex() + Permutation([1, 0, 3, 2]) + >>> _.rank() + 7 + >>> p.unrank_lex(p.size, rank=7) + Permutation([1, 0, 3, 2]) + + The product of two permutations p and q is defined as their composition as + functions, (p*q)(i) = q(p(i)) [6]_. + + >>> p = Permutation([1, 0, 2, 3]) + >>> q = Permutation([2, 3, 1, 0]) + >>> list(q*p) + [2, 3, 0, 1] + >>> list(p*q) + [3, 2, 1, 0] + >>> [q(p(i)) for i in range(p.size)] + [3, 2, 1, 0] + + The permutation can be 'applied' to any list-like object, not only + Permutations: + + >>> p(['zero', 'one', 'four', 'two']) + ['one', 'zero', 'four', 'two'] + >>> p('zo42') + ['o', 'z', '4', '2'] + + If you have a list of arbitrary elements, the corresponding permutation + can be found with the from_sequence method: + + >>> Permutation.from_sequence('SymPy') + Permutation([1, 3, 2, 0, 4]) + + Checking if a Permutation is contained in a Group + ================================================= + + Generally if you have a group of permutations G on n symbols, and + you're checking if a permutation on less than n symbols is part + of that group, the check will fail. + + Here is an example for n=5 and we check if the cycle + (1,2,3) is in G: + + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=True, pretty_print=False) + >>> from sympy.combinatorics import Cycle, Permutation + >>> from sympy.combinatorics.perm_groups import PermutationGroup + >>> G = PermutationGroup(Cycle(2, 3)(4, 5), Cycle(1, 2, 3, 4, 5)) + >>> p1 = Permutation(Cycle(2, 5, 3)) + >>> p2 = Permutation(Cycle(1, 2, 3)) + >>> a1 = Permutation(Cycle(1, 2, 3).list(6)) + >>> a2 = Permutation(Cycle(1, 2, 3)(5)) + >>> a3 = Permutation(Cycle(1, 2, 3),size=6) + >>> for p in [p1,p2,a1,a2,a3]: p, G.contains(p) + ((2 5 3), True) + ((1 2 3), False) + ((5)(1 2 3), True) + ((5)(1 2 3), True) + ((5)(1 2 3), True) + + The check for p2 above will fail. + + Checking if p1 is in G works because SymPy knows + G is a group on 5 symbols, and p1 is also on 5 symbols + (its largest element is 5). + + For ``a1``, the ``.list(6)`` call will extend the permutation to 5 + symbols, so the test will work as well. In the case of ``a2`` the + permutation is being extended to 5 symbols by using a singleton, + and in the case of ``a3`` it's extended through the constructor + argument ``size=6``. + + There is another way to do this, which is to tell the ``contains`` + method that the number of symbols the group is on does not need to + match perfectly the number of symbols for the permutation: + + >>> G.contains(p2,strict=False) + True + + This can be via the ``strict`` argument to the ``contains`` method, + and SymPy will try to extend the permutation on its own and then + perform the containment check. + + See Also + ======== + + Cycle + + References + ========== + + .. [1] Skiena, S. 'Permutations.' 1.1 in Implementing Discrete Mathematics + Combinatorics and Graph Theory with Mathematica. Reading, MA: + Addison-Wesley, pp. 3-16, 1990. + + .. [2] Knuth, D. E. The Art of Computer Programming, Vol. 4: Combinatorial + Algorithms, 1st ed. Reading, MA: Addison-Wesley, 2011. + + .. [3] Wendy Myrvold and Frank Ruskey. 2001. Ranking and unranking + permutations in linear time. Inf. Process. Lett. 79, 6 (September 2001), + 281-284. DOI=10.1016/S0020-0190(01)00141-7 + + .. [4] D. L. Kreher, D. R. Stinson 'Combinatorial Algorithms' + CRC Press, 1999 + + .. [5] Graham, R. L.; Knuth, D. E.; and Patashnik, O. + Concrete Mathematics: A Foundation for Computer Science, 2nd ed. + Reading, MA: Addison-Wesley, 1994. + + .. [6] https://en.wikipedia.org/w/index.php?oldid=499948155#Product_and_inverse + + .. [7] https://en.wikipedia.org/wiki/Lehmer_code + + """ + + is_Permutation = True + + _array_form = None + _cyclic_form = None + _cycle_structure = None + _size = None + _rank = None + + def __new__(cls, *args, size=None, **kwargs): + """ + Constructor for the Permutation object from a list or a + list of lists in which all elements of the permutation may + appear only once. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + + Permutations entered in array-form are left unaltered: + + >>> Permutation([0, 2, 1]) + Permutation([0, 2, 1]) + + Permutations entered in cyclic form are converted to array form; + singletons need not be entered, but can be entered to indicate the + largest element: + + >>> Permutation([[4, 5, 6], [0, 1]]) + Permutation([1, 0, 2, 3, 5, 6, 4]) + >>> Permutation([[4, 5, 6], [0, 1], [19]]) + Permutation([1, 0, 2, 3, 5, 6, 4], size=20) + + All manipulation of permutations assumes that the smallest element + is 0 (in keeping with 0-based indexing in Python) so if the 0 is + missing when entering a permutation in array form, an error will be + raised: + + >>> Permutation([2, 1]) + Traceback (most recent call last): + ... + ValueError: Integers 0 through 2 must be present. + + If a permutation is entered in cyclic form, it can be entered without + singletons and the ``size`` specified so those values can be filled + in, otherwise the array form will only extend to the maximum value + in the cycles: + + >>> Permutation([[1, 4], [3, 5, 2]], size=10) + Permutation([0, 4, 3, 5, 1, 2], size=10) + >>> _.array_form + [0, 4, 3, 5, 1, 2, 6, 7, 8, 9] + """ + if size is not None: + size = int(size) + + #a) () + #b) (1) = identity + #c) (1, 2) = cycle + #d) ([1, 2, 3]) = array form + #e) ([[1, 2]]) = cyclic form + #f) (Cycle) = conversion to permutation + #g) (Permutation) = adjust size or return copy + ok = True + if not args: # a + return cls._af_new(list(range(size or 0))) + elif len(args) > 1: # c + return cls._af_new(Cycle(*args).list(size)) + if len(args) == 1: + a = args[0] + if isinstance(a, cls): # g + if size is None or size == a.size: + return a + return cls(a.array_form, size=size) + if isinstance(a, Cycle): # f + return cls._af_new(a.list(size)) + if not is_sequence(a): # b + if size is not None and a + 1 > size: + raise ValueError('size is too small when max is %s' % a) + return cls._af_new(list(range(a + 1))) + if has_variety(is_sequence(ai) for ai in a): + ok = False + else: + ok = False + if not ok: + raise ValueError("Permutation argument must be a list of ints, " + "a list of lists, Permutation or Cycle.") + + # safe to assume args are valid; this also makes a copy + # of the args + args = list(args[0]) + + is_cycle = args and is_sequence(args[0]) + if is_cycle: # e + args = [[int(i) for i in c] for c in args] + else: # d + args = [int(i) for i in args] + + # if there are n elements present, 0, 1, ..., n-1 should be present + # unless a cycle notation has been provided. A 0 will be added + # for convenience in case one wants to enter permutations where + # counting starts from 1. + + temp = flatten(args) + if has_dups(temp) and not is_cycle: + raise ValueError('there were repeated elements.') + temp = set(temp) + + if not is_cycle: + if temp != set(range(len(temp))): + raise ValueError('Integers 0 through %s must be present.' % + max(temp)) + if size is not None and temp and max(temp) + 1 > size: + raise ValueError('max element should not exceed %s' % (size - 1)) + + if is_cycle: + # it's not necessarily canonical so we won't store + # it -- use the array form instead + c = Cycle() + for ci in args: + c = c(*ci) + aform = c.list() + else: + aform = list(args) + if size and size > len(aform): + # don't allow for truncation of permutation which + # might split a cycle and lead to an invalid aform + # but do allow the permutation size to be increased + aform.extend(list(range(len(aform), size))) + + return cls._af_new(aform) + + @classmethod + def _af_new(cls, perm): + """A method to produce a Permutation object from a list; + the list is bound to the _array_form attribute, so it must + not be modified; this method is meant for internal use only; + the list ``a`` is supposed to be generated as a temporary value + in a method, so p = Perm._af_new(a) is the only object + to hold a reference to ``a``:: + + Examples + ======== + + >>> from sympy.combinatorics.permutations import Perm + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> a = [2, 1, 3, 0] + >>> p = Perm._af_new(a) + >>> p + Permutation([2, 1, 3, 0]) + + """ + p = super().__new__(cls) + p._array_form = perm + p._size = len(perm) + return p + + def _hashable_content(self): + # the array_form (a list) is the Permutation arg, so we need to + # return a tuple, instead + return tuple(self.array_form) + + @property + def array_form(self): + """ + Return a copy of the attribute _array_form + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([[2, 0], [3, 1]]) + >>> p.array_form + [2, 3, 0, 1] + >>> Permutation([[2, 0, 3, 1]]).array_form + [3, 2, 0, 1] + >>> Permutation([2, 0, 3, 1]).array_form + [2, 0, 3, 1] + >>> Permutation([[1, 2], [4, 5]]).array_form + [0, 2, 1, 3, 5, 4] + """ + return self._array_form[:] + + def list(self, size=None): + """Return the permutation as an explicit list, possibly + trimming unmoved elements if size is less than the maximum + element in the permutation; if this is desired, setting + ``size=-1`` will guarantee such trimming. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation(2, 3)(4, 5) + >>> p.list() + [0, 1, 3, 2, 5, 4] + >>> p.list(10) + [0, 1, 3, 2, 5, 4, 6, 7, 8, 9] + + Passing a length too small will trim trailing, unchanged elements + in the permutation: + + >>> Permutation(2, 4)(1, 2, 4).list(-1) + [0, 2, 1] + >>> Permutation(3).list(-1) + [] + """ + if not self and size is None: + raise ValueError('must give size for empty Cycle') + rv = self.array_form + if size is not None: + if size > self.size: + rv.extend(list(range(self.size, size))) + else: + # find first value from rhs where rv[i] != i + i = self.size - 1 + while rv: + if rv[-1] != i: + break + rv.pop() + i -= 1 + return rv + + @property + def cyclic_form(self): + """ + This is used to convert to the cyclic notation + from the canonical notation. Singletons are omitted. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 3, 1, 2]) + >>> p.cyclic_form + [[1, 3, 2]] + >>> Permutation([1, 0, 2, 4, 3, 5]).cyclic_form + [[0, 1], [3, 4]] + + See Also + ======== + + array_form, full_cyclic_form + """ + if self._cyclic_form is not None: + return list(self._cyclic_form) + array_form = self.array_form + unchecked = [True] * len(array_form) + cyclic_form = [] + for i in range(len(array_form)): + if unchecked[i]: + cycle = [] + cycle.append(i) + unchecked[i] = False + j = i + while unchecked[array_form[j]]: + j = array_form[j] + cycle.append(j) + unchecked[j] = False + if len(cycle) > 1: + cyclic_form.append(cycle) + assert cycle == list(minlex(cycle)) + cyclic_form.sort() + self._cyclic_form = cyclic_form[:] + return cyclic_form + + @property + def full_cyclic_form(self): + """Return permutation in cyclic form including singletons. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation([0, 2, 1]).full_cyclic_form + [[0], [1, 2]] + """ + need = set(range(self.size)) - set(flatten(self.cyclic_form)) + rv = self.cyclic_form + [[i] for i in need] + rv.sort() + return rv + + @property + def size(self): + """ + Returns the number of elements in the permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation([[3, 2], [0, 1]]).size + 4 + + See Also + ======== + + cardinality, length, order, rank + """ + return self._size + + def support(self): + """Return the elements in permutation, P, for which P[i] != i. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([[3, 2], [0, 1], [4]]) + >>> p.array_form + [1, 0, 3, 2, 4] + >>> p.support() + [0, 1, 2, 3] + """ + a = self.array_form + return [i for i, e in enumerate(a) if a[i] != i] + + def __add__(self, other): + """Return permutation that is other higher in rank than self. + + The rank is the lexicographical rank, with the identity permutation + having rank of 0. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> I = Permutation([0, 1, 2, 3]) + >>> a = Permutation([2, 1, 3, 0]) + >>> I + a.rank() == a + True + + See Also + ======== + + __sub__, inversion_vector + + """ + rank = (self.rank() + other) % self.cardinality + rv = self.unrank_lex(self.size, rank) + rv._rank = rank + return rv + + def __sub__(self, other): + """Return the permutation that is other lower in rank than self. + + See Also + ======== + + __add__ + """ + return self.__add__(-other) + + @staticmethod + def rmul(*args): + """ + Return product of Permutations [a, b, c, ...] as the Permutation whose + ith value is a(b(c(i))). + + a, b, c, ... can be Permutation objects or tuples. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + + >>> a, b = [1, 0, 2], [0, 2, 1] + >>> a = Permutation(a); b = Permutation(b) + >>> list(Permutation.rmul(a, b)) + [1, 2, 0] + >>> [a(b(i)) for i in range(3)] + [1, 2, 0] + + This handles the operands in reverse order compared to the ``*`` operator: + + >>> a = Permutation(a); b = Permutation(b) + >>> list(a*b) + [2, 0, 1] + >>> [b(a(i)) for i in range(3)] + [2, 0, 1] + + Notes + ===== + + All items in the sequence will be parsed by Permutation as + necessary as long as the first item is a Permutation: + + >>> Permutation.rmul(a, [0, 2, 1]) == Permutation.rmul(a, b) + True + + The reverse order of arguments will raise a TypeError. + + """ + rv = args[0] + for i in range(1, len(args)): + rv = args[i]*rv + return rv + + @classmethod + def rmul_with_af(cls, *args): + """ + same as rmul, but the elements of args are Permutation objects + which have _array_form + """ + a = [x._array_form for x in args] + rv = cls._af_new(_af_rmuln(*a)) + return rv + + def mul_inv(self, other): + """ + other*~self, self and other have _array_form + """ + a = _af_invert(self._array_form) + b = other._array_form + return self._af_new(_af_rmul(a, b)) + + def __rmul__(self, other): + """This is needed to coerce other to Permutation in rmul.""" + cls = type(self) + return cls(other)*self + + def __mul__(self, other): + """ + Return the product a*b as a Permutation; the ith value is b(a(i)). + + Examples + ======== + + >>> from sympy.combinatorics.permutations import _af_rmul, Permutation + + >>> a, b = [1, 0, 2], [0, 2, 1] + >>> a = Permutation(a); b = Permutation(b) + >>> list(a*b) + [2, 0, 1] + >>> [b(a(i)) for i in range(3)] + [2, 0, 1] + + This handles operands in reverse order compared to _af_rmul and rmul: + + >>> al = list(a); bl = list(b) + >>> _af_rmul(al, bl) + [1, 2, 0] + >>> [al[bl[i]] for i in range(3)] + [1, 2, 0] + + It is acceptable for the arrays to have different lengths; the shorter + one will be padded to match the longer one: + + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> b*Permutation([1, 0]) + Permutation([1, 2, 0]) + >>> Permutation([1, 0])*b + Permutation([2, 0, 1]) + + It is also acceptable to allow coercion to handle conversion of a + single list to the left of a Permutation: + + >>> [0, 1]*a # no change: 2-element identity + Permutation([1, 0, 2]) + >>> [[0, 1]]*a # exchange first two elements + Permutation([0, 1, 2]) + + You cannot use more than 1 cycle notation in a product of cycles + since coercion can only handle one argument to the left. To handle + multiple cycles it is convenient to use Cycle instead of Permutation: + + >>> [[1, 2]]*[[2, 3]]*Permutation([]) # doctest: +SKIP + >>> from sympy.combinatorics.permutations import Cycle + >>> Cycle(1, 2)(2, 3) + (1 3 2) + + """ + from sympy.combinatorics.perm_groups import PermutationGroup, Coset + if isinstance(other, PermutationGroup): + return Coset(self, other, dir='-') + a = self.array_form + # __rmul__ makes sure the other is a Permutation + b = other.array_form + if not b: + perm = a + else: + b.extend(list(range(len(b), len(a)))) + perm = [b[i] for i in a] + b[len(a):] + return self._af_new(perm) + + def commutes_with(self, other): + """ + Checks if the elements are commuting. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> a = Permutation([1, 4, 3, 0, 2, 5]) + >>> b = Permutation([0, 1, 2, 3, 4, 5]) + >>> a.commutes_with(b) + True + >>> b = Permutation([2, 3, 5, 4, 1, 0]) + >>> a.commutes_with(b) + False + """ + a = self.array_form + b = other.array_form + return _af_commutes_with(a, b) + + def __pow__(self, n): + """ + Routine for finding powers of a permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> p = Permutation([2, 0, 3, 1]) + >>> p.order() + 4 + >>> p**4 + Permutation([0, 1, 2, 3]) + """ + if isinstance(n, Permutation): + raise NotImplementedError( + 'p**p is not defined; do you mean p^p (conjugate)?') + n = int(n) + return self._af_new(_af_pow(self.array_form, n)) + + def __rxor__(self, i): + """Return self(i) when ``i`` is an int. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation(1, 2, 9) + >>> 2^p == p(2) == 9 + True + """ + if int(i) == i: + return self(i) + else: + raise NotImplementedError( + "i^p = p(i) when i is an integer, not %s." % i) + + def __xor__(self, h): + """Return the conjugate permutation ``~h*self*h` `. + + Explanation + =========== + + If ``a`` and ``b`` are conjugates, ``a = h*b*~h`` and + ``b = ~h*a*h`` and both have the same cycle structure. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation(1, 2, 9) + >>> q = Permutation(6, 9, 8) + >>> p*q != q*p + True + + Calculate and check properties of the conjugate: + + >>> c = p^q + >>> c == ~q*p*q and p == q*c*~q + True + + The expression q^p^r is equivalent to q^(p*r): + + >>> r = Permutation(9)(4, 6, 8) + >>> q^p^r == q^(p*r) + True + + If the term to the left of the conjugate operator, i, is an integer + then this is interpreted as selecting the ith element from the + permutation to the right: + + >>> all(i^p == p(i) for i in range(p.size)) + True + + Note that the * operator as higher precedence than the ^ operator: + + >>> q^r*p^r == q^(r*p)^r == Permutation(9)(1, 6, 4) + True + + Notes + ===== + + In Python the precedence rule is p^q^r = (p^q)^r which differs + in general from p^(q^r) + + >>> q^p^r + (9)(1 4 8) + >>> q^(p^r) + (9)(1 8 6) + + For a given r and p, both of the following are conjugates of p: + ~r*p*r and r*p*~r. But these are not necessarily the same: + + >>> ~r*p*r == r*p*~r + True + + >>> p = Permutation(1, 2, 9)(5, 6) + >>> ~r*p*r == r*p*~r + False + + The conjugate ~r*p*r was chosen so that ``p^q^r`` would be equivalent + to ``p^(q*r)`` rather than ``p^(r*q)``. To obtain r*p*~r, pass ~r to + this method: + + >>> p^~r == r*p*~r + True + """ + + if self.size != h.size: + raise ValueError("The permutations must be of equal size.") + a = [None]*self.size + h = h._array_form + p = self._array_form + for i in range(self.size): + a[h[i]] = h[p[i]] + return self._af_new(a) + + def transpositions(self): + """ + Return the permutation decomposed into a list of transpositions. + + Explanation + =========== + + It is always possible to express a permutation as the product of + transpositions, see [1] + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([[1, 2, 3], [0, 4, 5, 6, 7]]) + >>> t = p.transpositions() + >>> t + [(0, 7), (0, 6), (0, 5), (0, 4), (1, 3), (1, 2)] + >>> print(''.join(str(c) for c in t)) + (0, 7)(0, 6)(0, 5)(0, 4)(1, 3)(1, 2) + >>> Permutation.rmul(*[Permutation([ti], size=p.size) for ti in t]) == p + True + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Transposition_%28mathematics%29#Properties + + """ + a = self.cyclic_form + res = [] + for x in a: + nx = len(x) + if nx == 2: + res.append(tuple(x)) + elif nx > 2: + first = x[0] + for y in x[nx - 1:0:-1]: + res.append((first, y)) + return res + + @classmethod + def from_sequence(self, i, key=None): + """Return the permutation needed to obtain ``i`` from the sorted + elements of ``i``. If custom sorting is desired, a key can be given. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + + >>> Permutation.from_sequence('SymPy') + (4)(0 1 3) + >>> _(sorted("SymPy")) + ['S', 'y', 'm', 'P', 'y'] + >>> Permutation.from_sequence('SymPy', key=lambda x: x.lower()) + (4)(0 2)(1 3) + """ + ic = list(zip(i, list(range(len(i))))) + if key: + ic.sort(key=lambda x: key(x[0])) + else: + ic.sort() + return ~Permutation([i[1] for i in ic]) + + def __invert__(self): + """ + Return the inverse of the permutation. + + A permutation multiplied by its inverse is the identity permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> p = Permutation([[2, 0], [3, 1]]) + >>> ~p + Permutation([2, 3, 0, 1]) + >>> _ == p**-1 + True + >>> p*~p == ~p*p == Permutation([0, 1, 2, 3]) + True + """ + return self._af_new(_af_invert(self._array_form)) + + def __iter__(self): + """Yield elements from array form. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> list(Permutation(range(3))) + [0, 1, 2] + """ + yield from self.array_form + + def __repr__(self): + return srepr(self) + + def __call__(self, *i): + """ + Allows applying a permutation instance as a bijective function. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([[2, 0], [3, 1]]) + >>> p.array_form + [2, 3, 0, 1] + >>> [p(i) for i in range(4)] + [2, 3, 0, 1] + + If an array is given then the permutation selects the items + from the array (i.e. the permutation is applied to the array): + + >>> from sympy.abc import x + >>> p([x, 1, 0, x**2]) + [0, x**2, x, 1] + """ + # list indices can be Integer or int; leave this + # as it is (don't test or convert it) because this + # gets called a lot and should be fast + if len(i) == 1: + i = i[0] + if not isinstance(i, Iterable): + i = as_int(i) + if i < 0 or i > self.size: + raise TypeError( + "{} should be an integer between 0 and {}" + .format(i, self.size-1)) + return self._array_form[i] + # P([a, b, c]) + if len(i) != self.size: + raise TypeError( + "{} should have the length {}.".format(i, self.size)) + return [i[j] for j in self._array_form] + # P(1, 2, 3) + return self*Permutation(Cycle(*i), size=self.size) + + def atoms(self): + """ + Returns all the elements of a permutation + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation([0, 1, 2, 3, 4, 5]).atoms() + {0, 1, 2, 3, 4, 5} + >>> Permutation([[0, 1], [2, 3], [4, 5]]).atoms() + {0, 1, 2, 3, 4, 5} + """ + return set(self.array_form) + + def apply(self, i): + r"""Apply the permutation to an expression. + + Parameters + ========== + + i : Expr + It should be an integer between $0$ and $n-1$ where $n$ + is the size of the permutation. + + If it is a symbol or a symbolic expression that can + have integer values, an ``AppliedPermutation`` object + will be returned which can represent an unevaluated + function. + + Notes + ===== + + Any permutation can be defined as a bijective function + $\sigma : \{ 0, 1, \dots, n-1 \} \rightarrow \{ 0, 1, \dots, n-1 \}$ + where $n$ denotes the size of the permutation. + + The definition may even be extended for any set with distinctive + elements, such that the permutation can even be applied for + real numbers or such, however, it is not implemented for now for + computational reasons and the integrity with the group theory + module. + + This function is similar to the ``__call__`` magic, however, + ``__call__`` magic already has some other applications like + permuting an array or attaching new cycles, which would + not always be mathematically consistent. + + This also guarantees that the return type is a SymPy integer, + which guarantees the safety to use assumptions. + """ + i = _sympify(i) + if i.is_integer is False: + raise NotImplementedError("{} should be an integer.".format(i)) + + n = self.size + if (i < 0) == True or (i >= n) == True: + raise NotImplementedError( + "{} should be an integer between 0 and {}".format(i, n-1)) + + if i.is_Integer: + return Integer(self._array_form[i]) + return AppliedPermutation(self, i) + + def next_lex(self): + """ + Returns the next permutation in lexicographical order. + If self is the last permutation in lexicographical order + it returns None. + See [4] section 2.4. + + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([2, 3, 1, 0]) + >>> p = Permutation([2, 3, 1, 0]); p.rank() + 17 + >>> p = p.next_lex(); p.rank() + 18 + + See Also + ======== + + rank, unrank_lex + """ + perm = self.array_form[:] + n = len(perm) + i = n - 2 + while perm[i + 1] < perm[i]: + i -= 1 + if i == -1: + return None + else: + j = n - 1 + while perm[j] < perm[i]: + j -= 1 + perm[j], perm[i] = perm[i], perm[j] + i += 1 + j = n - 1 + while i < j: + perm[j], perm[i] = perm[i], perm[j] + i += 1 + j -= 1 + return self._af_new(perm) + + @classmethod + def unrank_nonlex(self, n, r): + """ + This is a linear time unranking algorithm that does not + respect lexicographic order [3]. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> Permutation.unrank_nonlex(4, 5) + Permutation([2, 0, 3, 1]) + >>> Permutation.unrank_nonlex(4, -1) + Permutation([0, 1, 2, 3]) + + See Also + ======== + + next_nonlex, rank_nonlex + """ + def _unrank1(n, r, a): + if n > 0: + a[n - 1], a[r % n] = a[r % n], a[n - 1] + _unrank1(n - 1, r//n, a) + + id_perm = list(range(n)) + n = int(n) + r = r % ifac(n) + _unrank1(n, r, id_perm) + return self._af_new(id_perm) + + def rank_nonlex(self, inv_perm=None): + """ + This is a linear time ranking algorithm that does not + enforce lexicographic order [3]. + + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3]) + >>> p.rank_nonlex() + 23 + + See Also + ======== + + next_nonlex, unrank_nonlex + """ + def _rank1(n, perm, inv_perm): + if n == 1: + return 0 + s = perm[n - 1] + t = inv_perm[n - 1] + perm[n - 1], perm[t] = perm[t], s + inv_perm[n - 1], inv_perm[s] = inv_perm[s], t + return s + n*_rank1(n - 1, perm, inv_perm) + + if inv_perm is None: + inv_perm = (~self).array_form + if not inv_perm: + return 0 + perm = self.array_form[:] + r = _rank1(len(perm), perm, inv_perm) + return r + + def next_nonlex(self): + """ + Returns the next permutation in nonlex order [3]. + If self is the last permutation in this order it returns None. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> p = Permutation([2, 0, 3, 1]); p.rank_nonlex() + 5 + >>> p = p.next_nonlex(); p + Permutation([3, 0, 1, 2]) + >>> p.rank_nonlex() + 6 + + See Also + ======== + + rank_nonlex, unrank_nonlex + """ + r = self.rank_nonlex() + if r == ifac(self.size) - 1: + return None + return self.unrank_nonlex(self.size, r + 1) + + def rank(self): + """ + Returns the lexicographic rank of the permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3]) + >>> p.rank() + 0 + >>> p = Permutation([3, 2, 1, 0]) + >>> p.rank() + 23 + + See Also + ======== + + next_lex, unrank_lex, cardinality, length, order, size + """ + if self._rank is not None: + return self._rank + rank = 0 + rho = self.array_form[:] + n = self.size - 1 + size = n + 1 + psize = int(ifac(n)) + for j in range(size - 1): + rank += rho[j]*psize + for i in range(j + 1, size): + if rho[i] > rho[j]: + rho[i] -= 1 + psize //= n + n -= 1 + self._rank = rank + return rank + + @property + def cardinality(self): + """ + Returns the number of all possible permutations. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3]) + >>> p.cardinality + 24 + + See Also + ======== + + length, order, rank, size + """ + return int(ifac(self.size)) + + def parity(self): + """ + Computes the parity of a permutation. + + Explanation + =========== + + The parity of a permutation reflects the parity of the + number of inversions in the permutation, i.e., the + number of pairs of x and y such that ``x > y`` but ``p[x] < p[y]``. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3]) + >>> p.parity() + 0 + >>> p = Permutation([3, 2, 0, 1]) + >>> p.parity() + 1 + + See Also + ======== + + _af_parity + """ + if self._cyclic_form is not None: + return (self.size - self.cycles) % 2 + + return _af_parity(self.array_form) + + @property + def is_even(self): + """ + Checks if a permutation is even. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3]) + >>> p.is_even + True + >>> p = Permutation([3, 2, 1, 0]) + >>> p.is_even + True + + See Also + ======== + + is_odd + """ + return not self.is_odd + + @property + def is_odd(self): + """ + Checks if a permutation is odd. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3]) + >>> p.is_odd + False + >>> p = Permutation([3, 2, 0, 1]) + >>> p.is_odd + True + + See Also + ======== + + is_even + """ + return bool(self.parity() % 2) + + @property + def is_Singleton(self): + """ + Checks to see if the permutation contains only one number and is + thus the only possible permutation of this set of numbers + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation([0]).is_Singleton + True + >>> Permutation([0, 1]).is_Singleton + False + + See Also + ======== + + is_Empty + """ + return self.size == 1 + + @property + def is_Empty(self): + """ + Checks to see if the permutation is a set with zero elements + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation([]).is_Empty + True + >>> Permutation([0]).is_Empty + False + + See Also + ======== + + is_Singleton + """ + return self.size == 0 + + @property + def is_identity(self): + return self.is_Identity + + @property + def is_Identity(self): + """ + Returns True if the Permutation is an identity permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([]) + >>> p.is_Identity + True + >>> p = Permutation([[0], [1], [2]]) + >>> p.is_Identity + True + >>> p = Permutation([0, 1, 2]) + >>> p.is_Identity + True + >>> p = Permutation([0, 2, 1]) + >>> p.is_Identity + False + + See Also + ======== + + order + """ + af = self.array_form + return not af or all(i == af[i] for i in range(self.size)) + + def ascents(self): + """ + Returns the positions of ascents in a permutation, ie, the location + where p[i] < p[i+1] + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([4, 0, 1, 3, 2]) + >>> p.ascents() + [1, 2] + + See Also + ======== + + descents, inversions, min, max + """ + a = self.array_form + pos = [i for i in range(len(a) - 1) if a[i] < a[i + 1]] + return pos + + def descents(self): + """ + Returns the positions of descents in a permutation, ie, the location + where p[i] > p[i+1] + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([4, 0, 1, 3, 2]) + >>> p.descents() + [0, 3] + + See Also + ======== + + ascents, inversions, min, max + """ + a = self.array_form + pos = [i for i in range(len(a) - 1) if a[i] > a[i + 1]] + return pos + + def max(self): + """ + The maximum element moved by the permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([1, 0, 2, 3, 4]) + >>> p.max() + 1 + + See Also + ======== + + min, descents, ascents, inversions + """ + max = 0 + a = self.array_form + for i in range(len(a)): + if a[i] != i and a[i] > max: + max = a[i] + return max + + def min(self): + """ + The minimum element moved by the permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 4, 3, 2]) + >>> p.min() + 2 + + See Also + ======== + + max, descents, ascents, inversions + """ + a = self.array_form + min = len(a) + for i in range(len(a)): + if a[i] != i and a[i] < min: + min = a[i] + return min + + def inversions(self): + """ + Computes the number of inversions of a permutation. + + Explanation + =========== + + An inversion is where i > j but p[i] < p[j]. + + For small length of p, it iterates over all i and j + values and calculates the number of inversions. + For large length of p, it uses a variation of merge + sort to calculate the number of inversions. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3, 4, 5]) + >>> p.inversions() + 0 + >>> Permutation([3, 2, 1, 0]).inversions() + 6 + + See Also + ======== + + descents, ascents, min, max + + References + ========== + + .. [1] https://www.cp.eng.chula.ac.th/~prabhas//teaching/algo/algo2008/count-inv.htm + + """ + inversions = 0 + a = self.array_form + n = len(a) + if n < 130: + for i in range(n - 1): + b = a[i] + for c in a[i + 1:]: + if b > c: + inversions += 1 + else: + k = 1 + right = 0 + arr = a[:] + temp = a[:] + while k < n: + i = 0 + while i + k < n: + right = i + k * 2 - 1 + if right >= n: + right = n - 1 + inversions += _merge(arr, temp, i, i + k, right) + i = i + k * 2 + k = k * 2 + return inversions + + def commutator(self, x): + """Return the commutator of ``self`` and ``x``: ``~x*~self*x*self`` + + If f and g are part of a group, G, then the commutator of f and g + is the group identity iff f and g commute, i.e. fg == gf. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> p = Permutation([0, 2, 3, 1]) + >>> x = Permutation([2, 0, 3, 1]) + >>> c = p.commutator(x); c + Permutation([2, 1, 3, 0]) + >>> c == ~x*~p*x*p + True + + >>> I = Permutation(3) + >>> p = [I + i for i in range(6)] + >>> for i in range(len(p)): + ... for j in range(len(p)): + ... c = p[i].commutator(p[j]) + ... if p[i]*p[j] == p[j]*p[i]: + ... assert c == I + ... else: + ... assert c != I + ... + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Commutator + """ + + a = self.array_form + b = x.array_form + n = len(a) + if len(b) != n: + raise ValueError("The permutations must be of equal size.") + inva = [None]*n + for i in range(n): + inva[a[i]] = i + invb = [None]*n + for i in range(n): + invb[b[i]] = i + return self._af_new([a[b[inva[i]]] for i in invb]) + + def signature(self): + """ + Gives the signature of the permutation needed to place the + elements of the permutation in canonical order. + + The signature is calculated as (-1)^ + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2]) + >>> p.inversions() + 0 + >>> p.signature() + 1 + >>> q = Permutation([0,2,1]) + >>> q.inversions() + 1 + >>> q.signature() + -1 + + See Also + ======== + + inversions + """ + if self.is_even: + return 1 + return -1 + + def order(self): + """ + Computes the order of a permutation. + + When the permutation is raised to the power of its + order it equals the identity permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> p = Permutation([3, 1, 5, 2, 4, 0]) + >>> p.order() + 4 + >>> (p**(p.order())) + Permutation([], size=6) + + See Also + ======== + + identity, cardinality, length, rank, size + """ + + return reduce(lcm, [len(cycle) for cycle in self.cyclic_form], 1) + + def length(self): + """ + Returns the number of integers moved by a permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation([0, 3, 2, 1]).length() + 2 + >>> Permutation([[0, 1], [2, 3]]).length() + 4 + + See Also + ======== + + min, max, support, cardinality, order, rank, size + """ + + return len(self.support()) + + @property + def cycle_structure(self): + """Return the cycle structure of the permutation as a dictionary + indicating the multiplicity of each cycle length. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation(3).cycle_structure + {1: 4} + >>> Permutation(0, 4, 3)(1, 2)(5, 6).cycle_structure + {2: 2, 3: 1} + """ + if self._cycle_structure: + rv = self._cycle_structure + else: + rv = defaultdict(int) + singletons = self.size + for c in self.cyclic_form: + rv[len(c)] += 1 + singletons -= len(c) + if singletons: + rv[1] = singletons + self._cycle_structure = rv + return dict(rv) # make a copy + + @property + def cycles(self): + """ + Returns the number of cycles contained in the permutation + (including singletons). + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation([0, 1, 2]).cycles + 3 + >>> Permutation([0, 1, 2]).full_cyclic_form + [[0], [1], [2]] + >>> Permutation(0, 1)(2, 3).cycles + 2 + + See Also + ======== + sympy.functions.combinatorial.numbers.stirling + """ + return len(self.full_cyclic_form) + + def index(self): + """ + Returns the index of a permutation. + + The index of a permutation is the sum of all subscripts j such + that p[j] is greater than p[j+1]. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([3, 0, 2, 1, 4]) + >>> p.index() + 2 + """ + a = self.array_form + + return sum([j for j in range(len(a) - 1) if a[j] > a[j + 1]]) + + def runs(self): + """ + Returns the runs of a permutation. + + An ascending sequence in a permutation is called a run [5]. + + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([2, 5, 7, 3, 6, 0, 1, 4, 8]) + >>> p.runs() + [[2, 5, 7], [3, 6], [0, 1, 4, 8]] + >>> q = Permutation([1,3,2,0]) + >>> q.runs() + [[1, 3], [2], [0]] + """ + return runs(self.array_form) + + def inversion_vector(self): + """Return the inversion vector of the permutation. + + The inversion vector consists of elements whose value + indicates the number of elements in the permutation + that are lesser than it and lie on its right hand side. + + The inversion vector is the same as the Lehmer encoding of a + permutation. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([4, 8, 0, 7, 1, 5, 3, 6, 2]) + >>> p.inversion_vector() + [4, 7, 0, 5, 0, 2, 1, 1] + >>> p = Permutation([3, 2, 1, 0]) + >>> p.inversion_vector() + [3, 2, 1] + + The inversion vector increases lexicographically with the rank + of the permutation, the -ith element cycling through 0..i. + + >>> p = Permutation(2) + >>> while p: + ... print('%s %s %s' % (p, p.inversion_vector(), p.rank())) + ... p = p.next_lex() + (2) [0, 0] 0 + (1 2) [0, 1] 1 + (2)(0 1) [1, 0] 2 + (0 1 2) [1, 1] 3 + (0 2 1) [2, 0] 4 + (0 2) [2, 1] 5 + + See Also + ======== + + from_inversion_vector + """ + self_array_form = self.array_form + n = len(self_array_form) + inversion_vector = [0] * (n - 1) + + for i in range(n - 1): + val = 0 + for j in range(i + 1, n): + if self_array_form[j] < self_array_form[i]: + val += 1 + inversion_vector[i] = val + return inversion_vector + + def rank_trotterjohnson(self): + """ + Returns the Trotter Johnson rank, which we get from the minimal + change algorithm. See [4] section 2.4. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 1, 2, 3]) + >>> p.rank_trotterjohnson() + 0 + >>> p = Permutation([0, 2, 1, 3]) + >>> p.rank_trotterjohnson() + 7 + + See Also + ======== + + unrank_trotterjohnson, next_trotterjohnson + """ + if self.array_form == [] or self.is_Identity: + return 0 + if self.array_form == [1, 0]: + return 1 + perm = self.array_form + n = self.size + rank = 0 + for j in range(1, n): + k = 1 + i = 0 + while perm[i] != j: + if perm[i] < j: + k += 1 + i += 1 + j1 = j + 1 + if rank % 2 == 0: + rank = j1*rank + j1 - k + else: + rank = j1*rank + k - 1 + return rank + + @classmethod + def unrank_trotterjohnson(cls, size, rank): + """ + Trotter Johnson permutation unranking. See [4] section 2.4. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> Permutation.unrank_trotterjohnson(5, 10) + Permutation([0, 3, 1, 2, 4]) + + See Also + ======== + + rank_trotterjohnson, next_trotterjohnson + """ + perm = [0]*size + r2 = 0 + n = ifac(size) + pj = 1 + for j in range(2, size + 1): + pj *= j + r1 = (rank * pj) // n + k = r1 - j*r2 + if r2 % 2 == 0: + for i in range(j - 1, j - k - 1, -1): + perm[i] = perm[i - 1] + perm[j - k - 1] = j - 1 + else: + for i in range(j - 1, k, -1): + perm[i] = perm[i - 1] + perm[k] = j - 1 + r2 = r1 + return cls._af_new(perm) + + def next_trotterjohnson(self): + """ + Returns the next permutation in Trotter-Johnson order. + If self is the last permutation it returns None. + See [4] section 2.4. If it is desired to generate all such + permutations, they can be generated in order more quickly + with the ``generate_bell`` function. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> p = Permutation([3, 0, 2, 1]) + >>> p.rank_trotterjohnson() + 4 + >>> p = p.next_trotterjohnson(); p + Permutation([0, 3, 2, 1]) + >>> p.rank_trotterjohnson() + 5 + + See Also + ======== + + rank_trotterjohnson, unrank_trotterjohnson, sympy.utilities.iterables.generate_bell + """ + pi = self.array_form[:] + n = len(pi) + st = 0 + rho = pi[:] + done = False + m = n-1 + while m > 0 and not done: + d = rho.index(m) + for i in range(d, m): + rho[i] = rho[i + 1] + par = _af_parity(rho[:m]) + if par == 1: + if d == m: + m -= 1 + else: + pi[st + d], pi[st + d + 1] = pi[st + d + 1], pi[st + d] + done = True + else: + if d == 0: + m -= 1 + st += 1 + else: + pi[st + d], pi[st + d - 1] = pi[st + d - 1], pi[st + d] + done = True + if m == 0: + return None + return self._af_new(pi) + + def get_precedence_matrix(self): + """ + Gets the precedence matrix. This is used for computing the + distance between two permutations. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> p = Permutation.josephus(3, 6, 1) + >>> p + Permutation([2, 5, 3, 1, 4, 0]) + >>> p.get_precedence_matrix() + Matrix([ + [0, 0, 0, 0, 0, 0], + [1, 0, 0, 0, 1, 0], + [1, 1, 0, 1, 1, 1], + [1, 1, 0, 0, 1, 0], + [1, 0, 0, 0, 0, 0], + [1, 1, 0, 1, 1, 0]]) + + See Also + ======== + + get_precedence_distance, get_adjacency_matrix, get_adjacency_distance + """ + m = zeros(self.size) + perm = self.array_form + for i in range(m.rows): + for j in range(i + 1, m.cols): + m[perm[i], perm[j]] = 1 + return m + + def get_precedence_distance(self, other): + """ + Computes the precedence distance between two permutations. + + Explanation + =========== + + Suppose p and p' represent n jobs. The precedence metric + counts the number of times a job j is preceded by job i + in both p and p'. This metric is commutative. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([2, 0, 4, 3, 1]) + >>> q = Permutation([3, 1, 2, 4, 0]) + >>> p.get_precedence_distance(q) + 7 + >>> q.get_precedence_distance(p) + 7 + + See Also + ======== + + get_precedence_matrix, get_adjacency_matrix, get_adjacency_distance + """ + if self.size != other.size: + raise ValueError("The permutations must be of equal size.") + self_prec_mat = self.get_precedence_matrix() + other_prec_mat = other.get_precedence_matrix() + n_prec = 0 + for i in range(self.size): + for j in range(self.size): + if i == j: + continue + if self_prec_mat[i, j] * other_prec_mat[i, j] == 1: + n_prec += 1 + d = self.size * (self.size - 1)//2 - n_prec + return d + + def get_adjacency_matrix(self): + """ + Computes the adjacency matrix of a permutation. + + Explanation + =========== + + If job i is adjacent to job j in a permutation p + then we set m[i, j] = 1 where m is the adjacency + matrix of p. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation.josephus(3, 6, 1) + >>> p.get_adjacency_matrix() + Matrix([ + [0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 0, 1], + [0, 1, 0, 0, 0, 0], + [1, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0]]) + >>> q = Permutation([0, 1, 2, 3]) + >>> q.get_adjacency_matrix() + Matrix([ + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1], + [0, 0, 0, 0]]) + + See Also + ======== + + get_precedence_matrix, get_precedence_distance, get_adjacency_distance + """ + m = zeros(self.size) + perm = self.array_form + for i in range(self.size - 1): + m[perm[i], perm[i + 1]] = 1 + return m + + def get_adjacency_distance(self, other): + """ + Computes the adjacency distance between two permutations. + + Explanation + =========== + + This metric counts the number of times a pair i,j of jobs is + adjacent in both p and p'. If n_adj is this quantity then + the adjacency distance is n - n_adj - 1 [1] + + [1] Reeves, Colin R. Landscapes, Operators and Heuristic search, Annals + of Operational Research, 86, pp 473-490. (1999) + + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 3, 1, 2, 4]) + >>> q = Permutation.josephus(4, 5, 2) + >>> p.get_adjacency_distance(q) + 3 + >>> r = Permutation([0, 2, 1, 4, 3]) + >>> p.get_adjacency_distance(r) + 4 + + See Also + ======== + + get_precedence_matrix, get_precedence_distance, get_adjacency_matrix + """ + if self.size != other.size: + raise ValueError("The permutations must be of the same size.") + self_adj_mat = self.get_adjacency_matrix() + other_adj_mat = other.get_adjacency_matrix() + n_adj = 0 + for i in range(self.size): + for j in range(self.size): + if i == j: + continue + if self_adj_mat[i, j] * other_adj_mat[i, j] == 1: + n_adj += 1 + d = self.size - n_adj - 1 + return d + + def get_positional_distance(self, other): + """ + Computes the positional distance between two permutations. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> p = Permutation([0, 3, 1, 2, 4]) + >>> q = Permutation.josephus(4, 5, 2) + >>> r = Permutation([3, 1, 4, 0, 2]) + >>> p.get_positional_distance(q) + 12 + >>> p.get_positional_distance(r) + 12 + + See Also + ======== + + get_precedence_distance, get_adjacency_distance + """ + a = self.array_form + b = other.array_form + if len(a) != len(b): + raise ValueError("The permutations must be of the same size.") + return sum([abs(a[i] - b[i]) for i in range(len(a))]) + + @classmethod + def josephus(cls, m, n, s=1): + """Return as a permutation the shuffling of range(n) using the Josephus + scheme in which every m-th item is selected until all have been chosen. + The returned permutation has elements listed by the order in which they + were selected. + + The parameter ``s`` stops the selection process when there are ``s`` + items remaining and these are selected by continuing the selection, + counting by 1 rather than by ``m``. + + Consider selecting every 3rd item from 6 until only 2 remain:: + + choices chosen + ======== ====== + 012345 + 01 345 2 + 01 34 25 + 01 4 253 + 0 4 2531 + 0 25314 + 253140 + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation.josephus(3, 6, 2).array_form + [2, 5, 3, 1, 4, 0] + + References + ========== + + .. [1] https://en.wikipedia.org/wiki/Flavius_Josephus + .. [2] https://en.wikipedia.org/wiki/Josephus_problem + .. [3] https://web.archive.org/web/20171008094331/http://www.wou.edu/~burtonl/josephus.html + + """ + from collections import deque + m -= 1 + Q = deque(list(range(n))) + perm = [] + while len(Q) > max(s, 1): + for dp in range(m): + Q.append(Q.popleft()) + perm.append(Q.popleft()) + perm.extend(list(Q)) + return cls(perm) + + @classmethod + def from_inversion_vector(cls, inversion): + """ + Calculates the permutation from the inversion vector. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> Permutation.from_inversion_vector([3, 2, 1, 0, 0]) + Permutation([3, 2, 1, 0, 4, 5]) + + """ + size = len(inversion) + N = list(range(size + 1)) + perm = [] + try: + for k in range(size): + val = N[inversion[k]] + perm.append(val) + N.remove(val) + except IndexError: + raise ValueError("The inversion vector is not valid.") + perm.extend(N) + return cls._af_new(perm) + + @classmethod + def random(cls, n): + """ + Generates a random permutation of length ``n``. + + Uses the underlying Python pseudo-random number generator. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> Permutation.random(2) in (Permutation([1, 0]), Permutation([0, 1])) + True + + """ + perm_array = list(range(n)) + random.shuffle(perm_array) + return cls._af_new(perm_array) + + @classmethod + def unrank_lex(cls, size, rank): + """ + Lexicographic permutation unranking. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + >>> from sympy import init_printing + >>> init_printing(perm_cyclic=False, pretty_print=False) + >>> a = Permutation.unrank_lex(5, 10) + >>> a.rank() + 10 + >>> a + Permutation([0, 2, 4, 1, 3]) + + See Also + ======== + + rank, next_lex + """ + perm_array = [0] * size + psize = 1 + for i in range(size): + new_psize = psize*(i + 1) + d = (rank % new_psize) // psize + rank -= d*psize + perm_array[size - i - 1] = d + for j in range(size - i, size): + if perm_array[j] > d - 1: + perm_array[j] += 1 + psize = new_psize + return cls._af_new(perm_array) + + def resize(self, n): + """Resize the permutation to the new size ``n``. + + Parameters + ========== + + n : int + The new size of the permutation. + + Raises + ====== + + ValueError + If the permutation cannot be resized to the given size. + This may only happen when resized to a smaller size than + the original. + + Examples + ======== + + >>> from sympy.combinatorics import Permutation + + Increasing the size of a permutation: + + >>> p = Permutation(0, 1, 2) + >>> p = p.resize(5) + >>> p + (4)(0 1 2) + + Decreasing the size of the permutation: + + >>> p = p.resize(4) + >>> p + (3)(0 1 2) + + If resizing to the specific size breaks the cycles: + + >>> p.resize(2) + Traceback (most recent call last): + ... + ValueError: The permutation cannot be resized to 2 because the + cycle (0, 1, 2) may break. + """ + aform = self.array_form + l = len(aform) + if n > l: + aform += list(range(l, n)) + return Permutation._af_new(aform) + + elif n < l: + cyclic_form = self.full_cyclic_form + new_cyclic_form = [] + for cycle in cyclic_form: + cycle_min = min(cycle) + cycle_max = max(cycle) + if cycle_min <= n-1: + if cycle_max > n-1: + raise ValueError( + "The permutation cannot be resized to {} " + "because the cycle {} may break." + .format(n, tuple(cycle))) + + new_cyclic_form.append(cycle) + return Permutation(new_cyclic_form) + + return self + + # XXX Deprecated flag + print_cyclic = None + + +def _merge(arr, temp, left, mid, right): + """ + Merges two sorted arrays and calculates the inversion count. + + Helper function for calculating inversions. This method is + for internal use only. + """ + i = k = left + j = mid + inv_count = 0 + while i < mid and j <= right: + if arr[i] < arr[j]: + temp[k] = arr[i] + k += 1 + i += 1 + else: + temp[k] = arr[j] + k += 1 + j += 1 + inv_count += (mid -i) + while i < mid: + temp[k] = arr[i] + k += 1 + i += 1 + if j <= right: + k += right - j + 1 + j += right - j + 1 + arr[left:k + 1] = temp[left:k + 1] + else: + arr[left:right + 1] = temp[left:right + 1] + return inv_count + +Perm = Permutation +_af_new = Perm._af_new + + +class AppliedPermutation(Expr): + """A permutation applied to a symbolic variable. + + Parameters + ========== + + perm : Permutation + x : Expr + + Examples + ======== + + >>> from sympy import Symbol + >>> from sympy.combinatorics import Permutation + + Creating a symbolic permutation function application: + + >>> x = Symbol('x') + >>> p = Permutation(0, 1, 2) + >>> p.apply(x) + AppliedPermutation((0 1 2), x) + >>> _.subs(x, 1) + 2 + """ + def __new__(cls, perm, x, evaluate=None): + if evaluate is None: + evaluate = global_parameters.evaluate + + perm = _sympify(perm) + x = _sympify(x) + + if not isinstance(perm, Permutation): + raise ValueError("{} must be a Permutation instance." + .format(perm)) + + if evaluate: + if x.is_Integer: + return perm.apply(x) + + obj = super().__new__(cls, perm, x) + return obj + + +@dispatch(Permutation, Permutation) +def _eval_is_eq(lhs, rhs): + if lhs._size != rhs._size: + return None + return lhs._array_form == rhs._array_form diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/conftest.py b/env-llmeval/lib/python3.10/site-packages/sympy/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..7deb7c548c41f6fe64a361b34d6a9e9c0c1e0724 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/conftest.py @@ -0,0 +1,74 @@ +import sys +sys._running_pytest = True # type: ignore +from sympy.external.importtools import version_tuple + +import pytest +from sympy.core.cache import clear_cache, USE_CACHE +from sympy.external.gmpy import GROUND_TYPES, HAS_GMPY +from sympy.utilities.misc import ARCH +import re + +sp = re.compile(r'([0-9]+)/([1-9][0-9]*)') + +def process_split(config, items): + split = config.getoption("--split") + if not split: + return + m = sp.match(split) + if not m: + raise ValueError("split must be a string of the form a/b " + "where a and b are ints.") + i, t = map(int, m.groups()) + start, end = (i-1)*len(items)//t, i*len(items)//t + + if i < t: + # remove elements from end of list first + del items[end:] + del items[:start] + + +def pytest_report_header(config): + s = "architecture: %s\n" % ARCH + s += "cache: %s\n" % USE_CACHE + version = '' + if GROUND_TYPES =='gmpy': + if HAS_GMPY == 1: + import gmpy + elif HAS_GMPY == 2: + import gmpy2 as gmpy + version = gmpy.version() + s += "ground types: %s %s\n" % (GROUND_TYPES, version) + return s + + +def pytest_terminal_summary(terminalreporter): + if (terminalreporter.stats.get('error', None) or + terminalreporter.stats.get('failed', None)): + terminalreporter.write_sep( + ' ', 'DO *NOT* COMMIT!', red=True, bold=True) + + +def pytest_addoption(parser): + parser.addoption("--split", action="store", default="", + help="split tests") + + +def pytest_collection_modifyitems(config, items): + """ pytest hook. """ + # handle splits + process_split(config, items) + + +@pytest.fixture(autouse=True, scope='module') +def file_clear_cache(): + clear_cache() + +@pytest.fixture(autouse=True, scope='module') +def check_disabled(request): + if getattr(request.module, 'disabled', False): + pytest.skip("test requirements not met.") + elif getattr(request.module, 'ipython', False): + # need to check version and options for ipython tests + if (version_tuple(pytest.__version__) < version_tuple('2.6.3') and + pytest.config.getvalue('-s') != 'no'): + pytest.skip("run py.test with -s or upgrade to newer version.") diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/galgebra.py b/env-llmeval/lib/python3.10/site-packages/sympy/galgebra.py new file mode 100644 index 0000000000000000000000000000000000000000..be812bfcbcece834c86d7b55eb846286acd0ac08 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/galgebra.py @@ -0,0 +1 @@ +raise ImportError("""As of SymPy 1.0 the galgebra module is maintained separately at https://github.com/pygae/galgebra""") diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/py.typed b/env-llmeval/lib/python3.10/site-packages/sympy/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/release.py b/env-llmeval/lib/python3.10/site-packages/sympy/release.py new file mode 100644 index 0000000000000000000000000000000000000000..8d0cd9f51b685e98781a28872c4984338e242104 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/release.py @@ -0,0 +1 @@ +__version__ = "1.12" diff --git a/env-llmeval/lib/python3.10/site-packages/sympy/this.py b/env-llmeval/lib/python3.10/site-packages/sympy/this.py new file mode 100644 index 0000000000000000000000000000000000000000..c2a5504ac42c7d57790d65524b066a6df86ab539 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/sympy/this.py @@ -0,0 +1,21 @@ +""" +The Zen of SymPy. +""" + +s = """The Zen of SymPy + +Unevaluated is better than evaluated. +The user interface matters. +Printing matters. +Pure Python can be fast enough. +If it's too slow, it's (probably) your fault. +Documentation matters. +Correctness is more important than speed. +Push it in now and improve upon it later. +Coverage by testing matters. +Smart tests are better than random tests. +But random tests sometimes find what your smartest test missed. +The Python way is probably the right way. +Community is more important than code.""" + +print(s) diff --git a/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/INSTALLER b/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/LICENSE b/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c467ac089a1caa6610d1379fe6a48132c15dcd5a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Tsuyoshi Hombashi + +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/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/METADATA b/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..00c2945f053be786fb7e11a525ee5641ae3b3d94 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/METADATA @@ -0,0 +1,102 @@ +Metadata-Version: 2.1 +Name: tabledata +Version: 1.3.3 +Summary: tabledata is a Python library to represent tabular data. Used for pytablewriter/pytablereader/SimpleSQLite/etc. +Home-page: https://github.com/thombashi/tabledata +Author: Tsuyoshi Hombashi +Author-email: tsuyoshi.hombashi@gmail.com +License: MIT License +Project-URL: Changlog, https://github.com/thombashi/tabledata/releases +Project-URL: Documentation, https://tabledata.rtfd.io/ +Project-URL: Source, https://github.com/thombashi/tabledata +Project-URL: Tracker, https://github.com/thombashi/tabledata/issues +Keywords: table +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: DataProperty <2,>=1.0.1 +Requires-Dist: typepy <2,>=1.2.0 +Provides-Extra: logging +Requires-Dist: loguru <1,>=0.4.1 ; extra == 'logging' +Provides-Extra: test +Requires-Dist: pytablewriter >=0.46 ; extra == 'test' +Requires-Dist: pytest ; extra == 'test' + +.. contents:: **tabledata** + :backlinks: top + :depth: 2 + +Summary +--------- +`tabledata `__ is a Python library to represent tabular data. Used for pytablewriter/pytablereader/SimpleSQLite/etc. + +.. image:: https://badge.fury.io/py/tabledata.svg + :target: https://badge.fury.io/py/tabledata + :alt: PyPI package version + +.. image:: https://img.shields.io/pypi/pyversions/tabledata.svg + :target: https://pypi.org/project/tabledata + :alt: Supported Python versions + +.. image:: https://img.shields.io/pypi/implementation/tabledata.svg + :target: https://pypi.org/project/tabledata + :alt: Supported Python implementations + +.. image:: https://github.com/thombashi/tabledata/actions/workflows/ci.yml/badge.svg + :target: https://github.com/thombashi/tabledata/actions/workflows/ci.yml + :alt: Linux/macOS/Windows CI status + +.. image:: https://coveralls.io/repos/github/thombashi/tabledata/badge.svg?branch=master + :target: https://coveralls.io/github/thombashi/tabledata?branch=master + :alt: Test coverage + +Installation +============ + +Install from PyPI +------------------------------ +:: + + pip install tabledata + +Install from PPA (for Ubuntu) +------------------------------ +:: + + sudo add-apt-repository ppa:thombashi/ppa + sudo apt update + sudo apt install python3-tabledata + + +Dependencies +============ +- Python 3.7+ +- `Mandatory Python package dependencies (automatically installed) `__ + +Optional Python packages +------------------------------------------------ +- `loguru `__ + - Used for logging if the package installed +- `pandas `__ + - required to get table data as a pandas data frame + +Documentation +=============== +https://tabledata.rtfd.io/ + diff --git a/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/RECORD b/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..ef0f46d59e3fc059c82a7c256f4fc6d56d1c7378 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/RECORD @@ -0,0 +1,29 @@ +tabledata-1.3.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +tabledata-1.3.3.dist-info/LICENSE,sha256=vrvfBSShR_iaYV__U9eb3JDLx2MVUPtLclzT873NJPY,1074 +tabledata-1.3.3.dist-info/METADATA,sha256=IKxSJeg1Qrr6dSTCJdvnBIiKl6IKCa4aAIC_B4Ngwfg,3657 +tabledata-1.3.3.dist-info/RECORD,, +tabledata-1.3.3.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92 +tabledata-1.3.3.dist-info/top_level.txt,sha256=wPYCjph2PxB5odPJWPADX_65iL1gAIjMQFlAyZi80iI,10 +tabledata/__init__.py,sha256=OkkMA83NWJOKsmUru4qWiUXrwTxF5jDhHXl_dR2zQBQ,683 +tabledata/__pycache__/__init__.cpython-310.pyc,, +tabledata/__pycache__/__version__.cpython-310.pyc,, +tabledata/__pycache__/_common.cpython-310.pyc,, +tabledata/__pycache__/_constant.cpython-310.pyc,, +tabledata/__pycache__/_converter.cpython-310.pyc,, +tabledata/__pycache__/_core.cpython-310.pyc,, +tabledata/__pycache__/error.cpython-310.pyc,, +tabledata/__pycache__/normalizer.cpython-310.pyc,, +tabledata/__version__.py,sha256=JC4TkyHfH-eP9nAvfI04H3gEbgfItYa1jLE09ARSNSc,201 +tabledata/_common.py,sha256=eB3xHflvbF5p5hz1f5D9xNHQCujy6Uk91NLPTy5fFHY,274 +tabledata/_constant.py,sha256=I763_Fx-9IT_ZQTTncxi04WsXd6tK78z2VBYZ3up5Aw,154 +tabledata/_converter.py,sha256=0H61eirjQw_rs0h1N_APtCthRRFbYkKZVUHK-5-0GAE,895 +tabledata/_core.py,sha256=4y0sLRCEcvjJvqi_pUlhz5qjIass_pZu5FcnK_kpr7U,14530 +tabledata/_logger/__init__.py,sha256=7rkhAj6PGbUI3fouTa7GEzjRelUFj0_UPfzkZ_Yk71g,55 +tabledata/_logger/__pycache__/__init__.cpython-310.pyc,, +tabledata/_logger/__pycache__/_logger.cpython-310.pyc,, +tabledata/_logger/__pycache__/_null_logger.cpython-310.pyc,, +tabledata/_logger/_logger.py,sha256=3HreG22mzHGZvexAGZpjkU4A995ZZmGJmiIkPcrkA4o,783 +tabledata/_logger/_null_logger.py,sha256=QJuaErUIV_x6NjQ9qNX9eNSi_GB_9CrO7lKeXYZnuaw,1088 +tabledata/error.py,sha256=UGGJm3_9oLQi9GBWZz4cqp1dnzc5Kbu37c6CsiWozME,526 +tabledata/normalizer.py,sha256=lVz4agT8Bm97rvKUUUhP3OT1pGDsMczB5rAlx316XoY,6465 +tabledata/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/WHEEL b/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..7e688737d490be3643d705bc16b5a77f7bd567b7 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.2) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/top_level.txt b/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..43aaf2f47a3d66da5f27d0be87b84007bd70669a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/tabledata-1.3.3.dist-info/top_level.txt @@ -0,0 +1 @@ +tabledata diff --git a/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/INSTALLER b/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/LICENSE b/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..81241eca637574fb696620b54200d28a0ff53524 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2011-2020 Sergey Astanin and contributors + +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/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/METADATA b/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..3909a0009159614c1805e56722e8b8d285389796 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/METADATA @@ -0,0 +1,1149 @@ +Metadata-Version: 2.1 +Name: tabulate +Version: 0.9.0 +Summary: Pretty-print tabular data +Author-email: Sergey Astanin +License: MIT +Project-URL: Homepage, https://github.com/astanin/python-tabulate +Classifier: Development Status :: 4 - Beta +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Topic :: Software Development :: Libraries +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE +Provides-Extra: widechars +Requires-Dist: wcwidth ; extra == 'widechars' + +python-tabulate +=============== + +Pretty-print tabular data in Python, a library and a command-line +utility. + +The main use cases of the library are: + +- printing small tables without hassle: just one function call, + formatting is guided by the data itself +- authoring tabular data for lightweight plain-text markup: multiple + output formats suitable for further editing or transformation +- readable presentation of mixed textual and numeric data: smart + column alignment, configurable number formatting, alignment by a + decimal point + +Installation +------------ + +To install the Python library and the command line utility, run: + +```shell +pip install tabulate +``` + +The command line utility will be installed as `tabulate` to `bin` on +Linux (e.g. `/usr/bin`); or as `tabulate.exe` to `Scripts` in your +Python installation on Windows (e.g. `C:\Python39\Scripts\tabulate.exe`). + +You may consider installing the library only for the current user: + +```shell +pip install tabulate --user +``` + +In this case the command line utility will be installed to +`~/.local/bin/tabulate` on Linux and to +`%APPDATA%\Python\Scripts\tabulate.exe` on Windows. + +To install just the library on Unix-like operating systems: + +```shell +TABULATE_INSTALL=lib-only pip install tabulate +``` + +On Windows: + +```shell +set TABULATE_INSTALL=lib-only +pip install tabulate +``` + +Build status +------------ + +[![Build status](https://circleci.com/gh/astanin/python-tabulate.svg?style=svg)](https://circleci.com/gh/astanin/python-tabulate/tree/master) [![Build status](https://ci.appveyor.com/api/projects/status/8745yksvvol7h3d7/branch/master?svg=true)](https://ci.appveyor.com/project/astanin/python-tabulate/branch/master) + +Library usage +------------- + +The module provides just one function, `tabulate`, which takes a list of +lists or another tabular data type as the first argument, and outputs a +nicely formatted plain-text table: + +```pycon +>>> from tabulate import tabulate + +>>> table = [["Sun",696000,1989100000],["Earth",6371,5973.6], +... ["Moon",1737,73.5],["Mars",3390,641.85]] +>>> print(tabulate(table)) +----- ------ ------------- +Sun 696000 1.9891e+09 +Earth 6371 5973.6 +Moon 1737 73.5 +Mars 3390 641.85 +----- ------ ------------- +``` + +The following tabular data types are supported: + +- list of lists or another iterable of iterables +- list or another iterable of dicts (keys as columns) +- dict of iterables (keys as columns) +- list of dataclasses (Python 3.7+ only, field names as columns) +- two-dimensional NumPy array +- NumPy record arrays (names as columns) +- pandas.DataFrame + +Tabulate is a Python3 library. + +### Headers + +The second optional argument named `headers` defines a list of column +headers to be used: + +```pycon +>>> print(tabulate(table, headers=["Planet","R (km)", "mass (x 10^29 kg)"])) +Planet R (km) mass (x 10^29 kg) +-------- -------- ------------------- +Sun 696000 1.9891e+09 +Earth 6371 5973.6 +Moon 1737 73.5 +Mars 3390 641.85 +``` + +If `headers="firstrow"`, then the first row of data is used: + +```pycon +>>> print(tabulate([["Name","Age"],["Alice",24],["Bob",19]], +... headers="firstrow")) +Name Age +------ ----- +Alice 24 +Bob 19 +``` + +If `headers="keys"`, then the keys of a dictionary/dataframe, or column +indices are used. It also works for NumPy record arrays and lists of +dictionaries or named tuples: + +```pycon +>>> print(tabulate({"Name": ["Alice", "Bob"], +... "Age": [24, 19]}, headers="keys")) + Age Name +----- ------ + 24 Alice + 19 Bob +``` + +### Row Indices + +By default, only pandas.DataFrame tables have an additional column +called row index. To add a similar column to any other type of table, +pass `showindex="always"` or `showindex=True` argument to `tabulate()`. +To suppress row indices for all types of data, pass `showindex="never"` +or `showindex=False`. To add a custom row index column, pass +`showindex=rowIDs`, where `rowIDs` is some iterable: + +```pycon +>>> print(tabulate([["F",24],["M",19]], showindex="always")) +- - -- +0 F 24 +1 M 19 +- - -- +``` + +### Table format + +There is more than one way to format a table in plain text. The third +optional argument named `tablefmt` defines how the table is formatted. + +Supported table formats are: + +- "plain" +- "simple" +- "github" +- "grid" +- "simple\_grid" +- "rounded\_grid" +- "heavy\_grid" +- "mixed\_grid" +- "double\_grid" +- "fancy\_grid" +- "outline" +- "simple\_outline" +- "rounded\_outline" +- "heavy\_outline" +- "mixed\_outline" +- "double\_outline" +- "fancy\_outline" +- "pipe" +- "orgtbl" +- "asciidoc" +- "jira" +- "presto" +- "pretty" +- "psql" +- "rst" +- "mediawiki" +- "moinmoin" +- "youtrack" +- "html" +- "unsafehtml" +- "latex" +- "latex\_raw" +- "latex\_booktabs" +- "latex\_longtable" +- "textile" +- "tsv" + +`plain` tables do not use any pseudo-graphics to draw lines: + +```pycon +>>> table = [["spam",42],["eggs",451],["bacon",0]] +>>> headers = ["item", "qty"] +>>> print(tabulate(table, headers, tablefmt="plain")) +item qty +spam 42 +eggs 451 +bacon 0 +``` + +`simple` is the default format (the default may change in future +versions). It corresponds to `simple_tables` in [Pandoc Markdown +extensions](http://johnmacfarlane.net/pandoc/README.html#tables): + +```pycon +>>> print(tabulate(table, headers, tablefmt="simple")) +item qty +------ ----- +spam 42 +eggs 451 +bacon 0 +``` + +`github` follows the conventions of GitHub flavored Markdown. It +corresponds to the `pipe` format without alignment colons: + +```pycon +>>> print(tabulate(table, headers, tablefmt="github")) +| item | qty | +|--------|-------| +| spam | 42 | +| eggs | 451 | +| bacon | 0 | +``` + +`grid` is like tables formatted by Emacs' +[table.el](http://table.sourceforge.net/) package. It corresponds to +`grid_tables` in Pandoc Markdown extensions: + +```pycon +>>> print(tabulate(table, headers, tablefmt="grid")) ++--------+-------+ +| item | qty | ++========+=======+ +| spam | 42 | ++--------+-------+ +| eggs | 451 | ++--------+-------+ +| bacon | 0 | ++--------+-------+ +``` + +`simple_grid` draws a grid using single-line box-drawing characters: + + >>> print(tabulate(table, headers, tablefmt="simple_grid")) + ┌────────┬───────┐ + │ item │ qty │ + ├────────┼───────┤ + │ spam │ 42 │ + ├────────┼───────┤ + │ eggs │ 451 │ + ├────────┼───────┤ + │ bacon │ 0 │ + └────────┴───────┘ + +`rounded_grid` draws a grid using single-line box-drawing characters with rounded corners: + + >>> print(tabulate(table, headers, tablefmt="rounded_grid")) + ╭────────┬───────╮ + │ item │ qty │ + ├────────┼───────┤ + │ spam │ 42 │ + ├────────┼───────┤ + │ eggs │ 451 │ + ├────────┼───────┤ + │ bacon │ 0 │ + ╰────────┴───────╯ + +`heavy_grid` draws a grid using bold (thick) single-line box-drawing characters: + + >>> print(tabulate(table, headers, tablefmt="heavy_grid")) + ┏━━━━━━━━┳━━━━━━━┓ + ┃ item ┃ qty ┃ + ┣━━━━━━━━╋━━━━━━━┫ + ┃ spam ┃ 42 ┃ + ┣━━━━━━━━╋━━━━━━━┫ + ┃ eggs ┃ 451 ┃ + ┣━━━━━━━━╋━━━━━━━┫ + ┃ bacon ┃ 0 ┃ + ┗━━━━━━━━┻━━━━━━━┛ + +`mixed_grid` draws a grid using a mix of light (thin) and heavy (thick) lines box-drawing characters: + + >>> print(tabulate(table, headers, tablefmt="mixed_grid")) + ┍━━━━━━━━┯━━━━━━━┑ + │ item │ qty │ + ┝━━━━━━━━┿━━━━━━━┥ + │ spam │ 42 │ + ├────────┼───────┤ + │ eggs │ 451 │ + ├────────┼───────┤ + │ bacon │ 0 │ + ┕━━━━━━━━┷━━━━━━━┙ + +`double_grid` draws a grid using double-line box-drawing characters: + + >>> print(tabulate(table, headers, tablefmt="double_grid")) + ╔════════╦═══════╗ + ║ item ║ qty ║ + ╠════════╬═══════╣ + ║ spam ║ 42 ║ + ╠════════╬═══════╣ + ║ eggs ║ 451 ║ + ╠════════╬═══════╣ + ║ bacon ║ 0 ║ + ╚════════╩═══════╝ + +`fancy_grid` draws a grid using a mix of single and + double-line box-drawing characters: + +```pycon +>>> print(tabulate(table, headers, tablefmt="fancy_grid")) +╒════════╤═══════╕ +│ item │ qty │ +╞════════╪═══════╡ +│ spam │ 42 │ +├────────┼───────┤ +│ eggs │ 451 │ +├────────┼───────┤ +│ bacon │ 0 │ +╘════════╧═══════╛ +``` + +`outline` is the same as the `grid` format but doesn't draw lines between rows: + + >>> print(tabulate(table, headers, tablefmt="outline")) + +--------+-------+ + | item | qty | + +========+=======+ + | spam | 42 | + | eggs | 451 | + | bacon | 0 | + +--------+-------+ + +`simple_outline` is the same as the `simple_grid` format but doesn't draw lines between rows: + + >>> print(tabulate(table, headers, tablefmt="simple_outline")) + ┌────────┬───────┐ + │ item │ qty │ + ├────────┼───────┤ + │ spam │ 42 │ + │ eggs │ 451 │ + │ bacon │ 0 │ + └────────┴───────┘ + +`rounded_outline` is the same as the `rounded_grid` format but doesn't draw lines between rows: + + >>> print(tabulate(table, headers, tablefmt="rounded_outline")) + ╭────────┬───────╮ + │ item │ qty │ + ├────────┼───────┤ + │ spam │ 42 │ + │ eggs │ 451 │ + │ bacon │ 0 │ + ╰────────┴───────╯ + +`heavy_outline` is the same as the `heavy_grid` format but doesn't draw lines between rows: + + >>> print(tabulate(table, headers, tablefmt="heavy_outline")) + ┏━━━━━━━━┳━━━━━━━┓ + ┃ item ┃ qty ┃ + ┣━━━━━━━━╋━━━━━━━┫ + ┃ spam ┃ 42 ┃ + ┃ eggs ┃ 451 ┃ + ┃ bacon ┃ 0 ┃ + ┗━━━━━━━━┻━━━━━━━┛ + +`mixed_outline` is the same as the `mixed_grid` format but doesn't draw lines between rows: + + >>> print(tabulate(table, headers, tablefmt="mixed_outline")) + ┍━━━━━━━━┯━━━━━━━┑ + │ item │ qty │ + ┝━━━━━━━━┿━━━━━━━┥ + │ spam │ 42 │ + │ eggs │ 451 │ + │ bacon │ 0 │ + ┕━━━━━━━━┷━━━━━━━┙ + +`double_outline` is the same as the `double_grid` format but doesn't draw lines between rows: + + >>> print(tabulate(table, headers, tablefmt="double_outline")) + ╔════════╦═══════╗ + ║ item ║ qty ║ + ╠════════╬═══════╣ + ║ spam ║ 42 ║ + ║ eggs ║ 451 ║ + ║ bacon ║ 0 ║ + ╚════════╩═══════╝ + +`fancy_outline` is the same as the `fancy_grid` format but doesn't draw lines between rows: + + >>> print(tabulate(table, headers, tablefmt="fancy_outline")) + ╒════════╤═══════╕ + │ item │ qty │ + ╞════════╪═══════╡ + │ spam │ 42 │ + │ eggs │ 451 │ + │ bacon │ 0 │ + ╘════════╧═══════╛ + +`presto` is like tables formatted by Presto cli: + +```pycon +>>> print(tabulate(table, headers, tablefmt="presto")) + item | qty +--------+------- + spam | 42 + eggs | 451 + bacon | 0 +``` + +`pretty` attempts to be close to the format emitted by the PrettyTables +library: + +```pycon +>>> print(tabulate(table, headers, tablefmt="pretty")) ++-------+-----+ +| item | qty | ++-------+-----+ +| spam | 42 | +| eggs | 451 | +| bacon | 0 | ++-------+-----+ +``` + +`psql` is like tables formatted by Postgres' psql cli: + +```pycon +>>> print(tabulate(table, headers, tablefmt="psql")) ++--------+-------+ +| item | qty | +|--------+-------| +| spam | 42 | +| eggs | 451 | +| bacon | 0 | ++--------+-------+ +``` + +`pipe` follows the conventions of [PHP Markdown +Extra](http://michelf.ca/projects/php-markdown/extra/#table) extension. +It corresponds to `pipe_tables` in Pandoc. This format uses colons to +indicate column alignment: + +```pycon +>>> print(tabulate(table, headers, tablefmt="pipe")) +| item | qty | +|:-------|------:| +| spam | 42 | +| eggs | 451 | +| bacon | 0 | +``` + +`asciidoc` formats data like a simple table of the +[AsciiDoctor](https://docs.asciidoctor.org/asciidoc/latest/syntax-quick-reference/#tables) +format: + +```pycon +>>> print(tabulate(table, headers, tablefmt="asciidoc")) +[cols="8<,7>",options="header"] +|==== +| item | qty +| spam | 42 +| eggs | 451 +| bacon | 0 +|==== +``` + +`orgtbl` follows the conventions of Emacs +[org-mode](http://orgmode.org/manual/Tables.html), and is editable also +in the minor orgtbl-mode. Hence its name: + +```pycon +>>> print(tabulate(table, headers, tablefmt="orgtbl")) +| item | qty | +|--------+-------| +| spam | 42 | +| eggs | 451 | +| bacon | 0 | +``` + +`jira` follows the conventions of Atlassian Jira markup language: + +```pycon +>>> print(tabulate(table, headers, tablefmt="jira")) +|| item || qty || +| spam | 42 | +| eggs | 451 | +| bacon | 0 | +``` + +`rst` formats data like a simple table of the +[reStructuredText](http://docutils.sourceforge.net/docs/user/rst/quickref.html#tables) +format: + +```pycon +>>> print(tabulate(table, headers, tablefmt="rst")) +====== ===== +item qty +====== ===== +spam 42 +eggs 451 +bacon 0 +====== ===== +``` + +`mediawiki` format produces a table markup used in +[Wikipedia](http://www.mediawiki.org/wiki/Help:Tables) and on other +MediaWiki-based sites: + + ```pycon +>>> print(tabulate(table, headers, tablefmt="mediawiki")) +{| class="wikitable" style="text-align: left;" +|+ +|- +! item !! align="right"| qty +|- +| spam || align="right"| 42 +|- +| eggs || align="right"| 451 +|- +| bacon || align="right"| 0 +|} +``` + +`moinmoin` format produces a table markup used in +[MoinMoin](https://moinmo.in/) wikis: + +```pycon +>>> print(tabulate(table, headers, tablefmt="moinmoin")) +|| ''' item ''' || ''' quantity ''' || +|| spam || 41.999 || +|| eggs || 451 || +|| bacon || || +``` + +`youtrack` format produces a table markup used in Youtrack tickets: + +```pycon +>>> print(tabulate(table, headers, tablefmt="youtrack")) +|| item || quantity || +| spam | 41.999 | +| eggs | 451 | +| bacon | | +``` + +`textile` format produces a table markup used in +[Textile](http://redcloth.org/hobix.com/textile/) format: + +```pycon +>>> print(tabulate(table, headers, tablefmt="textile")) +|_. item |_. qty | +|<. spam |>. 42 | +|<. eggs |>. 451 | +|<. bacon |>. 0 | +``` + +`html` produces standard HTML markup as an html.escape'd str +with a ._repr_html_ method so that Jupyter Lab and Notebook display the HTML +and a .str property so that the raw HTML remains accessible. +`unsafehtml` table format can be used if an unescaped HTML is required: + +```pycon +>>> print(tabulate(table, headers, tablefmt="html")) + + + + + + + +
item qty
spam 42
eggs 451
bacon 0
+``` + +`latex` format creates a `tabular` environment for LaTeX markup, +replacing special characters like `_` or `\` to their LaTeX +correspondents: + +```pycon +>>> print(tabulate(table, headers, tablefmt="latex")) +\begin{tabular}{lr} +\hline + item & qty \\ +\hline + spam & 42 \\ + eggs & 451 \\ + bacon & 0 \\ +\hline +\end{tabular} +``` + +`latex_raw` behaves like `latex` but does not escape LaTeX commands and +special characters. + +`latex_booktabs` creates a `tabular` environment for LaTeX markup using +spacing and style from the `booktabs` package. + +`latex_longtable` creates a table that can stretch along multiple pages, +using the `longtable` package. + +### Column alignment + +`tabulate` is smart about column alignment. It detects columns which +contain only numbers, and aligns them by a decimal point (or flushes +them to the right if they appear to be integers). Text columns are +flushed to the left. + +You can override the default alignment with `numalign` and `stralign` +named arguments. Possible column alignments are: `right`, `center`, +`left`, `decimal` (only for numbers), and `None` (to disable alignment). + +Aligning by a decimal point works best when you need to compare numbers +at a glance: + +```pycon +>>> print(tabulate([[1.2345],[123.45],[12.345],[12345],[1234.5]])) +---------- + 1.2345 + 123.45 + 12.345 +12345 + 1234.5 +---------- +``` + +Compare this with a more common right alignment: + +```pycon +>>> print(tabulate([[1.2345],[123.45],[12.345],[12345],[1234.5]], numalign="right")) +------ +1.2345 +123.45 +12.345 + 12345 +1234.5 +------ +``` + +For `tabulate`, anything which can be parsed as a number is a number. +Even numbers represented as strings are aligned properly. This feature +comes in handy when reading a mixed table of text and numbers from a +file: + +```pycon +>>> import csv ; from StringIO import StringIO +>>> table = list(csv.reader(StringIO("spam, 42\neggs, 451\n"))) +>>> table +[['spam', ' 42'], ['eggs', ' 451']] +>>> print(tabulate(table)) +---- ---- +spam 42 +eggs 451 +---- ---- +``` + +To disable this feature use `disable_numparse=True`. + +```pycon +>>> print(tabulate.tabulate([["Ver1", "18.0"], ["Ver2","19.2"]], tablefmt="simple", disable_numparse=True)) +---- ---- +Ver1 18.0 +Ver2 19.2 +---- ---- +``` + +### Custom column alignment + +`tabulate` allows a custom column alignment to override the above. The +`colalign` argument can be a list or a tuple of `stralign` named +arguments. Possible column alignments are: `right`, `center`, `left`, +`decimal` (only for numbers), and `None` (to disable alignment). +Omitting an alignment uses the default. For example: + +```pycon +>>> print(tabulate([["one", "two"], ["three", "four"]], colalign=("right",)) +----- ---- + one two +three four +----- ---- +``` + +### Number formatting + +`tabulate` allows to define custom number formatting applied to all +columns of decimal numbers. Use `floatfmt` named argument: + +```pycon +>>> print(tabulate([["pi",3.141593],["e",2.718282]], floatfmt=".4f")) +-- ------ +pi 3.1416 +e 2.7183 +-- ------ +``` + +`floatfmt` argument can be a list or a tuple of format strings, one per +column, in which case every column may have different number formatting: + +```pycon +>>> print(tabulate([[0.12345, 0.12345, 0.12345]], floatfmt=(".1f", ".3f"))) +--- ----- ------- +0.1 0.123 0.12345 +--- ----- ------- +``` + +`intfmt` works similarly for integers + + >>> print(tabulate([["a",1000],["b",90000]], intfmt=",")) + - ------ + a 1,000 + b 90,000 + - ------ + +### Text formatting + +By default, `tabulate` removes leading and trailing whitespace from text +columns. To disable whitespace removal, set the global module-level flag +`PRESERVE_WHITESPACE`: + +```python +import tabulate +tabulate.PRESERVE_WHITESPACE = True +``` + +### Wide (fullwidth CJK) symbols + +To properly align tables which contain wide characters (typically +fullwidth glyphs from Chinese, Japanese or Korean languages), the user +should install `wcwidth` library. To install it together with +`tabulate`: + +```shell +pip install tabulate[widechars] +``` + +Wide character support is enabled automatically if `wcwidth` library is +already installed. To disable wide characters support without +uninstalling `wcwidth`, set the global module-level flag +`WIDE_CHARS_MODE`: + +```python +import tabulate +tabulate.WIDE_CHARS_MODE = False +``` + +### Multiline cells + +Most table formats support multiline cell text (text containing newline +characters). The newline characters are honored as line break +characters. + +Multiline cells are supported for data rows and for header rows. + +Further automatic line breaks are not inserted. Of course, some output +formats such as latex or html handle automatic formatting of the cell +content on their own, but for those that don't, the newline characters +in the input cell text are the only means to break a line in cell text. + +Note that some output formats (e.g. simple, or plain) do not represent +row delimiters, so that the representation of multiline cells in such +formats may be ambiguous to the reader. + +The following examples of formatted output use the following table with +a multiline cell, and headers with a multiline cell: + +```pycon +>>> table = [["eggs",451],["more\nspam",42]] +>>> headers = ["item\nname", "qty"] +``` + +`plain` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="plain")) +item qty +name +eggs 451 +more 42 +spam +``` + +`simple` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="simple")) +item qty +name +------ ----- +eggs 451 +more 42 +spam +``` + +`grid` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="grid")) ++--------+-------+ +| item | qty | +| name | | ++========+=======+ +| eggs | 451 | ++--------+-------+ +| more | 42 | +| spam | | ++--------+-------+ +``` + +`fancy_grid` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="fancy_grid")) +╒════════╤═══════╕ +│ item │ qty │ +│ name │ │ +╞════════╪═══════╡ +│ eggs │ 451 │ +├────────┼───────┤ +│ more │ 42 │ +│ spam │ │ +╘════════╧═══════╛ +``` + +`pipe` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="pipe")) +| item | qty | +| name | | +|:-------|------:| +| eggs | 451 | +| more | 42 | +| spam | | +``` + +`orgtbl` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="orgtbl")) +| item | qty | +| name | | +|--------+-------| +| eggs | 451 | +| more | 42 | +| spam | | +``` + +`jira` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="jira")) +| item | qty | +| name | | +|:-------|------:| +| eggs | 451 | +| more | 42 | +| spam | | +``` + +`presto` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="presto")) + item | qty + name | +--------+------- + eggs | 451 + more | 42 + spam | +``` + +`pretty` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="pretty")) ++------+-----+ +| item | qty | +| name | | ++------+-----+ +| eggs | 451 | +| more | 42 | +| spam | | ++------+-----+ +``` + +`psql` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="psql")) ++--------+-------+ +| item | qty | +| name | | +|--------+-------| +| eggs | 451 | +| more | 42 | +| spam | | ++--------+-------+ +``` + +`rst` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="rst")) +====== ===== +item qty +name +====== ===== +eggs 451 +more 42 +spam +====== ===== +``` + +Multiline cells are not well-supported for the other table formats. + +### Automating Multilines +While tabulate supports data passed in with multilines entries explicitly provided, +it also provides some support to help manage this work internally. + +The `maxcolwidths` argument is a list where each entry specifies the max width for +it's respective column. Any cell that will exceed this will automatically wrap the content. +To assign the same max width for all columns, a singular int scaler can be used. + +Use `None` for any columns where an explicit maximum does not need to be provided, +and thus no automate multiline wrapping will take place. + +The wrapping uses the python standard [textwrap.wrap](https://docs.python.org/3/library/textwrap.html#textwrap.wrap) +function with default parameters - aside from width. + +This example demonstrates usage of automatic multiline wrapping, though typically +the lines being wrapped would probably be significantly longer than this. + +```pycon +>>> print(tabulate([["John Smith", "Middle Manager"]], headers=["Name", "Title"], tablefmt="grid", maxcolwidths=[None, 8])) ++------------+---------+ +| Name | Title | ++============+=========+ +| John Smith | Middle | +| | Manager | ++------------+---------+ +``` + +### Adding Separating lines +One might want to add one or more separating lines to highlight different sections in a table. + +The separating lines will be of the same type as the one defined by the specified formatter as either the +linebetweenrows, linebelowheader, linebelow, lineabove or just a simple empty line when none is defined for the formatter + + + >>> from tabulate import tabulate, SEPARATING_LINE + + table = [["Earth",6371], + ["Mars",3390], + SEPARATING_LINE, + ["Moon",1737]] + print(tabulate(table, tablefmt="simple")) + ----- ---- + Earth 6371 + Mars 3390 + ----- ---- + Moon 1737 + ----- ---- + +### ANSI support +ANSI escape codes are non-printable byte sequences usually used for terminal operations like setting +color output or modifying cursor positions. Because multi-byte ANSI sequences are inherently non-printable, +they can still introduce unwanted extra length to strings. For example: + + >>> len('\033[31mthis text is red\033[0m') # printable length is 16 + 25 + +To deal with this, string lengths are calculated after first removing all ANSI escape sequences. This ensures +that the actual printable length is used for column widths, rather than the byte length. In the final, printable +table, however, ANSI escape sequences are not removed so the original styling is preserved. + +Some terminals support a special grouping of ANSI escape sequences that are intended to display hyperlinks +much in the same way they are shown in browsers. These are handled just as mentioned before: non-printable +ANSI escape sequences are removed prior to string length calculation. The only diifference with escaped +hyperlinks is that column width will be based on the length of the URL _text_ rather than the URL +itself (terminals would show this text). For example: + + >>> len('\x1b]8;;https://example.com\x1b\\example\x1b]8;;\x1b\\') # display length is 7, showing 'example' + 45 + + +Usage of the command line utility +--------------------------------- + + Usage: tabulate [options] [FILE ...] + + FILE a filename of the file with tabular data; + if "-" or missing, read data from stdin. + + Options: + + -h, --help show this message + -1, --header use the first row of data as a table header + -o FILE, --output FILE print table to FILE (default: stdout) + -s REGEXP, --sep REGEXP use a custom column separator (default: whitespace) + -F FPFMT, --float FPFMT floating point number format (default: g) + -I INTFMT, --int INTFMT integer point number format (default: "") + -f FMT, --format FMT set output table format; supported formats: + plain, simple, github, grid, fancy_grid, pipe, + orgtbl, rst, mediawiki, html, latex, latex_raw, + latex_booktabs, latex_longtable, tsv + (default: simple) + +Performance considerations +-------------------------- + +Such features as decimal point alignment and trying to parse everything +as a number imply that `tabulate`: + +- has to "guess" how to print a particular tabular data type +- needs to keep the entire table in-memory +- has to "transpose" the table twice +- does much more work than it may appear + +It may not be suitable for serializing really big tables (but who's +going to do that, anyway?) or printing tables in performance sensitive +applications. `tabulate` is about two orders of magnitude slower than +simply joining lists of values with a tab, comma, or other separator. + +At the same time, `tabulate` is comparable to other table +pretty-printers. Given a 10x10 table (a list of lists) of mixed text and +numeric data, `tabulate` appears to be slower than `asciitable`, and +faster than `PrettyTable` and `texttable` The following mini-benchmark +was run in Python 3.9.13 on Windows 10: + + ================================= ========== =========== + Table formatter time, μs rel. time + ================================= ========== =========== + csv to StringIO 12.5 1.0 + join with tabs and newlines 14.6 1.2 + asciitable (0.8.0) 192.0 15.4 + tabulate (0.9.0) 483.5 38.7 + tabulate (0.9.0, WIDE_CHARS_MODE) 637.6 51.1 + PrettyTable (3.4.1) 1080.6 86.6 + texttable (1.6.4) 1390.3 111.4 + ================================= ========== =========== + + +Version history +--------------- + +The full version history can be found at the [changelog](https://github.com/astanin/python-tabulate/blob/master/CHANGELOG). + +How to contribute +----------------- + +Contributions should include tests and an explanation for the changes +they propose. Documentation (examples, docstrings, README.md) should be +updated accordingly. + +This project uses [pytest](https://docs.pytest.org/) testing +framework and [tox](https://tox.readthedocs.io/) to automate testing in +different environments. Add tests to one of the files in the `test/` +folder. + +To run tests on all supported Python versions, make sure all Python +interpreters, `pytest` and `tox` are installed, then run `tox` in the root +of the project source tree. + +On Linux `tox` expects to find executables like `python3.7`, `python3.8` etc. +On Windows it looks for `C:\Python37\python.exe`, `C:\Python38\python.exe` etc. respectively. + +One way to install all the required versions of the Python interpreter is to use [pyenv](https://github.com/pyenv/pyenv). +All versions can then be easily installed with something like: + + pyenv install 3.7.12 + pyenv install 3.8.12 + ... + +Don't forget to change your `PATH` so that `tox` knows how to find all the installed versions. Something like + + export PATH="${PATH}:${HOME}/.pyenv/shims" + +To test only some Python environments, use `-e` option. For example, to +test only against Python 3.7 and Python 3.10, run: + +```shell +tox -e py37,py310 +``` + +in the root of the project source tree. + +To enable NumPy and Pandas tests, run: + +```shell +tox -e py37-extra,py310-extra +``` + +(this may take a long time the first time, because NumPy and Pandas will +have to be installed in the new virtual environments) + +To fix code formatting: + +```shell +tox -e lint +``` + +See `tox.ini` file to learn how to use to test +individual Python versions. + +Contributors +------------ + +Sergey Astanin, Pau Tallada Crespí, Erwin Marsi, Mik Kocikowski, Bill +Ryder, Zach Dwiel, Frederik Rietdijk, Philipp Bogensberger, Greg +(anonymous), Stefan Tatschner, Emiel van Miltenburg, Brandon Bennett, +Amjith Ramanujam, Jan Schulz, Simon Percivall, Javier Santacruz +López-Cepero, Sam Denton, Alexey Ziyangirov, acaird, Cesar Sanchez, +naught101, John Vandenberg, Zack Dever, Christian Clauss, Benjamin +Maier, Andy MacKinlay, Thomas Roten, Jue Wang, Joe King, Samuel Phan, +Nick Satterly, Daniel Robbins, Dmitry B, Lars Butler, Andreas Maier, +Dick Marinus, Sébastien Celles, Yago González, Andrew Gaul, Wim Glenn, +Jean Michel Rouly, Tim Gates, John Vandenberg, Sorin Sbarnea, +Wes Turner, Andrew Tija, Marco Gorelli, Sean McGinnis, danja100, +endolith, Dominic Davis-Foster, pavlocat, Daniel Aslau, paulc, +Felix Yan, Shane Loretz, Frank Busse, Harsh Singh, Derek Weitzel, +Vladimir Vrzić, 서승우 (chrd5273), Georgy Frolov, Christian Cwienk, +Bart Broere, Vilhelm Prytz, Alexander Gažo, Hugo van Kemenade, +jamescooke, Matt Warner, Jérôme Provensal, Kevin Deldycke, +Kian-Meng Ang, Kevin Patterson, Shodhan Save, cleoold, KOLANICH, +Vijaya Krishna Kasula, Furcy Pin, Christian Fibich, Shaun Duncan, +Dimitri Papadopoulos. + diff --git a/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/RECORD b/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..1f783983af4e517177adbaac403f0d941bf8fd99 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/RECORD @@ -0,0 +1,12 @@ +../../../bin/tabulate,sha256=MhV53gXjpOgn3Ye80-jARfmBkGS00REhRc5I6_VG-wk,235 +tabulate-0.9.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +tabulate-0.9.0.dist-info/LICENSE,sha256=zfq1DTfY6tBkaPt2o6uvzQXBZ0nsihjuv6UP1Ix8stI,1080 +tabulate-0.9.0.dist-info/METADATA,sha256=8oAqreJhIJG0WVHyZa8pF0-QwyNvaMyMzetkaUHmKWk,34132 +tabulate-0.9.0.dist-info/RECORD,, +tabulate-0.9.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92 +tabulate-0.9.0.dist-info/entry_points.txt,sha256=8DmChBYma2n4UqC1VkkKbD5Nu4MrdZasURoeTtG0JVo,44 +tabulate-0.9.0.dist-info/top_level.txt,sha256=qfqkQ2az7LTxUeRePtX8ggmh294Kf1ERdI-11aWqFZU,9 +tabulate/__init__.py,sha256=X3rwoo_NcTuDDJc4hnWUX6jElQsFtY-NGHyQCldS1X0,95290 +tabulate/__pycache__/__init__.cpython-310.pyc,, +tabulate/__pycache__/version.cpython-310.pyc,, +tabulate/version.py,sha256=QVVpjnTor93ym-Tb6Y_XtL_6pmQ3MtoNy3Q6I0o3Yqg,181 diff --git a/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/WHEEL b/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..becc9a66ea739ba941d48a749e248761cc6e658a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.37.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/entry_points.txt b/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..1efc880fa41d55743166d009c0a7368ba2493679 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +tabulate = tabulate:_main diff --git a/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/top_level.txt b/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..a5d51591ebf67bc53acb1c8481da364dae742a02 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/top_level.txt @@ -0,0 +1 @@ +tabulate